rggplot2axis

Make axis lines start from specific values in ggplot


I have the following scatterplot in ggplot:

library(ggplot2)

ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) + 
  geom_point() +
  theme_classic() +
  scale_y_continuous(limits = c(2, 5)) +
  scale_x_continuous(limits = c(4, 8))

enter image description here

My question is: what parameter should i tweak to make the axis.line.x and axis.line.y start respectively from the points x=4 and y=2?

I tried with coord_cartesian(expand=FALSE) and with scale_y_continuous(expand=c(0,0)) but the result is that the axis limits are being reduced to the value i put on the limits parameter.

Keep in mind that I don't want to create an Origin with x=4 and y=2 in the same point, i just want to remove from this plot only the black line that connect the x axis with the y axis, like in the following plot:

enter image description here,

where there is blank space below 0.01 for both axis.


Solution

  • You can achieve your desired result using the cap= argument of guide_axis (introduced with ggplot2 3.5.0) which allows to cap the axis at the first break (aka "lower") or the last break (aka "upper") or "both".

    library(ggplot2)
    
    ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
      geom_point() +
      theme_classic() +
      scale_y_continuous(limits = c(2, 5), guide = guide_axis(cap = "lower")) +
      scale_x_continuous(limits = c(4, 8), guide = guide_axis(cap = "lower"))