我有以下数据
MIN MAX GENDER
01/01/2002 17/12/2010 MAN
04/05/2012 07/08/2018 WOMAN
我试图为每行绘制一条从MIN
开始到MAX
结束的线,如图所示。
我正在尝试ggplot2
date <- c("2002-01-01", "2010-12-17", "2012-04-05", "2018-08-07"
group <- c("Man", "Woman")
df <- as.data.frame(cbind(date, group))
library(tidyverse)
df %>%
mutate(date = as.POSIXct(date)) %>% #convert to date
group_by(group, date) #group
但是找不到如何绘制日期之间的差异来画线。
答案 0 :(得分:0)
txt <- "MIN MAX GENDER
01/01/2002 17/12/2010 MAN
04/05/2012 07/08/2018 WOMAN"
dta <- read.table(textConnection(txt), header =TRUE)
dta$MIN <- as.Date(dta$MIN, format = "%d/%m/%Y")
dta$MAX <- as.Date(dta$MAX, format = "%d/%m/%Y")
dta %>%
group_by(GENDER) %>%
tidyr::gather(key, value, -GENDER) %>%
ggplot(aes(GENDER, value)) +
geom_line(aes(color = GENDER)) +
coord_flip() +
scale_y_date(breaks = c(dta$MIN, dta$MAX)) +
theme(axis.text.x = element_text(angle = 45, hjust = 1))