【问题标题】:Highlight values with a rectangle/shaded area in ggplot2 [duplicate]在ggplot2中用矩形/阴影区域突出显示值[重复]
【发布时间】:2019-02-13 21:25:36
【问题描述】:

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

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.")

我生成了这张图片:

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

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

【问题讨论】:

  • 或许geom_rect

标签: r ggplot2 time-series


【解决方案1】:

正如@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
  )

【讨论】:

    【解决方案2】:

    这将创建一个打开的框,但如果需要,在末尾添加一个额外的点可以将其关闭:

    + geom_path(data=data.frame(y=c(0,-2,-2,0), x=as.Date('1980-01-01')+30*c(40,40,60,60)),
                mapping=aes(x=x,y=y)) 
    

    主要的障碍是要认识到 x 轴是日期分类的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-21
      • 2012-12-24
      • 2011-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-09
      • 2023-03-10
      相关资源
      最近更新 更多