R将图例添加到ggplot2

时间:2019-03-13 11:11:34

标签: r 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的新手,以下线程似乎很相关,但很遗憾,这并没有帮助我解决问题(herehere

1 个答案:

答案 0 :(得分:1)

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

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)))

输出:

Here's the output plot

可以使用其他ggplot功能来进一步格式化绘图。 检查以下内容:How to melt R data.frame and plot group by bar plot

相关问题