Ggplot2 borders legend but not barchart

I am trying to create a histogram using ggplot2 with borders for the legend colors, but not included for the histogram.

I tried adding scale_fill_manual

with "grey32" mapped to municipalities as well legend.key = element_rect(colour='grey32')

, but none of them added a border around the legend items.

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 would like: bar_chart_with_borders_on_legend_but_not_chart

I tried:

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

      

and

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

      

Thank!

+3


source to share


1 answer


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 case, it looks like you need to write "color" with "u".

I usually use this method to do the opposite (remove the color from the fill legend) or to override a parameter alpha

for the legend.

Judging by your sample, you can also pass reverse = TRUE

in guide_legend

, which puts orange on the bottom, white on top to match your plot.

+5


source







All Articles