如何向 ggplot2 中的各种散点图添加指数趋势线?
How do I add an exponential trendline to various scatter plots in ggplot2?
第一次在这里发帖。
我似乎找不到一种简单的方法来向我的各种散点图添加指数趋势线。我有 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值,那也欢迎。
我将不胜感激!
我们没有您的数据,但这里有一个使用内置 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)
第一次在这里发帖。
我似乎找不到一种简单的方法来向我的各种散点图添加指数趋势线。我有 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值,那也欢迎。 我将不胜感激!
我们没有您的数据,但这里有一个使用内置 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)