Reputation: 51
I am trying to independently set colors for stacked barplots in ggplot.
y<-c("enjoyer", "explorer","explorer", "enjoyer", "enjoyer","enjoyer",
"explorer")
z<-c("yes", "no", "yes", "yes", "yes", "no", "yes")
x<-data.frame(y,z)
ggplot(x, aes(y, fill = z))+geom_bar()
This returns the following graph:
I would like to make the bottom parts of each bar different colors. I want the "enjoyer yes" to be black and the "explorer yes" to be green. The top parts can stay the same color or be set manually, no preference.
Appreciate any help!
Upvotes: 1
Views: 50
Reputation: 11957
You'll need to create four fill levels for each combination of enjoyer/explorer and yes/no (the quickest way is to use interaction
). After that, a customized scale_fill_manual
does the rest:
ggplot(x, aes(y, fill = interaction(y, z))) +
geom_bar() +
scale_fill_manual(
name = NULL,
labels = c('No', 'Explorer: Yes', 'Enjoyer: Yes'),
breaks = c('enjoyer.no', 'explorer.yes', 'enjoyer.yes'),
values = c(enjoyer.no = 'black', explorer.no = 'black', enjoyer.yes = 'blue', explorer.yes = 'green')
)
Upvotes: 3