1
votes

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:

enter image description here

2
@MrFlick I oversimplified my problem, added more details.Tomas Greif
Well, ggplot doesn't allow you to make up legends for things that aren't actually in the plot. The easiest thing would just to be to add fill = a for the second plot as well.MrFlick
...or you could move the first legend to the top or bottom of the first plot.joran

2 Answers

2
votes

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

This is what i needed

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

Thanks