【问题标题】:highlight areas within certain x range in ggplot2在ggplot2中突出显示特定x范围内的区域
【发布时间】:2015-09-12 20:04:30
【问题描述】:

我想突出显示 ggplot2 图表的某些区域,类似于此处所做的:How to highlight time ranges on a plot?

我有一个向量 v 0 0 1 1 1 ...,它每次都指示我是否要突出显示图表的那部分,是或否。也就是说,与上述问题相反,我没有每个应突出显示的范围的 xmin 和 xmax 值,但我也怀疑这是否可行,因为我需要突出显示多个范围。

有没有办法用dates[v == 1] 之类的东西为突出显示编写绘图语句(日期是绘图x 轴的带有日期的向量)? 如果没有,有没有其他的好方法?

【问题讨论】:

  • 为什么不添加一个数据框和 ggplot2 代码的最小工作示例,以帮助人们帮助您。

标签: r plot ggplot2


【解决方案1】:

使用diff 让区域为矩形着色,其余部分非常简单。

## 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)

【讨论】:

    猜你喜欢
    • 2012-08-21
    • 2022-06-14
    • 2011-04-06
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多