Marking lines in ggplot2 with their gradients and changing legend characteristics

I am looking at the change in maximum temperature per month since 1954-2000 using the data:

http://pastebin.com/37zUkaA4

I decided to plot a graph for each month on the graph for clarity. My code looks like this:

OxTemp$Month <- factor(OxTemp$Month, levels=c("January", "February", "March","April", "May", "June", "August", "September", "October", "November", "December"), ordered=TRUE)

p<-ggplot(OxTemp, aes(x=Year, y=MaxT, group=Month, colour=Season, linetype=Month))

p+geom_smooth(method = 'lm',size = 1, se = F)

      

Which gives me the following plot:

enter image description here

I was wondering if there is a way:

a) Change the colors in the "Month" legend to match the colors in the "Season" legend

b) Make the legends a little wider to make the line types more visible

c) Add a label for each line gradient to the graph so that the slope value is displayed to the right of each line

Many thanks!

+2


source to share


1 answer


OxTemp <- read.table("http://pastebin.com/raw.php?i=37zUkaA4",header=TRUE,stringsAsFactors=FALSE)

library(ggplot2)
OxTemp$Month <- factor(OxTemp$Month, 
                       levels=c("Jan", "Feb", "Mar","Apr", "May", "Jun","Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), ordered=TRUE)
OxTemp$Season <- factor(OxTemp$Season, 
                       levels=c("Spring", "Summer", "Autumn", "Winter"), ordered=TRUE)

library(plyr)
slopedat <- ddply(OxTemp,.(Month),function(df) data.frame(slope=format(signif(coef(lm(MaxT~Year,data=df))[2],2),scientific=-2),
                                                          y=max(predict(lm(MaxT~Year,data=df)))))



p <- ggplot(OxTemp, aes(x=Year, y=MaxT)) + 
  geom_smooth(aes(group=Month, colour=Season, linetype=Month),method = 'lm',size = 1, se = F) +
  scale_colour_manual(values=c("Winter"= 4, "Spring" = 1, "Summer" = 2,"Autumn" = 3)) +
  geom_text(data=slopedat,aes(x=2005,y=y,label=paste0("slope = ",slope))) +
  scale_x_continuous(limits=c(1950, 2010)) +
  guides(linetype=guide_legend(override.aes=list(colour=c("Jan"= 4, "Feb" = 4, "Mar" = 1,
                                                          "Apr" = 1, "May" = 1, "Jun" = 2,
                                                          "Jul" = 2, "Aug" = 2, "Sep" = 3, 
                                                          "Oct" = 3, "Nov" = 3, "Dec" = 4)),keywidth=5))

print(p)

      



enter image description here

+4


source







All Articles