Thanks for including your expected outcome; here is one potential approach you could try:
library(tidyverse)
df <- data.frame (
time = seq(1, 250),
state = c(rep ("AW", 20), rep ("QW", 35), rep ("NR", 100), rep ("Rt", 40), rep("R", 55)))
df %>%
mutate(state_numeric = case_when(state %in% c("AW", "QW") ~ 1,
state %in% c("Rt", "R") ~ -1,
state == "NR" ~ 0,
TRUE ~ NA_integer_),
state = factor(state, levels = c("AW", "QW", "NR", "Rt", "R"),
labels = c("W", "W", "NR", "R", "R"))) %>%
ggplot(aes(x = time, y = state_numeric)) +
geom_step(aes(group = 1)) +
geom_line(aes(x = time, y = state_numeric, colour = state)) +
labs(title = "Subject 1", x = "Time (s)", y = "State") +
theme_minimal() +
geom_area(aes(fill = state, colour = state),
alpha = 0.3) +
scale_y_continuous(breaks = c(-1, 0, 1), labels = c("R", "NR", "W"))
Created on 2024-07-08 with reprex v2.1.0
Based on your comment (if I just want to color the line, do I only use geom_line? and if I want to identify every state ("AW", "QW", "NR", "Rt", "R")?
), perhaps this is what you want?
library(tidyverse)
df <- data.frame (
time = seq(1, 250),
state = c(rep ("AW", 20), rep ("QW", 35), rep ("NR", 100), rep ("Rt", 40), rep("R", 55)))
df %>%
mutate(state_numeric = case_when(state %in% c("AW", "QW") ~ 1,
state %in% c("Rt", "R") ~ -1,
state == "NR" ~ 0,
TRUE ~ NA_integer_),
state = factor(state, levels = c("AW", "QW", "NR", "Rt", "R"))) %>%
ggplot(aes(x = time, y = state_numeric)) +
geom_step(aes(group = 1)) +
geom_line(aes(x = time, y = state_numeric, colour = state),
linewidth = 2) +
labs(title = "Subject 1", x = "Time (s)", y = "State") +
theme_minimal() +
scale_y_continuous(breaks = c(-1, 0, 1), labels = c("R", "NR", "W"))
Created on 2024-07-09 with reprex v2.1.0