---
webr:
packages: [dplyr, broom, broom.helpers, cardx, car, parameters, ggplot2, ggstats, patchwork, gtsummary] # gtsummary は最後(他パッケージに関数を上書きされないように)
resources: [R/setup.R]
cell-options:
autorun: true
---
{{< include ./_extensions/r-wasm/live/_knitr.qmd >}}
# オッズ比を図にする(フォレストプロット) {#sec-forest}
```{webr}
#| include: false
source("R/setup.R")
library(ggplot2)
library(patchwork)
```
回帰分析の結果は、表だけでなく **フォレストプロット**(推定値と信頼区間を横棒で並べた図)で示すことがよくあります。
この章では、第 @sec-regression 章のロジスティック回帰をフォレストプロットにします。
```{webr}
m <- glm(response ~ age + trt + grade + marker, data = trial, family = binomial)
t_mv <- tbl_regression(m, exponentiate = TRUE)
t_mv
```
## いちばん簡単な方法:`plot()`
gtsummary の回帰表は、そのまま `plot()` に渡すとフォレストプロットになります(内部で ggstats パッケージを使用)。
```{webr}
plot(t_mv)
```
結果は ggplot なので、`+` で ggplot2 の関数を足して調整できます。
```{webr}
plot(t_mv) +
ggplot2::labs(x = "Odds ratio (95% CI)") +
ggplot2::theme_bw()
```
## 表と図を並べる:`ggstats::ggcoef_table()`
論文でよく見る「左に変数、中央に図、右に OR (95% CI) と p 値」の形を1行で作れます。
```{webr}
#| fig-width: 9
#| fig-height: 4
ggstats::ggcoef_table(m, exponentiate = TRUE)
```
::: {.callout-note}
`ggcoef_table()` は gtsummary ではなく **モデルそのもの** (`m`) を受け取ります。
変数ラベルはデータのラベル属性から取られます。
:::
## 自分で作る:表のデータから ggplot
細かい見た目まで思い通りにしたいときは、gtsummary の表の中身(`table_body`)を取り出して、ggplot2 で描きます。
**表と図の数値が必ず一致する** のが利点です。
### ステップ1:データを取り出す
```{webr}
df <- t_mv$table_body |>
select(variable, var_type, row_type, reference_row, label,
estimate, conf.low, conf.high, p.value)
df
```
- `row_type == "label"`:変数名の行(カテゴリ変数では推定値なし)
- `reference_row == TRUE`:参照カテゴリの行(推定値なし)
### ステップ2:図用に整える
```{webr}
df_plot <- df |>
mutate(
# 参照カテゴリは OR = 1 として点だけ打つ
estimate = ifelse(reference_row %in% TRUE, 1, estimate),
# カテゴリの水準は字下げして表示
label = ifelse(row_type == "level", paste0(" ", label), label),
# 上から順に並ぶように y 座標を作る
y = rev(seq_len(n())),
or_text = case_when(
reference_row %in% TRUE ~ "Reference",
is.na(estimate) ~ "",
TRUE ~ sprintf("%.2f (%.2f–%.2f)", estimate, conf.low, conf.high)
),
p_text = ifelse(is.na(p.value), "", style_pvalue(p.value, digits = 3))
)
df_plot |> select(label, y, estimate, or_text, p_text)
```
### ステップ3:フォレストプロット
```{webr}
#| fig-height: 4
p_forest <- ggplot(df_plot, aes(x = estimate, y = y)) +
geom_vline(xintercept = 1, linetype = "dashed", colour = "grey50") +
geom_errorbar(aes(xmin = conf.low, xmax = conf.high), width = 0.2, na.rm = TRUE) +
geom_point(aes(shape = reference_row %in% TRUE), size = 3, na.rm = TRUE) +
scale_shape_manual(values = c(`FALSE` = 15, `TRUE` = 1), guide = "none") +
scale_x_log10() + # オッズ比は対数軸で
scale_y_continuous(breaks = df_plot$y, labels = df_plot$label, expand = expansion(add = 0.6)) +
labs(x = "Odds ratio (95% CI, log scale)", y = NULL) +
theme_minimal(base_size = 13) +
theme(panel.grid.minor = element_blank(),
panel.grid.major.y = element_blank(),
axis.text.y = element_text(hjust = 0))
p_forest
```
::: {.callout-tip}
## なぜ対数軸?
オッズ比 2(2倍)と 0.5(半分)は、効果の大きさとしては同じです。
普通の軸では 1 からの距離が 1 と 0.5 で違って見えますが、対数軸なら 1 を中心に対称になります。
:::
### ステップ4:右側に数値の列を付ける
patchwork パッケージで、図の右に「OR (95% CI)」と「p 値」の文字列の列を並べます。
```{webr}
#| fig-width: 9
#| fig-height: 4
text_col <- function(col, title) {
ggplot(df_plot, aes(x = 0, y = y, label = .data[[col]])) +
geom_text(hjust = 0, size = 4) +
scale_x_continuous(limits = c(0, 1), expand = c(0, 0)) +
scale_y_continuous(limits = range(df_plot$y) + c(-0.6, 0.6), expand = c(0, 0)) +
labs(title = title) +
theme_void(base_size = 13) +
theme(plot.title = element_text(face = "bold", size = 12))
}
p_forest + text_col("or_text", "OR (95% CI)") + text_col("p_text", "p-value") +
plot_layout(widths = c(3, 1.6, 0.8))
```
## 単変量と多変量を並べる
粗オッズ比(単変量)と調整オッズ比(多変量)を同じ図に描くと、交絡の影響が見えます。
```{webr}
#| fig-height: 4.5
t_uv <- trial |>
tbl_uvregression(method = glm, y = response,
method.args = list(family = binomial),
exponentiate = TRUE,
include = c(age, trt, grade, marker))
both <- bind_rows(
t_uv$table_body |> mutate(model = "Univariable"),
t_mv$table_body |> mutate(model = "Multivariable")
) |>
filter(!is.na(estimate)) |> # 推定値のある行だけ
mutate(label = ifelse(row_type == "level", paste(var_label, label), label))
ggplot(both, aes(x = estimate, y = label, colour = model)) +
geom_vline(xintercept = 1, linetype = "dashed", colour = "grey50") +
geom_errorbar(aes(xmin = conf.low, xmax = conf.high), width = 0.2,
position = position_dodge(width = 0.5)) +
geom_point(size = 2.5, position = position_dodge(width = 0.5)) +
scale_x_log10() +
labs(x = "Odds ratio (95% CI)", y = NULL, colour = NULL) +
theme_minimal(base_size = 13) +
theme(legend.position = "bottom")
```
## 論文用に保存する(自分の PC で)
```r
# 投稿規定でよくある:TIFF / 300 dpi / 幅 17 cm
ggsave("figure2_forest.tiff", plot = last_plot(),
width = 17, height = 8, units = "cm", dpi = 300, compression = "lzw")
# ベクター形式(拡大しても劣化しない)
ggsave("figure2_forest.pdf", width = 17, height = 8, units = "cm")
```
::: {.callout-important}
## この章のまとめ
- 手早く:`plot(tbl_regression(...))`、表+図:`ggstats::ggcoef_table(model)`
- 思い通りに:`tbl$table_body` を取り出して ggplot2 で描く → 表と図の数値が一致
- オッズ比・ハザード比は **対数軸**、1 に縦の点線
- patchwork で図の横に数値の列を並べられる
:::