Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot legend slashes

Tags:

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

enter image description here

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.

enter image description here

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?

like image 855
user1317221_G Avatar asked May 18 '12 23:05

user1317221_G


2 Answers

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, enter image description here 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.

like image 122
Eric Fail Avatar answered Oct 07 '22 14:10

Eric Fail


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.

like image 42
Tyler Rinker Avatar answered Oct 07 '22 15:10

Tyler Rinker