Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 border on legend but not in barchart

I'm trying to creating a bar chart using ggplot2 with borders on for the legend colours but not on for the bar chart.

I tried to add scale_fill_manual with 'grey32' mapped to the Municipalities as well as legend.key = element_rect(colour='grey32') but neither of them added a boundary around the legend elements.

This is what I have with this code:

ggplot(muns, aes(x=Regional.District, y=Population.2010, fill=Municipality)) +
  geom_bar(stat='identity', width=0.6) +
  xlab("Regional District") + ylab("Population 2010") +
  scale_y_continuous(labels = comma) +
  scale_fill_manual(values=fill.vals, breaks=muns$Municipality, labels=muns$lab) +
  geom_text(aes(y=bylaw.sums[1], label=c('No Bylaw')), colour = "gray32") +
  geom_text(aes(y=bylaw.sums[1]*2+bylaw.sums[2], label=c('Bylaw')), colour = "gray32") +
  theme(text=element_text(size=12, family="Open Sans"))

bar_chart_with_no_borders

This is what I'd like: bar_chart_with_borders_on_legend_but_not_chart

I've tried:

scale_colour_manual(values=greys, breaks=muns$Municipality, labels=muns$lab) +

as well as

theme(legend.key = element_rect(colour='grey32'))

Thank you!

like image 466
hailes Avatar asked Oct 19 '25 03:10

hailes


1 Answers

Try + guides(fill = guide_legend(override.aes = list(colour = "black")))

Working example:

ggplot(iris, aes(x = Species, fill = Species)) +
    geom_bar() + 
    guides(fill = guide_legend(override.aes = list(colour = "black")))

In this instance, it appears you do need to spell "colour" with a "u".

I normally use this method to do the opposite (remove a color from a fill legend) or for overriding an alpha setting for the legend.

Judging by your sample plot, you might also want to pass reverse = TRUE to guide_legend, which will put the orange on bottom, white on top to match your plot.

like image 146
Gregor Thomas Avatar answered Oct 21 '25 18:10

Gregor Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!