我已經獲得了 2 個回歸模型的資料(都得到了具有相應 CI 下限和上限的估計值)。兩個模型都包含 3 個變數(年齡、性別和吸煙狀況)。變數term(對應于模型中的變數)是有序的,所以它按照我指定的順序出現。
資料如下所示:
library(tidyverse)
library(ggplot2)
mydata <- structure(list(term = structure(c(1L, 1L, 2L, 2L, 3L, 4L, 4L,
5L, 5L), .Label = c("Age (years)", "Sex (male)", "Never smoking (reference)",
"Current smoking", "Former smoking", ">90 (reference)", "60-89",
"<60"), class = c("ordered", "factor")), estimate = c(1.5, 2.2,
0.7, 1.8, 1, 1.5, 2.2, 0.7, 1.6), conf_low = c(1.3, 1.8, 0.9,
1, 1, 1.3, 1.8, 0.9, 1), conf_high = c(1.7, 2.6, 0.5, 2.6, 1,
1.7, 2.6, 0.5, 2.4), model = structure(c(1L, 2L, 1L, 2L, NA,
1L, 2L, 1L, 2L), .Label = c("Model 1", "Model 2"), class = c("ordered",
"factor")), label = structure(c(3L, 6L, 1L, 5L, 2L, 3L, 6L, 1L,
4L), .Label = c("0.7 (0.9-0.5)", "1.0 (1.0-1.0)", "1.5 (1.3-1.7)",
"1.6 (1.0-2.4)", "1.8 (1.0-2.6)", "2.2 (1.8-2.6)"), class = "factor")), row.names = c(NA,
-9L), class = c("tbl_df", "tbl", "data.frame"))
head(mydata)
# A tibble: 6 x 6
term estimate conf_low conf_high model label
<ord> <dbl> <dbl> <dbl> <ord> <fct>
1 Age (years) 1.5 1.3 1.7 Model 1 1.5 (1.3-1.7)
2 Age (years) 2.2 1.8 2.6 Model 2 2.2 (1.8-2.6)
3 Sex (male) 0.7 0.9 0.5 Model 1 0.7 (0.9-0.5)
4 Sex (male) 1.8 1 2.6 Model 2 1.8 (1.0-2.6)
5 Never smoking (reference) 1 1 1 NA 1.0 (1.0-1.0)
6 Current smoking 1.5 1.3 1.7 Model 1 1.5 (1.3-1.7)
我做了以下情節:
ggplot(data=mydata,
aes(x=estimate,
y=fct_rev(term),
color=model))
geom_point(position=position_dodge(width=0.3))
geom_errorbarh(aes(xmin=conf_low, xmax=conf_high, height=0.15), position=position_dodge(width=0.3))

現在我進一步嘗試實作我無法作業的兩件事:
- 我想
Never smoking (reference)在 Y 軸的圖中添加一個標題/變數名稱,以便在該標簽上方顯示吸煙狀態(粗體)。我可以在原始資料框中添加另一行,但是標題和“從不吸煙”之間的距離會有點大。有沒有辦法在其他情況下添加標題,或者有辦法調整 Y 軸上某些標簽之間的特定距離? label資料集中還有一列,對應于估計值和 95%CI。我想將其添加為圖右側的額外列,以便它們與相應的點/誤差條處于相同的高度。
謝謝!
uj5u.com熱心網友回復:
實作所需結果的一種選擇是用于annotation_custom添加組標題并geom_text用于添加錯誤欄的文本標簽:
注意:要將注釋放在我使用的圖之外 coord_cartesian(clip = "off")
library(ggplot2)
library(forcats)
ggplot(
data = mydata,
aes(
x = estimate,
y = fct_rev(term),
color = model
)
)
geom_point(position = position_dodge(width = 0.3))
geom_errorbarh(aes(xmin = conf_low, xmax = conf_high, height = 0.15), position = position_dodge(width = 0.3))
annotation_custom(grob = grid::textGrob(label = "Smoking status", gp = grid::gpar(fontface = "bold"), hjust = 1), xmin = -Inf, xmax = -Inf, ymin = 3.2, ymax = 3.2)
geom_text(aes(x = max(conf_high) * 1.05, label = label, group = model), position = position_dodge(width = 0.3), hjust = 0, show.legend = FALSE, color = "black")
scale_x_continuous(expand = expansion(mult = c(.05, .3)))
coord_cartesian(clip = "off")
#> Warning: Removed 1 rows containing missing values (geom_point).

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/371926.html
