Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a vertical line when using a log scale?

Tags:

r

ggplot2

How does one add a vertical line to a ggplot plot that uses a log scale on the vertical axis?

For example,

ggplot(data.frame(x=1:2, y=c(10,20)), aes(x,y)) + 
  geom_line() + 
  geom_vline(xintercept = 1.5)

works as expected. If one transforms the vertical axis to a log scale:

ggplot(data.frame(x=1:2, y=c(10,20)), aes(x,y)) +
  geom_line() + 
  geom_vline(xintercept = 1.5) + 
  coord_trans(y = 'log')

then the vertical line disappears. Perhaps relevant is that if one changes the data slightly:

ggplot(data.frame(x=1:2, y=c(1,20)), aes(x,y)) + # y[1] is now different
  geom_line() + 
  geom_vline(xintercept = 1.5) + 
  coord_trans(y = 'log')

then the vertical line is still missing, but a warning message is issued:

Warning messages:
1: In self$trans$y$transform(y) : NaNs produced
2: In trans$transform(value) : NaNs produced

So it's possible that the missing line is caused by trying to take logs of 0 (-Inf and no warning) or negative numbers (NaN and a warning).

(sessionInfo() gives R version 3.3.1 (2016-06-21) and ggplot2_2.2.0.)

like image 494
banbh Avatar asked Oct 29 '22 13:10

banbh


1 Answers

I think your hunch is correct, that the problem is that geom_vline is trying to take a log of zero for the intercept. You can instead use, geom_line, to draw a line segment that does not cross zero.

ggplot(data.frame(x=1:2, y=c(10,20)), aes(x,y)) +
  geom_line() + 
  geom_line(aes(x=c(1.5,1.5), y=c(0.1,200))) + 
  coord_trans(y = 'log', limy = c(10,20))

enter image description here

like image 150
dww Avatar answered Nov 15 '22 07:11

dww