5

I have data (depth over time) that I want to display with a line plot. For clarity, I want to zoom in on a section but still show the user that the data continues outside the bounds of the plot. So I want the lines to stop at the plot's edge, rather than at the last point. This is straightforward enough in base graphics but I can't make it work in ggplot. Here's an example with base:

d <- data.frame(x = 1:10, y = 1:10)
plot(d$x, d$y, xlim = c(2,9))
lines(d$x, d$y)

line plot in base graphics

A similar approach with ggplot doesn't work; the lines stop at the last point. Example:

d <- data.frame(x = 1:10, y = 1:10)
ggplot(d, aes(x, y)) + geom_point() + geom_line() + xlim(2,9)

line plot in ggplot

Is there a way to get lines to run to the plot's edge in ggplot? Thanks.

2 Answers2

6

try this

d <- data.frame(x = 1:10, y = 1:10)
ggplot(d, aes(x, y)) + geom_point() + geom_line() + coord_cartesian(xlim = c(0,9))

enter image description here

Tomas H
  • 713
  • 4
  • 10
0

if you want a straight line, abline would be easiest

d <- data.frame(x = 1:10, y = 1:10)
ggplot(d, aes(x, y)) + geom_point() + geom_abline() + xlim(2,9)

enter image description here

baptiste
  • 75,767
  • 19
  • 198
  • 294