将图例添加到R

时间:2017-01-30 17:04:47

标签: r plot ggplot2 legend

我想在同一个绘图中绘制两个数据集,并添加一个图例以在R中使用ggplot2。我的数据集看起来像这样:

df1 = data.frame(
  DateTime = c("20/06/2016  09:11:01", "20/06/2016  10:11:01","20/06/2016  11:11:01","20/06/2016  12:11:01", "20/06/2016  13:11:01", "20/06/2016  14:11:01","20/06/2016  15:11:01", "20/06/2016  16:11:01", "20/06/2016  17:11:01","20/06/2016  18:11:01","20/06/2016  19:11:01", "20/06/2016  20:11:01")), 
  price1 = c(0.072, 0.072,  0.072,  0.074,  0.074,  0.072,  0.072,  0.072,  0.074,  0.075,  0.074, 0.074)
      )

df2 = data.frame(
DateTime = c("25/05/2016  00:05:00","31/05/2016  00:05:00","07/06/2016  00:05:00","14/06/2016  00:05:00","21/06/2016  00:05:00","29/06/2016  00:05:00","06/07/2016  00:05:00","14/07/2016  00:05:00","21/07/2016  00:05:00","26/07/2016  00:05:00","02/08/2016  00:05:00","09/08/2016  00:05:00"),
    price2 = c(0.54,    0.5,    0.49,   0.83,   0.61,   0.54,   0.38,   0.4,    0.29,   0.27,   0.6,    0.51)
                )

df1$DateTime1 = strptime(as.character(df1$DateTime), "%d/%m/%Y %H:%M:%S")
df2$DateTime2 = strptime(as.character(df2$DateTime), "%d/%m/%Y %H:%M:%S")

我用来制作情节的代码和图例如下

ggplot() + 
  geom_point(data = df1, aes(x = DateTime1, y = price1),colour="red", size = 2) +   
  geom_point(data = df2, aes(x = DateTime2, y = price2),colour="blue", size = 1) +
  xlab('Date') + ylab('Price') + ggtitle("Plot of prices") + 
  theme(plot.title = element_text(lineheight=.8, face="bold")) + 
  scale_colour_manual("", breaks = c("Price1", "Price2"),
                      values = c("Price1"="red", "Price2"="blue"))

输出低于

Plot of prices in both datasets for different dates

虽然我得到了我想要的情节,但传奇似乎没有出现在图表中,我没有得到任何错误。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

在ggplot中获取正确的图例,您需要指定相应的美学。

这是具有颜色手册的明确颜色名称的解决方案:

ggplot() + 
  geom_point(data = df1, aes(x = DateTime1, y = price1, color = 'df1'), size = 2) +   
  geom_point(data = df2, aes(x = DateTime2, y = price2, color = 'df2'), size = 1) +
  xlab('Date') + ylab('Price') + ggtitle("Plot of prices") + 
  theme(plot.title = element_text(lineheight=.8, face="bold")) + 
  scale_colour_manual("", values = c("df1"="red", "df2"="blue"))

答案 1 :(得分:0)

只需移动colours中的aes,将其包含在colour图例中即可:

ggplot() + 
  geom_point(data = df1, aes(x = DateTime1, y = price1, colour="red"), size = 2) +   
  geom_point(data = df2, aes(x = DateTime2, y = price2, colour="blue"), size = 1) +
  xlab('Date') + ylab('Price') + ggtitle("Plot of prices") + 
  theme(plot.title = element_text(lineheight=.8, face="bold")) +
  scale_colour_manual(values = c("blue", "red"))

enter image description here