我正在運行回歸并使用 ggplots 呈現結果。通常,目的是查看在第 2 階段發生的政策的動態效果。
我正在繪制回歸結果,我從回歸函式創建的資料框看起來像
dfplot1 <- data.frame(coef=c(0.05,0,0.1,0.15,0.2),
se=c(0.1,0,0.1,0.1,0.1),
period=1:5)
dfplot2 <- data.frame(coef=c(0.05,0,0.12,0.18,0.24),
se=c(0.12,0,0.12,0.12,0.12),
period=1:5)
我使用標準誤差繪制系數
library(ggplot2)
library(patchwork)
p1 <- ggplot(dfplot1)
geom_point(aes(x=period, y=coef))
geom_segment(aes(x=period, xend=period, y=coef-1.96*se, yend=coef 1.96*se))
geom_segment(aes(x=period, xend=period, y=coef-1.96*se, yend=coef 1.96*se))
labs(x='Year', y='Coefficients')
geom_hline(yintercept = 0, linetype = "dashed")
theme(panel.background = element_blank())
p2 <- ggplot(dfplot2)
geom_point(aes(x=period, y=coef))
geom_segment(aes(x=period, xend=period, y=coef-1.96*se, yend=coef 1.96*se))
geom_segment(aes(x=period, xend=period, y=coef-1.96*se, yend=coef 1.96*se))
labs(x='Year', y='Coefficients')
geom_hline(yintercept = 0, linetype = "dashed")
theme(panel.background = element_blank())
p1|p2
圖看起來,

我可以在每個 ggplot 中使用 ylim 來設定 y 軸限制并使它們相同
p1 ylim(-0.5,0.5)
p2 ylim(-0.5,0.5)

為了更好地可視化和比較這兩個回歸中具有不同協變數的系數,有沒有辦法自動找到最佳擬合并對齊兩個 ggplots 的軸?
非常感謝!
uj5u.com熱心網友回復:
您可以使用 獲取兩個圖中的范圍layer_scales,然后獲取要在range中使用的連接結果的整體ylim。這避免了猜測的需要。
lim <- range(c(layer_scales(p1)$y$range$range, layer_scales(p2)$y$range$range))
p1 ylim(lim) | p2 ylim(lim)

uj5u.com熱心網友回復:
你可以facet_wrap:
library(tidyverse)
dfplot1 <- data.frame(coef=c(0.05,0,0.1,0.15,0.2),
se=c(0.1,0,0.1,0.1,0.1),
period=1:5)
dfplot2 <- data.frame(coef=c(0.05,0,0.12,0.18,0.24),
se=c(0.12,0,0.12,0.12,0.12),
period=1:5)
df <- bind_rows(dfplot1, dfplot2, .id = "id")
df |> ggplot(aes(period, coef))
geom_point()
geom_segment(aes(xend = period, y = coef - 1.96 * se, yend = coef 1.96 * se))
labs(x = "Year", y = "Coefficients")
geom_hline(yintercept = 0, linetype = "dashed")
facet_wrap(~id)
theme(panel.background = element_blank())

由
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/482174.html
上一篇:如何通過多個變數重新排序條形圖
