Show legend for bar plot in ggplot

2019-08-03 17:11发布

问题:

How do I show legend for the following ggplot bar plot?

tmp <- data.frame(group = LETTERS[1:10], id = 10:1, a = runif(10), b = runif(10))

ggplot(tmp) + geom_bar(aes(x = reorder(group, id), a + b, group = 1), stat = 'identity')

Update: I have two charts arranged using grid.arrange from gridExtra. Both charts have the same number of bars, but one has legend. I thought that by adding any legend to the second chart, I will align the bars (make width of plot area of both plots the same):

tmp <- data.frame(group = LETTERS[1:10], id = 10:1, 
                  a = runif(10), b = runif(10), c = rnorm(10))

p1 <- ggplot(tmp) + geom_bar(aes(x = reorder(group, id), c, fill = a), stat = 'identity')
p2 <- ggplot(tmp) + geom_bar(aes(x = reorder(group, id), a + b, group = 1), stat = 'identity')

library(gridExtra)

grid.arrange(p1, p2, heights = c(2, 1) )

Now, it looks like this:

回答1:

You can try something like this for p2, which will create a new legend for the bottom graph.

p2 <- ggplot(tmp) + geom_bar(aes(x = reorder(group, id), a + b, group = 1, fill = 0), stat = 'identity') +
    guides(fill=guide_legend(title="Title"))


回答2:

This is what i needed

 guides(fill=guide_legend(title="Title"))

Thanks