1

I could not find a previous answer to this question, but I was unsure of exactly what to search, so it's quite possible that I missed something.

When I plot the following data.frame, I get exactly what you'd expect.

df <- data.frame(x = c(1:5), y = 2^c(1:5))
g <- ggplot(df, aes(x=x, y=y)) + geom_line()
g

y-axis includes all points

The problem arises when I try to limit the range of the y-axis such that one of the line segments, (4, 16) to (5, 32), is only partially on the plot. ggplot does not show the portion of that line segment that would be on the plot; instead, it just entirely omits the line segment.

g <- ggplot(df, aes(x=x, y=y)) + geom_line() + scale_y_continuous(limits = c(0, 25))

y-axis limited to 0-25

What I would like is something that looks like this.

enter image description here

I know that I could break the final line segment into smaller pieces, but that seems like an inconvenient solution. There must be some way to make ggplot include the segment.

njc
  • 126
  • 1
  • 6
  • 2
    Use `coord_cartesian(ylim=c(0,25))` to set the y-range. `scale_y_continuous` excludes data that's outside the range, while `coord_cartesian` does not. – eipi10 Oct 25 '16 at 14:57
  • @eipi10 Works great! Seems like it could be a short and sweet answer. – njc Oct 25 '16 at 15:01
  • This is a duplicate of several other SO questions, so no need to add another answer. – eipi10 Oct 25 '16 at 15:03
  • @eipi10 Makes sense. I tried to find them, but searching things like "ggplot segment off graph" and "ggplot segment out of range" got me nothing. I guess I needed a better understanding of the problem just to search for the problem... – njc Oct 25 '16 at 15:06

0 Answers0