Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

highlight areas within certain x range in ggplot2

Tags:

plot

r

ggplot2

I want highlight certain areas of a ggplot2 graph similar to what is done here: How to highlight time ranges on a plot?

I have a vector v 0 0 1 1 1 ... which indicates at each time whether I want that part of the graph highlighted, yes or no. That is, contrary to the question above, I do not have the xmin and xmax values for each of the ranges that should be highlighted, but I also doubt this would work since I need more than one range to be highlighted.

Is there a way to write a plot statement for the highlighting with something like dates[v == 1] (dates is the vector with dates for the x-axis of the plot)? If not, is there another good way to do it?

like image 591
dreamer Avatar asked Sep 12 '15 20:09

dreamer


People also ask

How do I highlight certain data points in R?

We can use the new data frame containing the data points to be highlighted to add another layer of geom_point(). Note that we have two geom_point(), one for all the data and the other for with data only for the data to be highlighted.

Can you filter in Ggplot?

ggplot2 allows you to do data manipulation, such as filtering or slicing, within the data argument.

What is GG in Ggplot?

ggplot2 is a system for declaratively creating graphics, based on The Grammar of Graphics. You provide the data, tell ggplot2 how to map variables to aesthetics, what graphical primitives to use, and it takes care of the details.


1 Answers

Using diff to get regions to color rectangles, the rest is pretty straightforward.

## Example data
set.seed(0)
dat <- data.frame(dates=seq.Date(Sys.Date(), Sys.Date()+99, 1),
                  value=cumsum(rnorm(100)))

## Determine highlighted regions
v <- rep(0, 100)
v[c(5:20, 30:35, 90:100)] <- 1

## Get the start and end points for highlighted regions
inds <- diff(c(0, v))
start <- dat$dates[inds == 1]
end <- dat$dates[inds == -1]
if (length(start) > length(end)) end <- c(end, tail(dat$dates, 1))

## highlight region data
rects <- data.frame(start=start, end=end, group=seq_along(start))

library(ggplot2)
ggplot(data=dat, aes(dates, value)) +
  theme_minimal() +
  geom_line(lty=2, color="steelblue", lwd=1.1) +
  geom_point() +
  geom_rect(data=rects, inherit.aes=FALSE, aes(xmin=start, xmax=end, ymin=min(dat$value),
                ymax=max(dat$value), group=group), color="transparent", fill="orange", alpha=0.3)

enter image description here

like image 164
Rorschach Avatar answered Sep 21 '22 16:09

Rorschach