JRBatHolmes
JRBatHolmes

Reputation: 88

Different colour schemes in the same plot

My dataset looks similar to

df <- data.frame(name = rep(letters[1:4], each = 3), category = rep(1:2, each = 6), 
                 time = rep(1:3, times = 4), value = sample(1:100, 12))

I want a stacked barplot that displays Value over time for each of the names, but I want the names to have different colour schemes based on their category.

In this example, I have a plot that looks like this

enter image description here

Now I want the names a and b to have a different colour scheme from names c and d as they are of different categories. I know I can facet based on categories, but for some particular reason, I want all info displayed on one graph. How do I do that?

Upvotes: 1

Views: 56

Answers (2)

Rui Barradas
Rui Barradas

Reputation: 76402

This solution uses the transparency factor alpha to make the difference between colors in each bar.

ggplot(df,
       aes(x = name, y = value, alpha = factor(time), fill = factor(category))) +
  geom_bar(stat = "identity") +
  scale_alpha_manual(name = "Time", values = c(0.3, 0.5, 1)) +
  scale_fill_manual(name = "Category", values = c("#1f78b4", "#33a02c")) +
  theme_classic()

enter image description here

Upvotes: 1

January
January

Reputation: 17090

One option:

df$cat.time <- paste0(df$category, ".", df$time)
ggplot(df, aes(x=name, y=value, fill=factor(cat.time))) + geom_bar(stat="identity")

Result:

enter image description here

You can then use scale_fill_manual to adapt the color scheme:

pal <- c(colorRampPalette(c("yellow", "DarkGreen"))(3), 
         colorRampPalette(c("red", "NavyBlue"))(3))

ggplot(df, aes(x=name, y=value, fill=factor(cat.time))) + 
   geom_bar(stat="identity") + scale_fill_manual(values=pal) 

Upvotes: 2

Related Questions