R中的ggplot2和spline() - 错误:`data`必须是一个数据框,或者是由`fortify()强制执行的其他对象

问题描述 投票:1回答:1

可重现的数据生成示例:

n <- 9
x <- 1:n
y <- rnorm(n)
data <- data.frame(x, y)

我知道如何使用没有ggplot2的样条曲线绘制数据。

plot(x, y, main = paste("spline[fun](.) "))
lines(spline(x, y))

情节图像在这里:

enter image description here

但是,我想用ggplot2绘制样条曲线。这是一个代码示例:

ggplot(aes(x = x, y = y)) + geom_point() + geom_line(spline(data))

我得到的错误是:错误:data必须是数据框,或fortify()强制执行的其他对象,而不是具有class uneval的S3对象您是否不小心将aes()传递给data参数?

如果我使用,会抛出相同的错误

ggplot(aes(data, x = x, y = y)) + geom_point() + geom_line(spline(data))

要么

ggplot(aes(x = x, y = y)) + geom_point() + geom_line(spline(x, y))

要么

ggplot(aes(x = data$x, y = data$y)) + geom_point() + geom_line(spline(data$x,data$y))

以下一个给出了不同的错误。它在here进行了探索,但我想绘制一个样条曲线并且不确定如何将解决方案应用于我的情况。

library(dplyr)
data %>% ggplot(aes(x = x, y = y)) + geom_point() + geom_line(spline(x, y))

错误:mapping必须由aes()创建

r ggplot2 spline
1个回答
1
投票

可能的方法:

ggplot(data, aes(x = x, y = y)) + 
  geom_point() + 
  geom_line(data = data.frame(spline(x, y))) #+
  #ggthemes::theme_base()

54942745

问题是:spline返回list,你应该将它转换为data.frame,就是这样。

© www.soinside.com 2019 - 2024. All rights reserved.