简体   繁体   中英

Legend in barplot with ggplot2

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM