This must have annoyed someone in the past so excuse me if this is a duplicate and I will remove it. Slashes across legends when using geom_bar
can be annoying. e.g.:
x <- c("a","b")
y <- c(1,2)
df <- as.data.frame(cbind(x,y))
a <- ggplot(df,aes(x=x,y=y,fill=x))
a + geom_bar(colour="black") + scale_fill_manual(values=c("white", "black"))
When I use coloured bars I use this work around, plotting bars without colours first e.g.
a + geom_bar() + geom_bar(colour="black",show_guide=FALSE) +
scale_fill_manual(values=c("white", "black"))
However when the fill is white this leaves an unsatisfying empty white box in the legend without a border. e.g.
I have fixed this in the past manually using graphics software but now I think this must be of use to enough people to ask a question here. Can we make ggplot
plot the legend with the black outline only but without the slash?
this,
a + geom_bar() + geom_bar(colour="black",show_guide=FALSE) +
scale_fill_manual(values=c("white", "black")) +
opts(legend.key = theme_rect(fill = 'black'))
gave me this, thanks to this site.
Alos, you get the same result using colour
instead of fill
(it might be argued that one is better than).
a + geom_bar() + geom_bar(colour="black",show_guide=FALSE) +
scale_fill_manual(values=c("white", "black")) +
opts(legend.key = theme_rect(colour = 'black'))
Important note: In modern versions of ggplot2 opts
has been deprecated and replaced with theme
, and theme_rect
has been replaced by element_rect
.
No that's what gives it it's outline. If you use a gray instead of white (with your trick) it's more distinguishable. You could also add background color to the legend to make it more distinguishable and keep it white. See the bottom of this page for more detail:
http://wiki.stdout.org/rcookbook/Graphs/Legends%20(ggplot2)/
i wish there were a less hackish way to do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With