首页 > 解决方案 > 如何在 geom_line 下添加区域?

问题描述

我想在同一张图上显示 geom_line 和状态(在向量中)。

以数据为例:

Timestamp;Value;State
20190618;1.2;UP
20190619;1.0;DOWN
20190620;1.1;UP
...

这是我想获得的一个例子:

在此处输入图像描述

我知道如何使用 geom_line,我已经尝试使用 geom_area 但这些都没有成功。有什么帮助吗?:-)

标签: rggplot2

解决方案


这是您正在寻找的(替代geom_rect)吗?

在此处输入图像描述

准备示例数据

x <- 1:5
y <- c(4,1,6,2,2)
plot.df <- data.frame(Timestamp=x, Value=y)

情节代码:

library(ggplot2)
ggplot(plot.df, aes(x=Timestamp,y=Value)) +
  annotate("rect", xmin = 1, xmax = 2, ymin = -Inf, ymax = Inf,
           alpha = .2, fill = "green") +
  annotate("rect", xmin = 2, xmax = 3, ymin = -Inf, ymax = Inf,
           alpha = .2, fill = "red") +
  annotate("rect", xmin = 3, xmax = 4, ymin = -Inf, ymax = Inf,
           alpha = .2, fill = "green") +
  geom_step(direction = "h") +
  theme_classic()

推荐阅读