This is my test dataset
State MinWage From To DataFrom DataTo
AK No 1994 2017
AL No 1994 2017 2005 2019
AR No 1994 2017 2006 2018
AZ No 1994 2017 2005 2019
CA Yes 2015 2017 1992 2019
CO Yes 1999 2017
CT Yes 2011 2017 2003 2019
DC Yes 2000 2017 2003 2017
I am trying to create a timeline line like this where each state is in a swimlane
The broken lines depict DataFrom - DataTo
The solid lines depict From - To
Red lines are those with MinWage=No
Blue lines are those with MinWage=Yes
Any suggestions on how to plot this figure is much appreciated.
CodePudding user response:
You may try(do not know condition of color)
library(dplyr)
library(ggplot2)
df %>%
rowwise %>%
mutate(DataFrom = ifelse(is.na(DataFrom), From, DataFrom),
DataTo = ifelse(is.na(DataTo), From, DataTo)) %>%
ggplot(aes(group = State))
geom_segment(aes(x = DataFrom, xend = DataTo, y = State, yend = State), linetype = 2)
geom_segment(aes(x = From, xend = DataFrom, y = State, yend = State))
geom_segment(aes(x = DataTo, xend = To, y = State, yend = State))
CodePudding user response:
library(tidyverse)
df %>%
ggplot(aes(group = State, color = MinWage, y = State, yend = State))
geom_segment(aes(x = From, xend = pmin(To, DataFrom, na.rm = T)))
geom_segment(aes(x = pmax(From, DataFrom), xend = pmin(DataTo, To)), linetype = 2)
geom_segment(aes(x = pmax(From, DataTo), xend = To), color = "blue")
scale_color_manual(values = c("red", "blue"))
geom_text(aes(x = From, label = From), color = "darkgrey", vjust = 1.5)
geom_text(aes(x = To, label = To), color = "darkgrey", vjust = 1.5)
geom_text(aes(x = DataFrom, label = DataFrom), color = "darkgrey", vjust = 1.5)
geom_text(aes(x = DataTo, label = DataTo), color = "darkgrey", vjust = 1.5)
theme_minimal()
scale_x_continuous(breaks = seq(1990, 2020, 5), limits = c(1990, 2020))
theme(panel.grid = element_blank())
labs(x = NULL)
guides(color = "none")
Created on 2022-07-05 by the reprex package (v2.0.1)