0

I have a bar plot with error bars. I want the bars to have different widths. Is it possible to remove the white space between the bars? I also want to remove the white space between the plot area and the x-axis and y-axis, if possible.

Example:

require(ggplot2)

df <- data.frame(order=c(1,2,3), 
      rate=c(28.6, 30.75, 25.25), 
      lower=c(24.5, 28.94, 22.86), 
      upper=c(31.26, 33.1, 28.95), 
      width=c(.25,1.25,.5))

plot <- ggplot(data=df, aes(x=order, y=rate, width=width)) + 
        geom_bar(aes(fill=as.factor(order)), stat="identity") + 
        geom_errorbar(aes(x=order, ymin=lower, ymax=upper), width=.1)
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • For how to remove the white space, see: https://stackoverflow.com/questions/22945651/how-to-remove-space-between-axis-area-plot-in-ggplot2. As for having different bar widths, your code already does that? – Joe Roe Mar 15 '21 at 10:56
  • Thanks! This link has helped me remove the white space between the plot area and axes, but I'm still not sure how to remove the space between the bars. I don't think I need help with the widths. – user15399429 Mar 15 '21 at 11:09
  • I think the space between the bars can be adjusted by the width option of `geom_bar`, e.g. `geom_bar(aes(fill=as.factor(order)), stat="identity", width = 1)` – Peace Wang Mar 15 '21 at 12:18
  • Does this answer your question? [How to make variable bar widths in ggplot2 not overlap or gap](https://stackoverflow.com/questions/20688376/how-to-make-variable-bar-widths-in-ggplot2-not-overlap-or-gap) – tjebo Mar 15 '21 at 15:25

1 Answers1

0

Thanks for the suggestions everyone. I managed to find a workaround using facet_grid(). It is not the most elegant solution, but it works nonetheless.

require(ggplot2)

df <- data.frame(order=c(1,2,3), 
  rate=c(28.6, 30.75, 25.25), 
  lower=c(24.5, 28.94, 22.86), 
  upper=c(31.26, 33.1, 28.95), 
  width=c(.25,1.25,.5))

plot <- ggplot(data=df, aes(x=order, y=rate, width=width)) + 
  geom_bar(aes(fill=as.factor(order)), stat="identity") + 
  geom_errorbar(aes(x=order, ymin=lower, ymax=upper), width=.1) +
  facet_grid(~as.factor(order), scales='free_x', space='free', switch="x") + 
  scale_y_continuous(expand=c(0, 0)) + 
  scale_x_continuous(expand=c(0, 0)) + 
  theme_bw() + 
  theme(panel.border=element_blank(),
        panel.spacing.x=unit(0, "lines"), 
        strip.background=element_blank(), 
        strip.placement="outside",
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        legend.position="none")

The main issue was in getting the correct alignment with geom_errorbar() and geom_bar(). The facet_grid option maintains the alignment. Adding the panel.spacing.x=unit(0,"lines") removes the white space between the bars by changing the space between each panel. The key is that width must be at least 1. This solution does cause problems with the alignment of the x-axis tick marks, but for my purposes this was not an issue.