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