繁体   English   中英

R将图例添加到ggplot2

[英]R add legend to ggplot2

我想绘制几个密度,图例应显示每个密度函数的参数。 不幸的是, ggplot2不包含图例(这很奇怪,在本教程中它是...)

产生资料:

x <- seq(from=-5, to=5, by=0.1)
y1 = dlaplace(x,0,0.5)
y2 = dlaplace(x,0,1)
y3 = dlaplace(x,0,2)
df = data.frame(x,y1,y2,y3)

情节

ggplot(data=df, aes(x=x))+
  geom_line(data= df, aes(y=y1), color="red")+
  geom_line(data= df,aes(y=y2), color="blue")+
  geom_line(data= df,aes(y=y3), color="green")+
  ggtitle("Gamma distribution density function") +ylab("density")+ xlab("x")+
  theme(legend.position = "bottom")+
  guides(fill = guide_legend(reverse=TRUE))

我是ggplot ,以下线程似乎相关,但不幸的是,这并没有帮助我解决问题( 在这里这里

正如Markus建议的那样,您需要通过将数据转换为长格式。 使用来自reshape2 melt功能。 它看起来应该像这样:

plotdf <- as.data.frame(t(df))
plotdf$var <- rownames(plotdf)
plotdf <- melt(plotdf[-c(1),], id.vars = "var")
print(ggplot(plotdf, aes(value, variable, colour = var)) + geom_point()+ scale_y_discrete(breaks=seq(0, 2, by = 0.5)) +
      ggtitle("Gamma distribution density function") +ylab("density")+ xlab("x")+
        theme(legend.position = "bottom")+
        guides(fill = guide_legend(reverse=TRUE)))

输出:

这是输出图

可以使用其他ggplot功能进一步格式化图。 检查以下内容: 如何融合R data.frame和按条形图分组

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM