I am trying to make a plot using scale_x_continuous(), scale_y_continuous(), and coord_fixed() and maybe coord_cartesian(). However one always seems to override the other one(s).
Consider the dataframe:
x<- as.vector(sample(250:500, 50))
y<- as.vector(sample(1:500, 50))
df<- as.data.frame(cbind(x,y))
I need to have the scale of the x and y axes set at a 1:1 ratio. This is easily accomplished like this:
p <-ggplot() + geom_point(data = df, aes(x = x, y = y))
p <- p + scale_x_continuous(limits = c(0,500)) + scale_y_continuous(limits = c(0,500))
p <- p + coord_fixed()
p
Now I want to remove all of that empty space on the left side of the plot. The logical step to me would be to use coord_cartesian() to "zoom" into my plot with out changing it, but it does not work.
p <- p + coord_cartesian(xlim = c(250, 500), ylim = c(0,500))
p
This line of code does zoom me in, but now the effect of coord_fixed() is gone. (This is seen when you change the margins of the plot and the the ratio of the axis spacing changes as well).
I have tried many iterations of setting limits in all three of these functions, and removing and/or reordering these functions as well and they always seems to negate each other at one point. Even setting xlim and ylim within coord_fixed() itself stops it from working.
p <-ggplot() + geom_point(data = df, aes(x= x, y = y))
p <- p + scale_x_continuous(limits = c(0,500)) + scale_y_continuous(limits = c(0,500))
p <- p + coord_fixed(ratio=1, xlim = c(250, 500), ylim = c(0,500))
p
How can I keep the ratio between my axes fixed at 1:1, while removing the empty space on the left of the plot?
Thank you!
You can use coord_fixed, and set the ratio to match the ratio between the limits of the two axes:
xlim = c(245, 505)
ylim = c(-5,505)
p + coord_fixed(ratio = diff(xlim)/diff(ylim), xlim=xlim, ylim=ylim, expand=F)

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With