【问题标题】:Unable to get R to display regression line (geom_smooth)?无法让 R 显示回归线(geom_smooth)?
【发布时间】:2020-08-02 07:47:40
【问题描述】:

晚上好,希望有人能帮忙。我整晚都在搞乱 ggplot 包,但由于某种原因,我无法使用 geom_smooth 显示回归线!

我在这里包含了代码,不幸的是,终端实际上​​并没有将其标记为错误,但这也是我被难住的部分原因!我逐行运行它,每一行都没有标志执行。图表本身甚至可以顺利出现,只是缺少回归线!

代码:

library(ggplot2)
ScatterPlot <- ggplot(graph, aes (x= Specimen.date, y= Daily.lab.confirmed.cases)) + geom_point() + geom_smooth(method = lm) + theme(axis.text.x = element_text(angle=90))

ScatterPlot + ylim(0,5000) + labs(x = "Date") + labs(y = "Daily Cases")

输出:

> ScatterPlot <- ggplot(graph, aes (x= Specimen.date, y= Daily.lab.confirmed.cases)) + geom_point() + geom_smooth(method = lm) + theme(axis.text.x = element_text(angle=90))
> ScatterPlot + ylim(0,5000) + labs(x = "Date") + labs(y = "Daily Cases")

geom_smooth() 使用公式'y ~ x'

我也尝试将列转换为数字,但这似乎也不起作用 (x = as.numeric(), y = as.numeric() )。

有什么建议!?

谢谢

迈克尔

【问题讨论】:

  • 试试method = "lm"而不是method = lm
  • 恐怕不高兴,谢谢!
  • 棘手!如果 geom_smooth 不起作用,您可以尝试直接绘制 lm - 请参阅 jim89 的示例:community.rstudio.com/t/insert-regression-model-into-ggplot2/… 祝你好运!
  • 请添加graph的样本数据。
  • 你试过 geom_smooth(method = lm, formula = y~x, se = FALSE)

标签: r ggplot2 regression


【解决方案1】:

好吧,我们终于到了那里。 Mlcyo(请参阅 cmets,谢谢!)取得了大部分进展。至少给了我一个更有帮助的错误。以下是它的修改方式...:

graph[] <- lapply(graph, as.numeric) # Force entire dataframe into numeric type


fit <- lm(Daily.lab.confirmed.cases ~ Specimen.date, data = graph) # Manually generate linear model 

 geom_line(data = fortify(fit), aes(x = Specimen.date, y = .fitted)) # Insert after geom_point()

希望它可以帮助别人!再次感谢 mlcyo,祝您获得博士学位!

M

【讨论】:

  • 您好,很高兴您能够展示情节……但尚不清楚您最初的案例中出了什么问题。您也应该能够使用geom_smooth 显示该行。在将整个数据框强制为数字后,您是否能够获得geom_smooth 绘制线的方式?另外,str(graph) prior 在答案中执行graph[] &lt;- lapply(...) 行的输出是什么?是不是特别是一列不是数字(但应该是)?
  • 很高兴你得到它的工作迈克尔 - 对于你的原始模型,你检查日期对象是否正确转换?昨晚我用 x=date 运行 lm,发生了一些奇怪的事情 - 这里有一些提示:stackoverflow.com/questions/28098324/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-21
  • 1970-01-01
  • 2020-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多