r - ggplot2 中用矩形/阴影区域突出显示值

标签 r ggplot2 time-series

大家好,我有以下示例数据:

library(ggplot2)
library(reshape)
library(tidyr)
library(dplyr)


set.seed(78)
vector <- runif(n = 360, min = -4, max = 4)
dates <- seq(as.Date('1980-01-01'), length.out=360, by='1 month')


df <- data.frame(dates = dates, index = vector)

#Aqui ya se hace la diferencia entre positivo y negativo con color
df$colour <- ifelse(df$index < 0, "Negative","Positive")
ggplot(df,aes(dates,index,label=""))+
  geom_bar(stat="identity",position="identity",aes(fill = colour))+
  scale_fill_manual(name = "Valor", values=c(Positive="firebrick",Negative="dodgerblue4"))+
  ggtitle("Index")+
  theme(plot.title = element_text(hjust = 0.5))+
  xlab("Year") + ylab("S.D.")

我生成了这个图像:

enter image description here

我想做的是用正方形或其他东西突出显示特定的时间间隔,所以它看起来像这样:

enter image description here

正如我所说,不一定是实线,它可以是阴影区域,有人知道我该怎么做吗?

最佳答案

正如 @dww 提到的,geom_rect 有效。添加下面的层:

  geom_rect(
    aes(
      xmin = as.Date('1993-06-01'),
      xmax = as.Date('1994-11-01'),
      ymin = min(index),
      ymax = 0
    ),
    fill = NA,
    color = "black",
    size = 2
  )

enter image description here

关于r - ggplot2 中用矩形/阴影区域突出显示值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54679680/

相关文章:

r - 将不同的预测方法传递给 R 中的分层时间序列预测?

在 R : from wide to long, 中 reshape 数据框,但 'varying' 列的长度不等

r - 如何展开使用 R 中的 igraph 包制作的社区图

r - 如何将 ggrepel 与生存图 (ggsurvplot) 结合使用?

R - ggplot2 - 获取两组差异的直方图

python - 创建一个新变量,它是 python 中另一个变量的每周最小/最大值

r - 使用来自预测的准确度()测量 VAR 准确度

r - 在 R 中绘制两个条形图

r - XTS 将功能应用于一天中的时间子集?

r - 仅绘制 y 轴,不绘制其他任何内容