突出显示ggplot2中某些x范围内的区域 [英] highlight areas within certain x range in ggplot2

查看:575
本文介绍了突出显示ggplot2中某些x范围内的区域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想突出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?

解决方案

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)

这篇关于突出显示ggplot2中某些x范围内的区域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆