1

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

Here is my code :

  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.

Thanks a lot in advance

scott_lotus
  • 3,171
  • 22
  • 51
  • 69
  • The way you use ggplot is to put the data in the correct format for plotting, which you probably have not done. You will likely need to convert your data from wide to long, but the details on how to do that will be impossible to explain without a reproducible example with data that we can use to demonstrate it. – joran Apr 28 '16 at 15:49
  • To add a legend, you need the variable determining the fill to be within the `aes()` mapping. To accomplish that you'll have to restructure your data frame. – Adam Birenbaum Apr 28 '16 at 15:49
  • 1
    Possible duplicate of [Add legend to ggplot2 line plot](http://stackoverflow.com/questions/10349206/add-legend-to-ggplot2-line-plot) – aosmith Apr 28 '16 at 15:50

1 Answers1

3

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

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.

Roland
  • 127,288
  • 10
  • 191
  • 288