使用ggplot根据线条颜色设置图例

时间:2016-07-13 14:12:24

标签: r ggplot2

我有一个情节 enter image description here

使用ggplot,如何设置仅带有两个标签的图例,即名称为“预测间隔”的红线和名称为“拟合线”的蓝线

我使用了以下R

dfs <- data.frame("x"=1:50,"fit" = rnorm(50,30,4),"upper"=rnorm(50,30,4)+15, "lower"=rnorm(50,30,4)-15)
df_melt <- reshape2::melt(dfs,id="x")
g <- ggplot(df_melt,aes(x=x,y=value,colour=variable)) + geom_line(linetype=5)
g <- g + scale_colour_manual(values=c("blue","red","red")) 
g <- g +  theme_grey(base_size = 16) + theme(axis.text=element_text(colour = "black",size = 12))
g

1 个答案:

答案 0 :(得分:4)

您只需添加一个包含2个值的新列(&#34;预测间隔&#34;或&#34;拟合线&#34;)

enter image description here

# Add a new group column 
df_melt$group[df_melt$variable == "fit"] <- "fit line"
df_melt$group[df_melt$variable != "fit"] <- "prediction intervals"

# don't forget `group = variable`
g <- ggplot(df_melt, aes(x = x, y = value, colour = group, group = variable)) +
geom_line(linetype=5)
g <- g + scale_colour_manual(values = c("blue" ,"red", "red")) 
g <- g +  theme_grey(base_size = 16) + 
theme(axis.text = element_text(colour = "black", size = 12))
g