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

R 如何使用ggplot向多个直方图添加图例?,r,ggplot2,histogram,legend,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(ta

我试图在图表中添加一个图例,但它不起作用。 你有什么想法吗

这是我的密码:

  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"))
我想用相应的颜色描述每个直方图


提前多谢

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

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
)通常更可取。

使用ggplot的方法是将数据以正确的格式进行打印,这可能是您没有做到的。您可能需要将数据从宽转换为长,但如果没有可复制的数据示例(我们可以使用该示例演示),则无法解释如何将数据从宽转换为长。要添加图例,您需要在
aes()
映射中确定填充的变量。要实现这一点,您必须重新构造数据帧。数据帧可能重复