Benjamin Telkamp
Benjamin Telkamp

Reputation: 1561

Change Color of Bars in Facetted Bar Plot

I'm trying to change some colours in the following plot:

The code below gave me the following plot, already quite pretty:

enter image description here

I still would like to change the colors of the 4 bars in my plots, to let's say "green4", "darkgreen", "orangered3" and "red3", but not change anything else to my plot (like used labels from the legend (of course the colors should change as well in the legend)). My data (df) has three variables. Variable 'V1n' is just a numeric version of the factor variable V1. It's just the last bit i can't get my head around, does anyone know how to change the four colors used by default?

library(ggplot2)
library(dplyr)
glimpse(df)

# Observations: 300
# Variables: 3
# $ METING.f <fctr> Meting 0, Meting 0, Meting 0, Meting 0, Meting 0,...
# $ V1n      <int> 2, 1, 2, 2, 2, 2, 2, 1, 2, 1, 2, 1, 1, 2, 2, 2, 1,...
# $ V1       <fctr> Ja, meerdere, namelijk..., Ja, Ja, meerdere, name...  


ggplot(df, aes(x = V1n, fill = V1)) + 
  geom_bar(aes(y = (..count..)/tapply(..count..,..PANEL..,sum)[..PANEL..])) + 
  scale_y_continuous(labels = scales::percent) + 
  geom_text(aes(y = ((..count..)/sum(..count..)), 
                label = scales::percent((..count..)/tapply(..count..,..PANEL..,sum)[..PANEL..])), 
                stat = "count", vjust = -0.25) +
  facet_grid(.~ METING.f) +
  scale_fill_discrete(name = "Beschikt uw instelling over een\naandachtsfunctionaris kindermishandeling?\n") +
  labs(title = " ",
       x = "Vraag 1",
       y = "Percentage")  +
  theme(axis.text.x = element_blank(),
        axis.ticks.x=element_blank())

Upvotes: 2

Views: 962

Answers (1)

pogibas
pogibas

Reputation: 28309

You can simply set wanted fill/colors using scale_fill_manual.

scale_fill_manual(name = "Beschikt...",
                  values = c("green4", "darkgreen", "orangered3", "red3"))

Or you can use one of the brewer pallets with scale_fill_brewer.

PS.: If you don't want to set name of fill in scale_fill_manual you can set it in labs() (as you did for title and x). For example labs(fill = "yourFillName").

Upvotes: 2

Related Questions