簡體   English   中英

時間序列的陰影 geom_rect,基於列值

[英]Shade geom_rect for time series, based on column value

我正在嘗試使用geom_rect根據state為我的時間序列( values )的部分着色。

    idx  state  value
1    1     S   0.00000
2    2     S   0.00001
3    3     S   0.00016
4    4     S   0.00003
5    5     S   0.00047
6    6     S   0.00002
7    7     J   0.00048
8    8     J   0.00011
9    9     J   0.00001
10  10     J   0.00753
'data.frame':   245 obs. of  3 variables:
 $ idx  : chr  "1" "2" "3" "4" ...
 $ state: chr  "S" "S" "S" "S" ...
 $ value: num  0 0.00001 0.00016 0.00003 ...

編碼:

ggplot(new, aes(x = idx, y = value)) + 
  geom_rect(aes(xmin = idx, xmax = dplyr::lead(idx), ymin = -Inf, ymax = Inf, fill = factor(state)), 
            alpha = .3)  +
  geom_line(aes(x = idx, y = value)) +
  theme(axis.title.y = element_blank()) 

不幸的是,我收到一個錯誤:

geom_path:每組僅包含一個觀察值。 需要調整群體審美嗎?

我究竟做錯了什么?

總而言之,您的代碼完美無缺:

只需將idx更改為數字,即可解決問題:

看到這里來自Xin Niu ggplot2折線圖的回答給出了“geom_path:每個組只包含一個觀察值。你需要調整組審美嗎?”

library(tidyverse)
ggplot(df, aes(x = as.numeric(idx), y = value)) + 
  geom_rect(aes(xmin = idx, xmax = dplyr::lead(idx), ymin = -Inf, ymax = Inf, fill = factor(state)), 
            alpha = .3)  +
  geom_line(aes(x = idx, y = value)) +
  theme(axis.title.y = element_blank()) 

數據:

df <- structure(list(idx = 1:10, state = c("S", "S", "S", "S", "S", 
"S", "J", "J", "J", "J"), value = c(0, 1e-05, 0.00016, 3e-05, 
0.00047, 2e-05, 0.00048, 0.00011, 1e-05, 0.00753)), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8", "9", "10"))

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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