Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equal bar width across facet_wrap barplots

Tags:

r

ggplot2

I have a data frame that looks like this:

category = c(rep("house", 2), rep("apartment", 4), rep("condo", 3))
sample = paste("ID", seq(1:9), sep='')
group = c(rep(1,9), rep(2,9))
value = c(0.990000, 0.608143, 0.451284, 0.500343, 0.482670, 0.358965, 0.393272, 0.300472, 0.334363, 0.001000, 0.391857, 0.548716, 0.499657, 0.517330, 0.641035, 0.606728, 0.699528, 0.665637)
data = as.data.frame(cbind(category, sample, group, value))

I want to use the variable 'category' to facet_wrap a stacked barplot, like this:

ggplot(data, aes(x=sample, y=value, fill=group)) + 
  geom_bar(stat="identity", width=1) +
  facet_wrap(facet ~ ., scales="free_x")

The number of samples in each category is uneven but ggplot automatically makes each barplot the same width, meaning that the bars across plots are not the same width, like this:

enter image description here

Is there a way to force ggplot to keep the bars all the same width, such that the overall width of each barplot is different across plots?

Thanks for any tips!

like image 415
nrcombs Avatar asked Sep 08 '25 00:09

nrcombs


1 Answers

Try facet_grid

ggplot(data, aes(x = sample, y = value, fill = group)) + 
    geom_bar(stat = "identity", width = 1, col = "black") +
    facet_grid(. ~ category, scales = "free", space = "free")
like image 185
d.b Avatar answered Sep 09 '25 15:09

d.b