如何使用ggplot向多个直方图添加图例? [英] How to add a legend to the multiple histograms with ggplot?

查看:219
本文介绍了如何使用ggplot向多个直方图添加图例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to add a legend to the graph but it doesn't work. Do you have any ideas ?

这是我的代码:

  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"))

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

I wanted a description for every histogram with a corresponding colour.

非常感谢

推荐答案

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

If you don't want to reshape your data, just do this:

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"))

关键是您需要将某些内容映射到aes中的fill.当然,通常最好将数据重整为长格式(并因此实际上具有一列要映射到fill的列).

The key is that you need to map something to fill inside aes. Of course, reshaping your data to long format (and actually having a column to map to fill as a result) is usually preferable.

这篇关于如何使用ggplot向多个直方图添加图例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆