簡體   English   中英

geom_rect 在 plot 行的背景中顯示分類變量的變化

[英]geom_rect to show variation of a categorical variable in the background of line plot

  1. 下面是 output 與時間的示例。
  2. 我已經使用持續時間為線條着色。
  3. 我還想在 plot 中包含能級。 如何在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM