[問題]
新手剛學ggplot2一週,已經畫出一個gantt chart.想再加上第二個X軸,並且把legend
text 移到水平的bars的上方。先謝謝了。
這是已經畫出的圖
https://hackmd.io/_uploads/ry8ezMD82.png
這是想要的圖
https://hackmd.io/_uploads/ry2HQfD8n.jpg
第二個X軸的部分,我所看到的例子只用了一個變數,但是我的數據是事件的開始及結束
時間,可能要用到2個變數(AESTDY,AEENDY)。
[數據]
變數說明:
AETERM: 事件名
AESTDTC: 事件的開始日期
AESTDY: 事件的開始天數
AEENDTC:事件的結束日期
AEENDY: 事件的結束天數
SUBJID: Subject ID
[程式碼]
我把程式碼貼在hackmd note裡,比較容易看。圖也在裡頭
https://hackmd.io/@Chang/adverse-events-gantt-chart
以下是程式碼:
# Sample data
sample.data <- data.frame(AESEQ=c(4:1)
,AETERM=c("Tearing", "Grittiness", "eyelid
itchiness","Eyelid margin crusting")
,AESTDTC=c("2022-02-06","2022-02-06","2022-02-06","2022-01-16")
,AESTDY=c(25, 25, 25, 4)
,AEENDTC=c("2022-02-12","2022-03-12","2022-02-12","2022-01-22")
,AEENDY=c(31,59,31,10)
,SUBJID=rep("023-302", 4)
)
SUBJID <- unique(sample.data$SUBJID)
sample.data %>%
ggplot2::ggplot(aes(xmin = AESTDTC, xmax = AEENDTC, y = SUBJID, color =
AETERM)
,show.legend = TRUE) +
ggplot2::geom_linerange(linewidth = 5, position = position_dodge(width =
0.5)
,show.legend = TRUE) +
ggplot2::labs(title = paste0("Adverse events of subject ", SUBJID)
,x = "Start and end dates"
,y="") +
ggplot2::theme_minimal(base_size = 16)+
# Rotate and space bottom x axis label text
ggplot2::theme(axis.text.x = element_text(angle = 0, vjust = 0.5, hjust=1)
# Remove y axis label
,axis.text.y=element_blank()
# Legend position: top right inside plot
## The coordinates for legend.position are x- and y- offsets from the
bottom-left of the plot, ranging from 0 - 1.
,legend.position = c(0.75,0.8))