Adela Adela - 3 months ago 9
R Question

Lines with geo_segment does not reach the axis limit

I'm trying to plot several lines using

ggplot2
and functions
geom_hline
and
geom_segment
. The problem is that with
geom_segment
it is not possible to reach axis limit. This is not the problem with
geom_hline
but then the plot seems a little bit inconsistent. I also tried to change axis limits but without any success.

Example:

ggplot() +
geom_hline(yintercept = 3) +
geom_segment(aes(x = 2, xend = 4, y = 2.75, yend = 2.75)) +
geom_segment(aes(x = 3, xend = 5, y = 3.75, yend = 3.75)) +
# xlim(c(2, 5)) # no change
# xlim(c(2.5, 4.5)) # warning + no geom_segment lines plotted

Answer

You need to set the expand argument to zero to turn off padding

ggplot() + 
  geom_hline(yintercept = 3) + 
  geom_segment(aes(x = 2, xend = 4, y = 2.75, yend = 2.75)) +
  geom_segment(aes(x = 3, xend = 5, y = 3.75, yend = 3.75)) + 
  scale_x_continuous(expand = c(0,0))