0

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

Gilean0709
  • 1,098
  • 6
  • 17
Martina
  • 139
  • 1
  • 10

2 Answers2

1

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)

Andy Baxter
  • 5,833
  • 1
  • 8
  • 22
1

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)

Kene David Nwosu
  • 828
  • 6
  • 12
  • 1
    hi kene, thank you very very much for your solution it works also perfectly, but i noticed that i had to make a little adaption to get the same results with my data - I had rewrite the command "group_by(block)" to "group_by(N)" because I wanted the proportions related to N per block. When I adapt your code in this way it perfectly worked :) – Martina Oct 27 '21 at 10:53