【发布时间】:2018-07-23 22:15:00
【问题描述】:
我试图(未成功)在我的 R ggplot2 图中显示一个图例,其中涉及多个图。我的数据框df和代码如下:
Individuals Mod.2 Mod.1 Mod.3
1 2 -0.013473145 0.010859793 -0.08914021
2 3 -0.011109863 0.009503278 -0.09049672
3 4 -0.006465788 0.011304668 -0.08869533
4 5 0.010536718 0.009110458 -0.09088954
5 6 0.015501212 0.005929766 -0.09407023
6 7 0.014565584 0.005530390 -0.09446961
7 8 -0.009712516 0.012234843 -0.08776516
8 9 -0.011282278 0.006569570 -0.09343043
9 10 -0.011330579 0.003505439 -0.09649456
str(df)
'data.frame': 9 obs. of 4 variables:
$ Individuals : num 2 3 4 5 6 7 8 9 10
$ Mod.2 : num -0.01347 -0.01111 -0.00647 0.01054 0.0155 ...
$ Mod.1 : num 0.01086 0.0095 0.0113 0.00911 0.00593 ...
$ Mod.3 : num -0.0891 -0.0905 -0.0887 -0.0909 -0.0941 ...
ggplot(df, aes(df$Individuals)) +
geom_point(aes(y=df[,2]), colour="red") + geom_line(aes(y=df[,2]), colour="red") +
geom_point(aes(y=df[,3]), colour="lightgreen") + geom_line(aes(y=df[,3]), colour="lightgreen") +
geom_point(aes(y=df[,4]), colour="darkgreen") + geom_line(aes(y=df[,4]), colour="darkgreen") +
labs(title = "Modules", x = "Number of individuals", y = "Mode")
我查找了以下堆栈流线程以及 Google 搜索:
- Merging ggplot2 legend
- ggplot2 legend not showing
- `ggplot2` legend not showing label for added series
- ggplot2 legend for geom_area/geom_ribbon not showing
- ggplot and R: Two variables over time
- ggplot legend not showing up in lift chart
- Why ggplot2 legend not show in the graph
- ggplot legend not showing up in lift chart。 这是 4 天前创建的
这让我意识到让图例出现是一个反复出现的问题,尽管图例通常会自动出现。
我的第一个问题是使用 ggplot 时没有出现图例的原因是什么?二是如何解决这些原因。其中一个原因似乎与多个地块和aes()的使用有关,但我怀疑还有其他原因。
【问题讨论】:
-
如果没有实际的数据框就很难回答。但是,您在 ggplot 中使用的是普通的
plot()语法。这里的关键问题是为 ggplot 准备数据框。如果你能提供你的 df 夹头,我很乐意提供帮助。 -
我已将数据框添加到我的 OP