10

我制作了一个简单的经典情节,ggplot2其中两个图表合二为一。但是,我正在努力展示传奇。它没有显示传奇。我没有使用融化和重塑的方式,我只是使用经典的方式。下面是我的代码。

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)

数据框是:

 A,res1,res2
 1,11,25
 2,29,40
 3,40,42
 4,50,51
 5,66,61
 6,75,69
 7,85,75

关于如何显示上图的图例有什么建议吗?

4

1 回答 1

12

ggplot2中,为您设置的每个美学 ( ) 显示图例aes;如group, colour, shape. 为此,您必须以以下形式获取数据:

A variable value
1     res1    11
...    ...    ...
6     res1    85
7     res2    75

您可以reshape2使用 using来完成此操作melt(如下所示):

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)

例如,如果您不想要colour积分,则只需colour=variablegeom_point(aes(.)). 有关更多图例选项,请关注this link

在此处输入图像描述

于 2013-03-14T19:35:09.520 回答