【问题标题】:How do I add an exponential trendline to various scatter plots in ggplot2?如何向 ggplot2 中的各种散点图添加指数趋势线?
【发布时间】:2021-02-24 08:18:09
【问题描述】:

第一次在这里发帖。

我似乎找不到一种简单的方法来将指数趋势线添加到我的各种散点图中。我有 8 种树种,它们的高度(以米为单位)和胸高的直径(简称 DBH,以厘米为单位)的关系不同。现在我已经设法为每种树种绘制了不同的散点图,但我似乎找不到添加指数趋势线的方法。 Scatter Plot of DBH - Height Relationship per Tree type

我使用的代码如下:

ggplot(data, aes(Height__m_,DBH__cm_)) +
  geom_point(aes(color = Species)) +
  facet_wrap(~Species, ncol = 4, nrow = 2) +
  labs(title = "DBH - Height Relationship", y = "Height (m)", x = "DBH (cm)")

当我添加geom_smooth 函数时,我似乎无法添加指数趋势线,因为我知道这些类型的关系最适合。我尝试使用的代码是:

 geom_smooth(method = "nls", formula =  y ~ a * exp(b * x), aes(color = "Exponential"),
          se = FALSE, start = c(a = 1, b= 1))`

如果还有可能添加 R2 值,那也将受到欢迎。 我将不胜感激!

【问题讨论】:

  • 在您尝试geom_smooth 函数后得到了什么输出或错误?
  • 大约有 17 个警告,但它们的状态都相同:Computation failed in stat_smooth(): number of iterations exceeded maximum of 50 14: In (function (formula, data = parent.frame(), start, control = nls.control(), ... : No starting values specified for some parameters. Initializing ‘a’, ‘b’ to '1.'. Consider specifying 'start' or using a selfStart model'

标签: r ggplot2 exponential


【解决方案1】:

我们没有您的数据,但这里有一个使用内置 Orange 数据集的示例。在这种情况下,将较低的起始 b 值设置为 0.001 会删除警告消息 (1: Computation failed in stat_smooth(): 奇异梯度 阻止找到任何可行的拟合。

ggplot(Orange, aes(age,circumference)) +
  geom_point() +
  facet_wrap(~Tree, nrow = 2) +
  stat_smooth(method = 'nls', 
            method.args = list(start = c(a=1, b=0.001)), 
            formula = y~a*exp(b*x), colour = 'black', se = FALSE)

【讨论】:

  • 这样做了,我将 b 值更改为 0.001,它现在显示指数趋势。
  • 不错的答案,+1,虽然我猜样本数据的更合适的模型可能是线性模型......;P
猜你喜欢
  • 2014-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-10
  • 1970-01-01
  • 2021-07-04
  • 1970-01-01
  • 2020-02-26
相关资源
最近更新 更多