【问题标题】:R add legend to ggplot2R将图例添加到ggplot2
【发布时间】:2019-08-04 01:11:00
【问题描述】:

我想绘制几个密度,其中图例应显示每个密度函数的参数。不幸的是,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 的新手,以下线程似乎相关,但不幸的是没有帮助我解决它(here 和here)

【问题讨论】:

  • 而不是添加三个线层到你的情节你应该重塑你的数据从宽到长,添加一个geom_line(),然后将生成的“关键”变量映射到color美学 - 这个在aes() 内完成。您可以在这里找到更多信息:Plotting two variables as lines using ggplot2 on the same graph
  • 好的,但ggplot 的目的不是处理数据帧吗?我的意思是它应该能够处理宽,不是吗?
  • 重点是使用长格式的数据帧。
  • 是的,重点是使用数据框,但让ggplot2 与众不同的是其名称中的“图形语法”。一般的ggplot 范式是将变量映射到美学,例如映射到颜色的观察组。如果您按照教程进行操作,他们可能都是这样操作的。

标签: r ggplot2


【解决方案1】:

正如 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 功能更多地格式化绘图。 检查这个:How to melt R data.frame and plot group by bar plot

【讨论】:

  • 将标签从 y1 更改为“\alpha = 1”的最佳方法是什么
  • 在融合数据之前,根据需要更改变量名称。在这里,它将是新列“var”。装箱后,替换“y1”,然后融化并绘图。应该这样做。
猜你喜欢
  • 2019-03-05
  • 2018-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多