1

I'm trying to use geom_rect to colour parts of my time series (values), based on the 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 ...

The code:

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

Unfortunately, I get an error:

geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?

What am I doing wrong?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
thesecond
  • 362
  • 2
  • 9

1 Answers1

1

All in all your code works perfect:

Just change idx to numeric, will solve the issue:

See here answer from Xin Niu 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()) 

data:

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

enter image description here

TarJae
  • 72,363
  • 6
  • 19
  • 66