我正在生成一個圖表以圖形方式顯示估計值和 CI。現在我的估計和 y 軸標簽在圖上不同步。
如果這是我的資料集。
Group Est conf.low conf.high pvalue
Bi 1.12 0.65 1.603 0.000
Di -0.24 -0.44 -0.038 0.02
Dn -0.47 -0.80 -0.140 0.005
HMD -0.006 -0.32 0.311 0.968
HMS 0.72 -1.00 -0.436 0.000
LM -0.055 -0.32 0.214 0.6886
PaS -1.31 -1.79 -0.850 0.000
Ph A 0.065 -0.250 0.381 0.6885
TRB 1.023 0.63 1.41 0.000
TRC -0.599 -0.94 -0.249 0.0008
我看到的是下面這樣的圖,其中 y 軸標簽和估計完全亂序。

這是我的代碼
ggplot(df, aes(y = row.names(df), x= Est))
geom_point(shape = 16, size =5)
scale_y_discrete(label = df$Group)
geom_errobarh(aes(xmin = conf.low, xmax = conf.high), width =0, size = 1)
geom_vline(xintercept=1, color="black", linetype = "dashed", cex=1, alpha=0.5)
非常感謝有關如何將我的 y 軸標簽與估計值同步的任何幫助。謝謝。
uj5u.com熱心網友回復:
如果您希望繪圖以與資料框中的資料相同的順序出現,則需要Group在 y 軸上繪圖,但首先將其轉換為水平與列相反的因子Group:
library(ggplot2)
ggplot(df, aes(y = factor(Group, rev(Group)), x = Est))
geom_point(shape = 16, size = 5)
geom_text(aes(label = Est), nudge_y = 0.3, size = 4)
geom_errorbarh(aes(xmin = conf.low, xmax = conf.high), height = 0, size = 1)
geom_vline(xintercept = 1, linetype = "dashed", cex = 1, alpha = 0.5)
labs(y = "Group")
theme_gray(base_size = 16)

可重現的資料
df <- structure(list(Group = c("Bi", "Di", "Dn", "HMD", "HMS", "LM",
"PaS", "Ph A", "TRB", "TRC"), Est = c(1.12, -0.24, -0.47, -0.006,
-0.72, -0.055, -1.31, 0.065, 1.023, -0.599), conf.low = c(0.65,
-0.44, -0.8, -0.32, -1, -0.32, -1.79, -0.25, 0.63, -0.94), conf.high = c(1.603,
-0.038, -0.14, 0.311, -0.436, 0.214, -0.85, 0.381, 1.41, -0.249
), pvalue = c(0, 0.02, 0.005, 0.968, 0, 0.6886, 0, 0.6885, 0,
8e-04)), class = "data.frame", row.names = c(NA, -10L))

uj5u.com熱心網友回復:
學分:我忘記了上面的值,從艾倫卡梅倫的回答中更正復制并粘貼。
這是一個解決方案,reorder將 y 軸按條形中點的順序排列Est。
df1<-"Group Est conf.low conf.high pvalue
Bi 1.12 0.65 1.603 0.000
Di -0.24 -0.44 -0.038 0.02
Dn -0.47 -0.80 -0.140 0.005
HMD -0.006 -0.32 0.311 0.968
HMS -0.72 -1.00 -0.436 0.000
LM -0.055 -0.32 0.214 0.6886
PaS -1.31 -1.79 -0.850 0.000
'Ph A' 0.065 -0.250 0.381 0.6885
TRB 1.023 0.63 1.41 0.000
TRC -0.599 -0.94 -0.249 0.0008"
df1 <- read.table(textConnection(df1), header = TRUE)
library(ggplot2)
ggplot(df1, aes(x = Est, y = reorder(Group, -Est)))
geom_pointrange(aes(xmin = conf.low, xmax = conf.high), size = 1)
geom_text(aes(label = Est), nudge_y = 0.3, size = 4)
geom_vline(xintercept = 1, linetype = "dashed", alpha = 0.5)
ylab("Group")

使用reprex v2.0.2創建于 2022-10-29
并帶有誤差線,而不是線形。這一次,這些點需要顯式呼叫geom_point.
ggplot(df1, aes(x = Est, y = reorder(Group, -Est)))
geom_point(pch = 16, size = 5)
geom_errorbarh(aes(xmin = conf.low, xmax = conf.high), height = 0.5, size = 1)
geom_text(aes(label = Est), nudge_y = 0.3, size = 4)
geom_vline(xintercept = 1, linetype = "dashed", alpha = 0.5)
ylab("Group")

使用reprex v2.0.2創建于 2022-10-29
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/523451.html
標籤:rggplot2
