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"))