ggplot2:如何显示图例 [英] ggplot2: how to show the legend
问题描述
我用 ggplot2
做了一个简单的经典情节,这是一个两个图表。不过,我正在努力展示这个传奇。它没有显示图例。我没有使用融化和重塑的方式,我只是使用经典的方式。以下是我的代码。
df< -read.csv(testDataFrame.csv)
图< - ggplot (df,aes(A))+
geom_line(aes(y = res1),color =1)+
geom_point(aes(y = res1),size = 5,形状= 12)+
geom_line(aes(y = res2),color =2)+
geom_point(aes(y = res2),size = 5,shape = 20 )+
scale_colour_manual(values = c(red,green))+
scale_x_discrete(name =X axis)+
scale_y_continuous(name =Y (Test)+
#scale_shape_discrete(name =results,labels = c(Res1,Res2),solid = TRUE)
打印(图表)
数据框为:
A,res1,res2
1,11,25
2,29,40
3,40,42
4, 50,51
5,66,61
6,75,69
7,85,75
任何有关如何显示上图图例的建议?
c $ c> ggplot2 ,每个审美都会显示图例( aes
)你设置;如 group
, color
, shape
。要做到这一点,您必须以表格形式获取数据:
变量值
1 res1 11
... ... ...
6 res1 85
7 res2 75
您可以使用 melt
(如下所示)使用 reshape2
完成此操作:
require(reshape2)
require(ggplot2)
ggplot(dat = melt(df,id (颜色=变量,组=变量))+
geom_point(aes(color = variable,例如,如果你不这样做的话,那么你可以使用下面的代码想要 color 为点,然后从 geom_point(aes(。))中删除 color = variable
)
。有关更多图例选项,请按照 此链接 code>
。
I made a simple classic plot with ggplot2
which is two graphs in one. However, I'm struggling in showing the legend. It's not showing the legend. I didn't use the melt and reshape way, I just use the classic way. Below is my code.
df<-read.csv("testDataFrame.csv")
graph<- ggplot(df,aes(A)) +
geom_line(aes(y=res1), colour = "1")+
geom_point(aes(y=res1),size = 5,shape=12)+
geom_line(aes(y=res2), colour = "2")+
geom_point(aes(y=res2), size = 5, ,shape=20)+
scale_colour_manual(values=c("red","green"))+
scale_x_discrete (name="X axis")+
scale_y_continuous(name="Y-axis")+
ggtitle("Test")+
#scale_shape_discrete(name ="results",labels=c("Res1", "Res2"),solid = TRUE)
print(graph)
the data frame is:
A,res1,res2
1,11,25
2,29,40
3,40,42
4,50,51
5,66,61
6,75,69
7,85,75
Any suggestion on how to show the legend for the above graph?
解决方案 In ggplot2
, legends are shown for every aesthetic (aes
) you set; such as group
, colour
, shape
. And to do that, you'll have to get your data in the form:
A variable value
1 res1 11
... ... ...
6 res1 85
7 res2 75
You can accomplish this with reshape2
using melt
(as shown below):
require(reshape2)
require(ggplot2)
ggplot(dat = melt(df, id.var="A"), aes(x=A, y=value)) +
geom_line(aes(colour=variable, group=variable)) +
geom_point(aes(colour=variable, shape=variable, group=variable), size=4)
For example, if you don't want colour
for points, then just remove colour=variable
from geom_point(aes(.))
. For more legend options, follow this link
.
这篇关于ggplot2:如何显示图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!