[英]geom_rect to show variation of a categorical variable in the background of line plot
geom_rect
)。library(tidyverse)
tbl <- tibble(time = 1:100,
output = - time^2 + 5*time,
duration = c(rep("start", 30), rep("mid", 40), rep("end", 30)),
energy = c(rep("high", 40), rep("medium", 30), rep("low", 30)))
ggplot(data = tbl,
aes(x = time,
y = output,
color = duration)) +
geom_line() +
theme_bw()
我使用 data.table 創建輔助表能量,我很確定如果您更喜歡另一種方法,您可以輕松轉換它。
setDT(tbl)
library(data.table)
energy <- tbl[, .(first = first(time), last = last(time)), by = energy]
ggplot(data = tbl) +
geom_line(aes(x = time, y = output, color = duration), size = 2) +
geom_rect(data = energy, aes(NULL, NULL, xmin = first, xmax = last, fill = energy), ymin = -Inf, ymax = Inf, alpha = 0.3)
我無法評論,但如果你想要 dplyr 版本,一種選擇是
energy= tbl %>% group_by(energy) %>% mutate(first= first(time), last=last(time)) %>%
select(energy, first, last) %>% distinct()
但我喜歡 data.table 版本
如果您覆蓋y
值,您應該能夠將其添加為另一層。 通過添加alpha = (% transparent)
添加透明度。
ggplot(data = tbl, aes(x = time, y = output, color = duration)) +
geom_line()+
geom_rect(y= anothery, alpha = 0.5)+
theme_bw()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.