Search code examples
rggplot2geom-bar

How to reduce binwidth in geom_bar for one single bar?


I'm trying to get a side-by-side bar plot using ggplot's geom_bar(). Here's some sample data I made up for replication purposes:

dat <- data.frame("x"=c(rep(c(1,2,3,4,5),5)),
                  "by"=c(NA,0,0,0,0,NA,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1))

I want to plot "x" grouped by "by". Now, because I don't need to plot NA values, I filtered for !is.na(by))

library(dplyr)
dat <- filter(dat, !is.na(by))

Now for the plot:

library(ggplot2)
ggplot(dat, aes(x=x, fill=as.factor(by))) + geom_bar(position="dodge") + theme_tufte()

This returns what I need; almost. Unfortunately, the first bar looks really weird, because it's binwidth is twice as high (due to the fact that there are no zeros in "by" for "x"==1).

Is there a way to reduce the binwidth for the first bar back to "normal"? enter image description here


Solution

  • Never mind, I just figured out that you can manipulate the binwidth argument using an ifelse statement.

    ...geom_bar(..., binwidth = ifelse("by"==1 & is.na("x"), .5, 1)))
    

    So if you play around with this, it will work. At least it worked for me.