Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

geom_bar width in ggplot2 [duplicate]

Tags:

r

ggplot2

I am generating faceted barchart with ggplot. I have the problem that the MWE below generates the graph at the bottom. I would like it to generate bars that have the same widths in both facets. How would I go about this?

library(ggplot2)

df = data.frame(x = as.factor(c(1, 2, 3, 1, 2)),
                y = c(2, 3, 4, 5, 6),
                g = c(1, 1, 1, 2, 2));

ggplot(df, aes(x = 1, y = y, fill = x)) +
  geom_bar(stat = "identity",
           position = "dodge") +
  facet_wrap(~ g);

problematic image

like image 977
Manuel Avatar asked May 01 '26 19:05

Manuel


1 Answers

Not sure if this is what you need. Creating a place holder for the missing factor level using the complete function from tidyr package can also make the bar width the same at two facets. The downside is that the second plot is imblanced.

ggplot(tidyr::complete(df, x, g), aes(x = 1, y = y, fill = x)) +
       geom_bar(stat = "identity", position = "dodge") +
       facet_wrap(~ g);

enter image description here

like image 73
Psidom Avatar answered May 03 '26 17:05

Psidom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!