2016-04-28 127 views
1

我想添加图例的图例,但它不起作用。 你有什么想法吗?如何使用ggplot将图例添加到多个直方图?

这里是我的代码:

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

我想用一个相应颜色的每个直方图的描述。

感谢很多提前

+0

您使用ggplot的方式是将数据以正确的格式绘制出来,这可能还没有完成。您可能需要将数据从广泛转换为长数据,但如果没有可用于演示数据的可重复示例,关于如何做到这一点的详细信息将无法解释。 – joran

+0

要添加图例,您需要确定填充位于'aes()'映射内的变量。要做到这一点,您必须重新构建数据框架。 –

+0

[将图例添加到ggplot2线图]可能重复(http://stackoverflow.com/questions/10349206/add-legend-to-ggplot2-line-plot) – aosmith

回答

1

如果你不想重塑你的数据,只是这样做:

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

的关键是,你需要一些映射到fillaes。当然,将数据转换为长格式(实际上有一列作为结果映射到fill)通常是可取的。