Geom_bar + facet_grid not behaving as expected



In the this ggplot I generated, I think the width of the rectangle in facet == 3 is not right. I want it the be equally wide as other rectangles and should be in the middle of Sex == 2 and Sex == 4 respectively. Did I do anything wrong?

A reproducible example will be as follow. Unfortunately I couldn't find the option of uploading files in the post but I will be happy to share with emails.

ggplot(b, aes(x = Sex), weight = rel_mean) + geom_bar(position = "fill") + 
    facet_grid(rows = vars(Race))


If you look for information on the function geom_bar with ?geom_bar, you will see that the defaults arguments for this function are as follows:

 geom_bar(mapping = NULL, data = NULL, stat = "count",
       position = "stack", ..., width = NULL, binwidth = NULL, na.rm = FALSE,
       show.legend = NA, inherit.aes = TRUE)


  width: Bar width. By default, set to 90% of the resolution of the

So I imagine that your 3rd graph has a different data resolution? If you want all the bars to be of the same width, set a numerical value for the width argument in the geom_bar function:

ggplot(b, aes(x = Sex), weight = rel_mean) +
    geom_bar(position = "fill", width = n) + 
    facet_grid(rows = vars(Race))

(and replace n by whatever value works for you of course).

I cannot test it without the data, so please let us know if this fixes your problem.


Thank you prosoitos! I tried using different widths but they did not adjust the specific bar that I wanted, and here is the data, could you take a look?


This problem has been stuck for a while, could someone help?


Hey @trcc! If you need some help putting a reprex together, we have a guide that can you with it, including making your data accessible to the script regardless of who runs it :slight_smile:


Hi! What's the specific problem. Is this not ok?
(I put color = white to make clearer separations between identical bars. Also, weight should probably be inside the aes call, although I don't know if geom_bar takes weights into account when counting.)

ggplot(b, aes(x = Sex, weight = rel_mean)) + 
  geom_bar(position = "fill", width = 1, color = "white") + 
  facet_grid(rows = vars(Race))


That's exactly the solution I suggested a week ago. But this was the OP's reply:


Yes, I actually took it from your answer :slight_smile:
I was just asking for clarification on why they felt they didn't get the plot they wanted.


Oh, I see. Sorry: based on the OP's comment, I had ruled out this suggestion as the solution for their problem and I thought that you had missed my post higher up. Thanks for spending the time to test it with the OP's data.

@trcc: if you can't get this to work on your end, let us know what is going on so that we can try to help you further with this.