Suppose I want to plot a bar chart with x axis ranged from 2 to 4. It's not enough to set limits of x axis as [2, 4], since it doesn't cover the width of bars. So, I need to manually add 0.5, which is half the width of the bar, to the limits. This seems too tricky.
Are there any good way to ensure the whole bars are included in the limits? (Note that expand seems to expand the limit after cutting the data, so it doesn't help here.)
I want to plot bar charts without caring about the bar widths. I don't want to change the width for bar to be included, but want the scale to include them automatically...!
Does your use case require that the x axis be mapped to scale? If not, you could convert to factors and then ggplot will take care of the spacing without intervention.
I know using the discrete scale solve the problem quickly as below, but my concern is different; I just wonder why the bars at 2 and 4 won't be included whrereas 2 and 4 are definitely within the range of the x axis.
library(ggplot2)
d <- data.frame(x = 1:5)
ggplot(d) +
geom_bar(aes(factor(x))) +
# BTW, I don't know why I lose the tick at x=2 when I specify limits=2:4...
scale_x_discrete(limits = as.character(2:4))
#> Warning: Removed 2 rows containing non-finite values (stat_count).