如何用ggplot复刻qgraph包centralityPlot生成的中心性图?
问题:复刻qgraph包的centralityPlot并为均值点添加连接线
我想要复刻qgraph包中centralityPlot生成的中心性图,现有如下数据框:
temporal.dep.in <- structure(list( symptom = c("9", "8", "7", "6", "5", "4", "3", "2", "1"), lower_bound = c(0.209023862993771, -0.656057911395765, -0.144732954079441, -0.240150983834066, -2.09690619987396, -1.14713000698362, -1.78304406354482, -1.31269792892215, -1.04552934099257), mean = c(1.35359542511945, 0.546873106351184, 0.787717966105717, 0.42221064177518, -1.18693181743255, -0.284265955202698, -1.19008711707311, -0.377827032555581, -0.0712852170875892), upper_bound = c(1.9749871489344, 1.54642345677796, 1.46727206716789, 1.10712439281518, -0.0748008645128608, 0.812125575894532, -0.510038969136605, 0.587753574399307, 0.981045133733119) ), class = "data.frame", row.names = c(NA, -9L))
目标图样式:每个症状对应一条垂直的置信区间线段,均值点用红色圆点标记,且所有均值点之间用红色折线连接。
目前用ggplot绘制的效果不理想,核心问题是无法将均值点用线连接,现有代码如下:
temporal.dep.in.plot <- ggplot(temporal.dep.in, aes(x = symptom)) + ylim(NA, 2.25) + geom_errorbar( aes(ymin = lower_bound, ymax = upper_bound), width = 0.4, color = "#56B4E9" ) + geom_segment( aes(y = lower_bound, yend = upper_bound, xend = symptom), linetype = "solid", color = "#2166AC", size = 6 ) + geom_point( aes(y = mean), shape = 16, size = 9, color = "#D6604D" ) + theme_classic() + coord_flip() + ylab("Z-scores") + xlab("Symptoms") + theme(axis.text.y = element_text( face = "bold", colour = c( "#ff0000", "#ffaa00", "#aaff00", "#00ff00", "#00ffaa", "#00aaff", "#0000ff", "#aa00ff", "#ff00aa" ), size = 14 ))
解决方案
无法连线的核心原因是未指定连线的分组(group=1),同时需要调整图层顺序让线显示在点下方。修改后的完整代码如下:
library(ggplot2) temporal.dep.in.plot <- ggplot(temporal.dep.in, aes(x = symptom)) + ylim(NA, 2.25) + # 置信区间竖线(调整size避免过粗遮挡连线) geom_segment( aes(y = lower_bound, yend = upper_bound, xend = symptom), linetype = "solid", color = "#2166AC", size = 4 ) + # 置信区间误差条 geom_errorbar( aes(ymin = lower_bound, ymax = upper_bound), width = 0.4, color = "#56B4E9" ) + # 添加均值点连线:指定group=1确保所有点连为一条线,放在点之前避免遮挡 geom_line(aes(y = mean, group = 1), color = "#D6604D", size = 1.5) + # 均值点 geom_point( aes(y = mean), shape = 16, size = 9, color = "#D6604D" ) + theme_classic() + coord_flip() + ylab("Z-scores") + xlab("Symptoms") + theme(axis.text.y = element_text( face = "bold", colour = c( "#ff0000", "#ffaa00", "#aaff00", "#00ff00", "#00ffaa", "#00aaff", "#0000ff", "#aa00ff", "#ff00aa" ), size = 14 )) print(temporal.dep.in.plot)
关键修改说明
- 添加
geom_line(aes(y = mean, group = 1)):group=1告诉ggplot将所有点视为同一组,从而连成一条折线; - 调整图层顺序:将
geom_segment和geom_errorbar放在最前面,geom_line放在geom_point之前,确保连线不会被点或粗竖线遮挡; - 减小
geom_segment的size值(从6改为4),避免过粗的竖线挡住连线。
内容的提问来源于stack exchange,提问作者Jesse Wonnink
相关产品推荐
相关产品推荐

