2
votes

Making a plot with ggplot, I wish to set my axis exactly. I am aware that I can set the plot range (e.g. for the x-axis I specified limits from 2 to 4) with coord_cartesian() but that leaves a bit of space to the left and right of the range I specify:

enter image description here

Code for the MWE above:

library(ggplot2)

data.mwe = cbind.data.frame(x = 1:5, y = 2:6)

plot.mwe = ggplot(data = data.mwe, aes(x=x,y=y)) + geom_line() + coord_cartesian(xlim = c(2,4))
print(plot.mwe)

My desired result is a plot where the displayed area is exactly between the limits I specify.

I am aware of How to set limits for axes in ggplot2 R plots? but it does not answer my question, as it produces the undesired result above, or cuts out observations (with the limits argument to scale_x_continuous). I know I could tinker with setting a smaller range for limits, but I am looking for a clean result. At the least I would like to know by how much the actual range differs from the one I specify, so that I could adapt my limits accordingly.

1
This question is similar to the present question.jazzurro

1 Answers

5
votes

Add expand = FALSE:

library(ggplot2)

data.mwe = data.frame(x = 1:5, 
                      y = 2:6)

ggplot(data.mwe, aes(x, y)) + 
    geom_line() + 
    coord_cartesian(xlim = c(2, 4), 
                    expand = FALSE)