簡體   English   中英

如何自動對齊不同ggplots的軸限制

[英]how to automatically align the axis limits for different ggplots

我正在運行回歸並使用 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 的軸?

非常感謝!

您可以使用layer_scales從兩個圖中獲取范圍,然后獲取要在ylim中使用的串聯結果的總體range 這避免了猜測的需要。

lim <- range(c(layer_scales(p1)$y$range$range, layer_scales(p2)$y$range$range))

p1 + ylim(lim) | p2 + ylim(lim)

在此處輸入圖像描述

你可以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())

reprex 包於 2022-05-27 創建 (v2.0.1)

這一款幾乎是一樣的! 到@Carl's+1。 他的速度更快。 在我看來,主要功能是將bind_rows.id參數一起使用。 這讓我們使用id列作為facet_wrap並且我們可以獲得一個共同的 y 軸:

bind_rows(list(dfplot1 = dfplot1, dfplot2 = dfplot2), .id = 'id') %>% 
  ggplot()+
  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())+
  facet_wrap(.~id)
  

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM