如何使用ggplot向多个直方图添加图例?

时间:2016-04-28 15:43:51

标签: r ggplot2 histogram legend

我正在尝试向图表添加图例,但它不起作用。 你有什么想法 ?

这是我的代码:

  ggplot(data =stats_201507_AF ) +
  geom_histogram(aes(gross_ind),fill="dodgerblue3", show.legend =T,bins=25)+
  geom_histogram(aes(net_ind),fill="springgreen4",show.legend = T,bins=25) +
  geom_histogram(aes(tax_ind),fill="gold2",show.legend = T, bins=25) +
  xlab("Indices")+
  scale_colour_manual(values=c("dodgerblue3","springgreen4","gold2"))

我想要对每个具有相应颜色的直方图进行描述。

提前多多感谢

1 个答案:

答案 0 :(得分:2)

如果您不想重塑数据,请执行以下操作:

ggplot(iris) +
  geom_histogram(aes(x = Sepal.Length, fill = "Sepal.Length"), 
                 position = "identity", alpha = 0.5) +
  geom_histogram(aes(x = Sepal.Width, fill = "Sepal.Width"), 
                 position = "identity", alpha = 0.5) +
  scale_fill_manual(values = c(Sepal.Length = "blue",
                               Sepal.Width = "red"))

关键是您需要将内容映射到fill内的aes。当然,将数据重新整形为长格式(实际上有一列要映射到fill)通常更可取。