Pongo
Pongo

Reputation: 23

Can I use multiple fill patterns in ggplot2?

I've created a dodged bar chart in ggplot2 with geom_col(). The code looks like this:

cat <- c("A", "A", "A", "A","B", "B", "B", "B")
var <- c("X", "Y", "Z", "T", "X", "Y", "Z", "T")
val <- c(35, 25, 20, 20, 40, 10, 15, 35)
df <- data.frame(var, cat, val)
ggplot(data = df) + 
  geom_col(aes(x = var, y = val, fill = cat), position = "dodge")

This produces the following plot: enter image description here

I would like each variable to have a different filling colour, for example T = Green, X = Blue etc. and still keep a colour separation between the categories, for example T-A = darkgreen, T-B = lightgreen, X-A = darkblue, X-B = lightblue etc.

Is there an easy way to add this feature?

Thanks!

Upvotes: 1

Views: 808

Answers (2)

Allan Cameron
Allan Cameron

Reputation: 174556

I think the easiest way to do what you're asking is to use the alpha scale:

ggplot(data = df) + 
  geom_col(aes(x = var, y = val, fill = var, alpha = cat), 
           position = "dodge") +
  scale_alpha_discrete(range = c(0.5, 1), guide = guide_none()) +
  theme_classic()

enter image description here

If you really want to use a grid in the background and don't want to see lines through the pale bars, make sure you plot some white bars of the same dimension underneath:

ggplot(data = df) + 
  geom_col(aes(x = var, y = val, group = cat), 
           position = "dodge", fill = "white", alpha = 1) +
    geom_col(aes(x = var, y = val, fill = var, alpha = cat), 
           position = "dodge") +
  scale_alpha_discrete(range = c(0.5, 1), guide = guide_none())

enter image description here

Upvotes: 2

Duck
Duck

Reputation: 39613

Maybe this can be useful:

library(ggplot2)
#Data
cat <- c("A", "A", "A", "A","B", "B", "B", "B")
var <- c("X", "Y", "Z", "T", "X", "Y", "Z", "T")
val <- c(35, 25, 20, 20, 40, 10, 15, 35)
df <- data.frame(var, cat, val)
#Plot
ggplot(data = df) + 
  geom_col(aes(x = var, y = val, fill = interaction(var,cat)), position = "dodge")+
  labs(fill='Var')

Output:

enter image description here

You can customize colors with scale_fill_*(). Here an example using a fill scale from ggsci package:

#Plot 2
ggplot(data = df) + 
  geom_col(aes(x = var, y = val, fill = interaction(var,cat)), position = "dodge")+
  labs(fill='Var')+
  ggsci::scale_fill_futurama()

Output:

enter image description here

Upvotes: 0

Related Questions