【问题标题】:Add exp/power trend line to a ggplot将 exp/power 趋势线添加到 ggplot
【发布时间】:2012-05-10 06:34:10
【问题描述】:

我想在我的绘图中添加一条指数(+ 幂)(趋势)线。我正在使用 ggplot2 包。

我有这样的东西(只是有更多的数据):

require(ggplot2)

df <-read.table("test.csv", header = TRUE, sep = ",")
df
    meta temp
1  1.283    6
2  0.642    6
3  1.962    6
4  8.989   25
5  8.721   25
6 12.175   25
7 11.676   32
8 12.131   32
9 11.576   32

ggplot(df, aes(temp, meta)) + 
    ylab("Metabolism") + xlab("Temperature") +
    geom_point() + 
    theme_bw() + 
    scale_x_continuous(limits = c(0, 35)) + 
    scale_y_log10()

我知道这应该用指数函数来表示 - 所以我的问题是我如何才能找到最佳的“指数”拟合?同样的,是否也可以做一个power-fit?

stat_smooth() 函数是否有这个机会,或者我应该使用ggplot2 包中的其他函数?

【问题讨论】:

  • 欢迎来到 SO。 +1 用于发布代码和示例数据。

标签: r ggplot2


【解决方案1】:

您可以通过传递两个参数来指定要适合的模型作为stat_smooth 的参数:

  • 方法,例如method="lm"
  • 型号,例如model = log(y) ~ x

ggplot2 首先进行比例转换,然后拟合模型,因此在您的示例中,您只需添加

+ stat_smooth(method="lm")

到你的情节:

library(ggplot2)
ggplot(df, aes(temp, meta)) + 
    ylab("Metabolism") + xlab("Temperature") +
    geom_point() + 
    theme_bw() + 
    scale_x_continuous(limits = c(0, 35)) + 
    scale_y_log10() +
    stat_smooth(method="lm")


同样,拟合和绘制功率曲线就像将 x 比例更改为对数一样简单:

ggplot(df, aes(temp, meta)) + 
    ylab("Metabolism") + xlab("Temperature") +
    geom_point() + 
    theme_bw() + 
    scale_x_log10() + 
    scale_y_log10() +
    stat_smooth(method="lm")

【讨论】:

  • 非常感谢!很好,ggplot 通过“它自己”弄清楚当轴发生变化时使用什么样的模型。我还有一个问题。是否有可能从拟合中得到 R^2 值?在正常的线性图中,我只会使用: fit
猜你喜欢
  • 1970-01-01
  • 2019-06-15
  • 1970-01-01
  • 2016-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-17
相关资源
最近更新 更多