【问题标题】:Shade geom_rect for time series, based on column value时间序列的阴影 geom_rect,基于列值
【发布时间】:2022-01-21 01:22:54
【问题描述】:

我正在尝试使用 geom_rect 为我的时间序列 (values) 的部分着色,基于 state

    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:每个组仅包含一个观察值。是否需要调整 群体审美?

我做错了什么?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    总而言之,您的代码完美无缺:

    只需将idx 更改为数字,即可解决问题:

    看这里来自新牛ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"的回答

    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"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-08
      • 1970-01-01
      • 1970-01-01
      • 2017-04-10
      • 1970-01-01
      • 2011-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多