我想在同一图形上显示geom_line和状态(在矢量中)。
数据例如:
Timestamp;Value;State
20190618;1.2;UP
20190619;1.0;DOWN
20190620;1.1;UP
...
这是我想要获得的示例:
我知道如何使用geom_line,我已经尝试使用geom_area,但是这些尝试都没有成功。 有什么帮助吗? :-)
答案 0 :(得分:0)
library(tidyverse)
ggplot(df) +
geom_rect(aes(xmin = Timestamp, xmax = lead(Timestamp),
ymin = 0, ymax = Inf,
fill = State), alpha = 0.2) +
geom_step(aes(Timestamp, Value))
# based on your data, after converting into table with Timestamp as a date
df <- structure(list(Timestamp = structure(c(18065, 18066, 18067), class = "Date"),
Value = c(1.2, 1, 1.1), State = c("UP", "DOWN", "UP")),
class = "data.frame", row.names = c(NA, -3L))
答案 1 :(得分:0)
这是您要寻找的(替代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()