Martina
Martina

Reputation: 159

How can I color bars in a faceted and grouped ggplot

i made the following plot (I used the "npk" dataset as dummy data because I cannot share the original data - but the systematic of the plot stayed the same):

library(ggplot2)
library(scales)

ggplot(npk,aes(x=block,group=N)) + 
geom_bar(aes(y = ..prop..)) +
facet_grid(~ N) +
xlab("blocks") +
scale_y_continuous(labels = percent) +
theme(axis.text.x=element_blank(),axis.ticks.x=element_blank(),
     legend.title=element_blank())

block: blocknumber 1-6
N: binary variable 1/0

plot

Now I want to color each bar (= block) in a different color according to the number of the block (I know, this doesn't make much sense here, since the proportion for each block (for variable N) is the same,but with my original data I have different proportions so it makes sense...). In addition to faceting the plot I had to use "group=N" because I needed the proportions per block.

How can I do this? I have tried many different ways to declare the color for these blocks but unfortenately I am not able to color each block, only all blocks together in grey or another specific color...

Thanks for your help! It's very much appreciated! Martina

Upvotes: 0

Views: 100

Answers (2)

Kene David Nwosu
Kene David Nwosu

Reputation: 898

Can the problem be fixed by precalculating your proportions and using geom_col instead of geom_bar?

library(tidyverse)

npk %>% 
  slice_sample(n = 15) %>% ## so that percentages vary
  group_by(block, N) %>% 
  count(name = "count") %>% 
  group_by(block) %>% 
  mutate(prop = count/sum(count)) %>% 
  ungroup() %>% 
  ggplot(aes(x=block,y=prop)) + 
  geom_col(aes(fill = block)) +
  facet_grid(~ N)

Created on 2021-10-25 by the reprex package (v2.0.1)

Upvotes: 1

Andy Baxter
Andy Baxter

Reputation: 7626

This seems indeed a tricky thing to get around! Putting together an answer from here and here you can do it by tweaking slightly the method that it uses to calculate y, in order to take into account the grouping by facets without overriding fill by including group:

library(tidyverse)
library(scales)

ggplot(npk, aes(x = block)) +
  geom_bar(aes(
    y = ..count.. / tapply(..count.., ..PANEL.., sum)[..PANEL..],
    fill = block
  )) +
  facet_grid( ~ N) +
  xlab("blocks") +
  ylab("Percentage") +
  scale_y_continuous(labels = percent) +
  theme(
    axis.text.x = element_blank(),
    axis.ticks.x = element_blank(),
    legend.title = element_blank()
  )

Created on 2021-10-25 by the reprex package (v2.0.0)

Upvotes: 1

Related Questions