[英]How to plot date interval with event between in R
我有一個數據框,其ID與開始日期,結束日期以及與前兩個事件之間發生的事件對應的ID有關。
我想在縱坐標上繪制ID,在橫坐標上繪制日期,並在所考慮的時間段的開始和結束之間划一條線,並為事件日期畫一個圓圈(或其他形狀)。
幾個小時以來,我一直在努力尋找合適的解決方案,因此,我們將不勝感激!
library(tidyverse)
set.seed(2018-11-11)
df <- data_frame(
ID = c('A', 'B', 'C'),
begin = seq(as.Date("2017-06-01"), as.Date("2017-08-31"), "1 month"),
event = seq(as.Date("2018-06-01"), as.Date("2018-08-31"), "1 month"),
end = seq(as.Date("2020-06-01"), as.Date("2020-08-31"), "1 month")
)
ggplot(df, aes(x = begin, y = ID, group = ID)) +
geom_point() +
geom_line()+
xlab('Dates') +
ylab('ID')
這是你想要的嗎:
library(tidyverse)
set.seed(2018-11-11)
# data_frame is sort of depreciated (The warning suggested me to use tibble instead)
df <- tibble(
ID = c('A', 'B', 'C'),
begin = seq(as.Date("2017-06-01"), as.Date("2017-08-31"), "1 month"),
event = seq(as.Date("2018-06-01"), as.Date("2018-08-31"), "1 month"),
end = seq(as.Date("2020-06-01"), as.Date("2020-08-31"), "1 month")
)
# -------------------------------------------------------------------------
#df
# # A tibble: 3 x 4
# ID begin event end
# <chr> <date> <date> <date>
# 1 A 2017-06-01 2018-06-01 2020-06-01
# 2 B 2017-07-01 2018-07-01 2020-07-01
# 3 C 2017-08-01 2018-08-01 2020-08-01
# -------------------------------------------------------------------------
base <- ggplot(df, aes(x = begin, y = ID))
# add a duration between begin and end using a horizontal segment
b_duration <- base + geom_segment(aes(x = begin, xend = end, y = ID, yend=ID), linetype = "dashed", color = "red")
# add a the event date using a circle (point)
b_duration + geom_point(aes(event), size=4, color = "cyan4") + theme_bw()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.