Reputation: 23767
I need to combine continuous and categorical data and need to factorise my continuous variable. I struggle to understand how to cut off the axis ticks on the right limits.
I understand that the x limits are based on the new factor levels, but why do the ticks extend beyond the lower limit?
Background:
I'd like to combine a linear regression line on a continuous variable (with geom_smooth
) with summarising stats on binned data of the same variable (e.g., geom_boxplot
). I need to create a factor with all levels because otherwise those plots don't overlay. But this then creates a lot of blank space to both sides, therefore I tried to set the limits with coord_cartesian
, which I am aware is always continuous.
library(ggplot2)
foo <- data.frame(x = 20:50, y = rnorm(31))
ggplot(foo) +
geom_col(aes(factor(x), y)) +
coord_cartesian(xlim = c(10,50))
Created on 2020-03-02 by the reprex package (v0.3.0)
Upvotes: 2
Views: 362
Reputation: 145965
Use a group
aesthetic to define which bar is which, rather than using a discrete scale.
ggplot(foo, aes(x, y)) +
stat_smooth(method = "lm", se = FALSE) +
geom_col(aes(group = x))
Upvotes: 5