1
votes

I have a barplot in ggplot2 with 12 bars (non stacked) in which every even bar has one color and odd bars have another color, but I can't figure out how to legend just the color of the bars. Even though I could reshape my data two just have this two categories they have to be displayed from 1 to 12. For plotting I created a data frame with 5 columns in which the 1st is 1:12, the 2nd the heights of the bars, 3rd and 4th the standard errors and 5th the color of each bar.

and the code I used:

per.block.plot<-data.frame(block,means,std.up,std.down,color.block)
performance.per.block.plot<-ggplot(per.block.plot,aes(block,means)) +
     geom_bar(stat="identity",fill=color.block) + xlab("Block number") +
     ylab("Error rate") + ggtitle("Performance per block") + 
     geom_errorbar(aes(ymin=std.down, ymax=std.up),width=.2) + 
     theme_classic() 

Thanks in advance!

1
Can you add your data? For instance, by copy-pasting the output of dput(per.block.plot)? - Heroka
But generally to create a legend, you need to put 'fill' inside the aes, either in the general call to ggplot or inside the call to geom_bar. - Heroka
Yes it works now! Thanks, really, it was really simple in the end :) - Ana
Can you accept @Katrin's answer then? Marks the question as closed. - Heroka

1 Answers

0
votes

As Heroka commented above, fill should be specified in aes() with the variable ... that determines the color of the bars, like so:

performance.per.block.plot<-ggplot(per.block.plot,aes(block,means, fill = ...))

Side hint: spelling the parameters out like aes(x = block, y = means) can help to build the working script you want ;-) Once working, there will still be time to remove these little helpers.