mat
mat

Reputation: 2617

ggplot: draw segment that goes off the chart's limits

I want to draw a chart with a segment that goes off the limits of the plot. Ggplot simply suppress the segment instead of displaying the visible part of it.

This is an example for illustration:

library(ggplot2)

df <- data.frame(x1 = 2, x2 = 6, y1 = 10, y2 = 50)

ggplot(mtcars, aes(wt, mpg)) +
    geom_point() +
    geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2), data = df) +
    xlim(c(0, 7)) +
    ylim(c(0, 35)) +
    coord_fixed(.1)

This is what I want:
enter image description here

But instead the segment is not drawn and I get the following warning:

Warning message:
Removed 1 rows containing missing values (geom_segment). 

I want to keep the chart limits fixed and the coord_fixed(.1) setting.

Upvotes: 4

Views: 223

Answers (1)

stefan
stefan

Reputation: 124013

Using xlim and ylim will remove data that falls outside of the limits. To achieve the desired result set the limits inside coord_fixed.

library(ggplot2)

df <- data.frame(x1 = 2, x2 = 6, y1 = 10, y2 = 50)

ggplot(mtcars, aes(wt, mpg)) +
  geom_point() +
  geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2), data = df) +
  coord_fixed(.1, xlim= c(0,7), ylim = c(0, 35))

Upvotes: 4

Related Questions