5

I have a data frame of positive x and y values that I want to present as a scatterplot in ggplot2. The values are clustered away from the point (0,0), but I want to include the x=0 and y=0 lines in the plot to show overall magnitude. How can I do this?

set.seed(349)
d <- data.frame(x = runif(10, 1, 2), y = runif(10, 1, 2))
ggplot(d, aes(x,y)) + geom_point()

Plot without (0,0)

But what I want is something roughly equivalent to this, without having to specify both ends of the limits:

ggplot(d, aes(x=x, y=y)) + geom_point() + 
  scale_x_continuous(limits = c(0,2)) + scale_y_continuous(limits = c(0,2))

Plot with (0,0)

Blue Magister
  • 13,044
  • 5
  • 38
  • 56
  • I know this is an old question but I just ran into it question and there seems to be a better solution. Use the function `expand_limits(...)` specifying the limits you want to include. (probably a new addition which wasn't available a few years back) – Adi Sarid Feb 26 '18 at 22:18

3 Answers3

9

One option is to just anchor the x and y min, but leave the max unspecified

ggplot(d, aes(x,y)) + geom_point() +
  scale_x_continuous(limits = c(0,NA)) + 
  scale_y_continuous(limits = c(0,NA))
MrFlick
  • 195,160
  • 17
  • 277
  • 295
1

This solution is a bit hacky, but it works for standard plot also.

Where d is the original dataframe we add two "fake" data points:

d2 = rbind(d,c(0,NA),c(NA,0))

This first extra data point has x-coordinate=0 and y-coordinate=NA. This means 0 will be included in the xlim, but the point will not be displayed (because it has no y-coordinate).

The other data point does the same for the y limits.

Just plot d2 instead of d and it will work as desired.

If using ggplot, as opposed to plot, you will get a warning about missing values. This can be suppressed by replacing geom_point() with geom_point(na.rm=T)


One downside with this solution (especially for plot) is that an extra value must be added for any other 'per-data-point' parameters, such as col= if you give each point a different colour.

Aaron McDaid
  • 26,501
  • 9
  • 66
  • 88
1

Use the function expand_limits(x=0,y=0), i.e.:

set.seed(349)
d <- data.frame(x = runif(10, 1, 2), y = runif(10, 1, 2))
ggplot(d, aes(x,y)) + geom_point() + expand_limits(x = 0, y = 0)
Adi Sarid
  • 799
  • 8
  • 13