0

I'm plotting a line using geom_line with ggplot. I'm running into a problem where, because the line has no data (0) it ends up getting obscured by the axis, such as below:

enter image description here

Is there any known way to circumvent this without having to remove the expand(0,0) on the scale_y_continuous layer?

Hanna
  • 69
  • 1
  • 10
  • 8
    How exactly would you like to fix this? Just draw the line on top of the axes? When asking for help, you should include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jul 02 '18 at 20:23

1 Answers1

3

You can remove the actual x axis, and manually add an axis line that sits underneath the data by using geom_hline(yintercept = 0). It's important to put your geom_hline() axis before the geom_line() that plots your data in your plot code. ggplot plots items in the order they are written, so if you call geom_line() after geom_hline() your data will be drawn on top of the axis line.

#some made up data
df <- data.frame(x = 1:12, y = c(rep(0,12), rep(c(1,2), 6)), 
                 group = c(rep("zeros", 12), rep("not zeros", 12)))

ggplot(df, aes(x = x, y = y, color = group)) +
  geom_hline(yintercept = 0) + #first, add an axis line using geom_hline
  geom_line() + #next, add the geom for your data
  theme_classic() +
  coord_cartesian(expand = FALSE) +
  theme(axis.line.x = element_blank())  #remove actual x axis line

enter image description here

Jan Boyer
  • 1,540
  • 2
  • 14
  • 22