I like my ggplots to have the axis always start at 0, so I use this code within my ggplot to do it :
coord_cartesian(xlim = c(0,max(df$A)), ylim = c(0,max(df$B))) +
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0)) +
As a full reproducible example:
df = tibble(A = sample(1:100,100, replace = TRUE), B = seq(1,100))
df %>%
filter(A > 30) %>%
ggplot(aes(A, B)) +
geom_point() +
coord_cartesian(xlim = c(0,max(df$A)), ylim = c(0,max(df$B))) +
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0))
Now, those 3 lines are a pain to remember, and quite bloated.
Is there a way I can put those 3 lines into a function, and call it within the ggplot whenever I want to limit my axis?
I saw this link:
ggplot - function for graph styling
Which you can use a function for the theme() part, but I am not sure how to do it for just those 3 lines I put above i.e. coord_cartesian, scale_x etc.
I.e. I want to do something like this:
df %>%
filter(A > 30) %>%
ggplot(aes(A, B)) +
geom_point() +
fix_the_axis()
Many thanks


+ xlim(0, NA) + ylim(0, NA)?