【问题标题】:Add legend to scatterplots from different datasets ggplot2 in R将图例添加到来自 R 中不同数据集 ggplot2 的散点图
【发布时间】:2017-01-30 17:04:47
【问题描述】:

我有两个数据集,我想在同一个图中绘制并添加一个图例以在 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"))

输出如下

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

【问题讨论】:

  • rbind 你的两个数据集(带有 id 列),然后只有一个 geom_point 与 aes 设置为颜色

标签: r plot ggplot2 legend


【解决方案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"))

【讨论】:

    【解决方案2】:

    这应该可以工作,只需将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"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-04
      • 2019-05-15
      • 2018-11-12
      • 2019-05-08
      • 2017-11-16
      • 2016-08-10
      • 2019-03-05
      • 2015-12-14
      相关资源
      最近更新 更多