3

I am using ggplot2 in R to plot some data from a csv file. I am particularly interested in seeing the discontinuities in the data. On my line graphs, ggplot leaves gaps in the lines, but I'd like to go even further and highlight the background when these discontinuities occur. Is there a way to do this? I saw this answer(ggplot2: highlight chart area) but I couldn't understand their solution enough to attempt to make it work for me(I'm fairly inexperienced with ggplot).

Here's one of the graphs:

Basically I want to highlight the background of those gaps on the right in transparent red.

Here is the code I'm using to generate the graph:

p5 <- ggplot(d2.m, aes_string(x="timestamp",y="value")) +
      geom_line() +
      ylab("Latency (s)") +
      xlab("Time (s)") +
      scale_y_continuous(labels = comma) +
      facet_wrap(~variable, scales="free", ncol=1)

print(p5)
Community
  • 1
  • 1
turnerba
  • 145
  • 1
  • 4
  • It's difficult to help without a minimal working example. Can you provide data (`d2.m`)? – Tyler Rinker Apr 11 '15 at 21:36
  • likely best way is to use `geom_segment` setting the y limit as inf and the x limits as the range of the NA values on the x axis – jalapic Apr 11 '15 at 21:38

1 Answers1

4

You could use this geom_rect solution:

require(ggplot2)

set.seed(1337)
dat <- data.frame(x = 1:11, y = sample(c(1:5, rep(NA,2)), 11, replace = TRUE))
ggplot() + 
  geom_line(data = dat, aes(x = x, y = y)) 

Actual Code

cum_sum <- cumsum(is.na(dat$y))
diff_diff <- diff(diff(cum_sum)) # change of the slope
start <- which(diff_diff== 1)+1 # positive inflection point's
if (is.na(dat$y[1])) start <- c(1,start)
end <- which(diff_diff == -1)+2 # negative inflection point's
if (is.na(tail(dat$y,1))) end <- c(end, length(dat$y))

dat_rect <- data.frame(xmin = start, xmax = end)

ggplot() + 
  geom_line(data = dat, aes(x = x, y = y)) +
  geom_rect(data = dat_rect, alpha = 0.3, aes(xmin = xmin, xmax = xmax, ymin = -Inf, ymax = Inf))

Result: enter image description here

Rentrop
  • 20,979
  • 10
  • 72
  • 100