[问题] add a second x axis

楼主: luenchang (luen)   2023-06-02 15:32:00
[问题]
新手刚学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))

Links booklink

Contact Us: admin [ a t ] ucptt.com