【问题标题】:ggplot2 & spline() in R - Error in : `data` must be a data frame, or other object coercible by `fortify()`R 中的 ggplot2 和 spline() - 错误:`data` 必须是数据框,或其他可被`fortify()` 强制的对象
【发布时间】:2019-03-01 10:32:08
【问题描述】:

数据生成的可重现示例:

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))

此处提供绘图图像:

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

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

我得到的错误是: 错误:data 必须是数据框,或其他可被fortify() 强制转换的对象,而不是类 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】:

    这样做的可能方法:

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

    问题是:spline 返回list,您只需将其转换为data.frame 即可。

    【讨论】:

      猜你喜欢
      • 2018-12-26
      • 1970-01-01
      • 2022-12-10
      • 1970-01-01
      • 2020-07-24
      • 2020-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多