Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add exp/power trend line to a ggplot

Tags:

r

ggplot2

I want to add a exponential (+ power) (trend) line to my plot. I am using ggplot2 package.

I have something like this (just with much more data):

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

I know that this should be expressed with an exponential function - so my question is how I can ad the best 'exponential' fit? Likewise, is it possible to make a power-fit too?

Does the stat_smooth() function have this opportunity, or are there other functions in ggplot2 package I should use?

like image 300
PJensen Avatar asked May 10 '12 06:05

PJensen


1 Answers

You can specify the model to fit as an argument to stat_smooth by passing two arguments:

  • method, e.g. method="lm"
  • model, e.g. model = log(y) ~ x

ggplot2 first does the scale transformation and then fits the model, so in your example you simply have to add

+ stat_smooth(method="lm")

to your plot:

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

enter image description here


Similarly, fitting and plotting a power curve is as simple as changing your x-scale to log:

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

enter image description here

like image 78
Andrie Avatar answered Sep 26 '22 02:09

Andrie