Reputation: 43
I want to create a stacked barplot where I can have distinct colours for the categories along the x axis (for communication purposes as they relate to a set of strongly colour coded items), but I also want to distinguish between the stacked parts of the bar with two categories, ideally using a pattern. I've found a partial solution using colour transparency, but it's not exactly what I want.
I found some solutions using extra packages to give complex fill patterns using image fills, and some workarounds to plot lines to sit over the bars to create an artificial fill effect, and some that allowed bars to have a colour and pattern fill, but only splitting either based on bars or stacks, not both. So far I have found nothing that just allows a simple pattern fill for the stacks while also allowing the bars to be different colours.
Example:
mydata <- as.data.frame(cbind(letters = c("a","b","c","d","e","f","a","b","c","d","e","f"),
split=c("yes","yes","yes","yes","yes","yes","no","no","no","no","no","no"),
amount= c(2,3,5,3,4,6,7,2,5,7,2,4)))
colfill <- c("red","blue","green","orange","magenta","purple") ## fill for letters variable
## stackfill <- c("solid","striped") ## example of type of fill variable I want for for 'split'
## Make the barplots:
# this one colours bars by 'split':
ggplot(data=mydata, aes(x=letters, y=amount, fill=split)) +
geom_bar(stat="identity",position="stack")+
scale_fill_manual(values=colfill)
# while this one distinguished based on 'letters'
ggplot(data=mydata, aes(x=letters, y=amount, fill=letters)) +
geom_bar(stat="identity",position="stack")+
scale_fill_manual(values=colfill)
# I want to combine both to get something like this, with colour coded 'letters' and pattern coded 'split':
ggplot(data=mydata)+
geom_col(aes(x=letters, y=amount, fill=letters, alpha=split)) +
scale_alpha_discrete(range=c(1,0.5))+
scale_fill_manual(values=colfill)
Appreciate any suggestions!
Thanks,
Upvotes: 3
Views: 1193
Reputation: 39613
Try this:
library(ggplot2)
#remotes::install_github("coolbutuseless/ggpattern")
library(ggpattern)
#Data
mydata <- as.data.frame(cbind(letters = c("a","b","c","d","e","f","a","b","c","d","e","f"),
split=c("yes","yes","yes","yes","yes","yes","no","no","no","no","no","no"),
amount= c(2,3,5,3,4,6,7,2,5,7,2,4)))
colfill <- c("red","blue","green","orange","magenta","purple") ## fill for letters variable
## Make the barplots:
ggplot(data=mydata)+
geom_col(aes(x=letters, y=amount, fill=letters)) +
geom_col_pattern(
aes(letters, amount, pattern_fill = split,fill=letters),
pattern = 'stripe',
colour = 'black'
)+
scale_fill_manual(values=colfill)
Output:
Upvotes: 5