0

How can you produce consistent bar widths and position of the bars when using geom_col and position_dodge?

This has been asked before Consistent width for geom_bar in the event of missing data. Is the best solution still to expand the data or is there a different approach within ggplot2?

An example showing the issue:

library(ggplot2)
df1 <- data.frame(x=factor(c(1, 1, 2)), y=c(1,-1, -1), sign=factor(c(1, 2, 2))) 

# The bar is in the wrong position (left instead of right)
ggplot(df1, aes(x, y, fill=sign)) + 
          geom_col(position=position_dodge(preserve = "single"))

# Still not positioned correctly - centered instead of in right hand side
ggplot(df1, aes(x, y, fill=sign)) + 
          geom_col(position=position_dodge2(preserve = "single", padding = 0))

I can expand the data as in the accepted solution at the linked question, which then gives the expected result

df1 <- data.frame(x=factor(c(1, 1, 2, 2)), y=c(1,-1, 0, -1), sign=factor(c(1, 2, 1, 2 )))
ggplot(df1, aes(x, y, fill=sign)) + 
           geom_col(position=position_dodge(preserve = "single"))
user2957945
  • 2,353
  • 2
  • 21
  • 40
  • What exactly are you looking for? Is `position_dodge(preserve = "single")` not fully satisfactory, and you want to achieve something slightly different? – divibisan Jan 13 '22 at 17:28
  • @divibisan; the code at the end shows the expected outcome. No `position_dodge(preserve = "single")` is not satisfactory as it places the bar with the missing levels in a different position to the bars with all the levels e.g. for x = 1 group with no missing levels the bars are ordered with the left hand side bar is +ve and rhs is -ve. Using `position_dodge(preserve = "single")` when there is no +ve value, the -ve value is placed into the left hand side position. – user2957945 Jan 13 '22 at 18:18
  • To be clear: what you are looking to do is have the the positioning of `position_dodge(preserve="single")`, but have the placement of the bars from right to left? As far as I know, the only way to do that would be expanding the data as you show. There is unfortunately no attribute that can position the bars by default on the right. – chemdork123 Jan 14 '22 at 19:46
  • @chemdork123; "... placement of the bars from right to left?". Not really. What I am wanting is that the placement of the bars for each group defined by the fill aes to be consistently placed on the x-axis – user2957945 Jan 15 '22 at 12:34

0 Answers0