我正在观察每月最高温度的变化,从1954年至2000年使用数据:
为了清晰起见,我决定只在图表上绘制每个月的下划线。我的代码如下:
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)
这给了我以下情节:
我想知道是否有办法:
a)更改“月”图例中的颜色以匹配“季节”图例中的颜色
b)使图例更宽一些,以使线型更加明显
c)在图中添加每条线的渐变标签,以便在每条线的右侧显示斜率值
非常感谢!
答案 0 :(得分:4)
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)