ggplot2: Decadal Trend Rates in Global Temperature
July 12, 2009
Charts & Graphs blog has posted GISS Anomaly Trend Chart with Decadal Trend Rates created using base graphics in R and has invited me to prepare a ggplot2 version of the same.
Data Preparation
- The data import process is described in a more detail in a previous post.
- Convert years and months into yearmon class.
- Calculate decades from annual data and coefficients by decade.
> library(ggplot2) |
> library(zoo) > dfm$yearmo <- with(dfm, paste(Month, Year)) > dfm$yearmo <- as.yearmon(dfm$yearmo, "%b %Y") > dfm <- dfm[order(dfm$yearmo), ] > dfm$decade <- dfm$Year%/%10 * 10 > dfm <- ddply(dfm, .(decade), transform, a = coef(lm(value/100 ~ + yearmo))[1]) |
Plotting
First setup the graph
> p <- ggplot(dfm, aes(yearmo, value/100)) + opts(legend.position = "none",
+ title = "GISS Temperature Anomaly with Trend Rates By Decade") +
+ xlab("") + ylab("GISS Temperature Anomaly - C") +
+ theme_bw()
|

Plot annual temperature anomaly
> p + geom_line(colour = "grey80") |

Add overall trend
> last_plot() + geom_smooth(method = lm, se = F, colour = "green") |

Add trend by decade
> last_plot() + geom_smooth(aes(group = factor(decade), + colour = (a > 0)), method = lm, se = F) |

Fix colour mapping
> last_plot() + scale_colour_manual(values = c("blue",
+ "red"))
|

Remove Legend
> last_plot() + opts(legend.position = "none") |

Add text labels
> trend_rate <- ddply(dfm, .(decade), summarise, b = coef(lm(value/100 ~ + yearmo))[2] * 100) > last_plot() + geom_text(data = trend_rate, aes(decade + + 5, -0.9, label = round(b, 1), colour = (b <= 0)), + size = 4) |

Annotate the graph
> b_flm <- with(dfm, round(coef(lm(value ~ yearmo)), 3))[2] |
> last_plot() + annotate(x = 1880, y = 0.7, geom = "text",
+ hjust = 0, label = paste("Overall Trend - oC/C \n",
+ b_flm), size = 4, colour = "darkgreen") + annotate(x = 1920,
+ y = -0.8, geom = "text", hjust = 0, label = "Decade Trend Rate -oC per Century",
+ size = 4, colour = "darkgreen")
|

2 Comments
leave one →
A triumph! Thank you, especially, for the lesson in the use of ddply().