When using geom_bar with stat = "identity", the y-axis max is the sum total of all values. In this example, I want the y-axis max to be 100 rather than 300 and the stacked bar to show the proportion of the bar each replicate is. Does anyone know how I can do this?
dat = data.frame(sample = c(rep(1, 12),
rep(2, 9),
rep(3, 6)),
category = c(rep(c("A", "B", "C"), each = 4),
rep(c("A", "B", "C"), each = 3),
rep(c("A", "B", "C"), each = 2)),
replicate = c(rep(c("a", "b", "c", "d"), 3),
rep(c("a", "b", "c"), 3),
rep(c("a", "b"), 3)),
value = c(rep(25, 12),
rep(c(25, 25, 50), 3),
rep(50, 6))
)
ggplot(dat,
aes(x = sample, y = value)) +
geom_bar(aes(fill = replicate),
stat = "identity")
One way would be to pre-calculate the values before plotting.
library(dplyr)
library(ggplot2)
dat %>%
group_by(sample) %>%
mutate(value = value/sum(value) * 100) %>%
ggplot() + aes(x = sample, y = value, fill = replicate) +
geom_col() +
ylab('value %')