PDM
PDM

Reputation: 84

How to add a line under ggplot axis text

I want to add a pair of horizontal lines at the bottom of ggplot to illustrate grouping of the x axis elements. It looks like both geom_abline and geom_segment will add lines inside the graph. Any idea how to add lines under it ?

p + geom_segment(aes(x = 2, y = -0.5, xend = 4, yend = -0.5 )) +
        geom_segment(aes(x = 5, y = -0.5, xend = 7, yend = -0.5)) 

this plots the line segment within the plot not under the axis title.

Upvotes: 1

Views: 3263

Answers (1)

phalteman
phalteman

Reputation: 3532

You can make annotations outside the plot area by using coord_cartesian(xlim, ylim, clip="off") and then using annotate() with the appropriate geom. Depending on your aesthetic for grouping, you can put lines at the base of the plot area or below the axis labels.

library(ggplot2)

df <- data.frame(x=seq(1,10), y=seq(1,10))

ggplot(df, aes(x,y)) +
  geom_point() +
  coord_cartesian(xlim=c(0,10), ylim=c(0,10), clip="off") +
  annotate("segment", x = 2, xend = 4, y = -1, yend = -1) +
  annotate("segment", x = 5, xend = 7, y = -0.5, yend = -0.5)

enter image description here

Upvotes: 3

Related Questions