簡體   English   中英

在 ggplot2 中跨多個繪圖創建線

[英]Create line across multiple plots in ggplot2

我想創建一條跨越兩個地塊的水平線,並結合拼湊而成的 package。

library(ggplot2)
library(patchwork)

# Annotation after plot
p1 <- ggplot(mtcars, aes(x=disp,y=mpg))+
  geom_point()
p2 <- ggplot(mtcars, aes(x=hp,y=mpg))+
  geom_point()
# Want line across plots at y (mpg) of 15
p3 <- (p1+p2)+annotate("segment",x=-Inf,xend=Inf,y=15,yend=15)
p3

此方法僅將線穿過最后一個 plot (p2)。 在此處輸入圖像描述

嘗試將注釋與每個 plot 一起放置。

# Annotation with each plot
p1 <- ggplot(mtcars, aes(x=disp,y=mpg))+
  geom_point()+
  annotate("segment",x=-Inf,xend=Inf,y=15,yend=15)
p2 <- ggplot(mtcars, aes(x=hp,y=mpg))+
  geom_point()+
  annotate("segment",x=-Inf,xend=Inf,y=15,yend=15)

p1+p2

此方法將線放在每個 plot 但不在之間。 在此處輸入圖像描述

我想要這樣的東西: 在此處輸入圖像描述

您可以使用grid.draw繪制線,它將線繪制在繪圖 window 中的任何其他內容上:

library(grid)
p3
grid.draw(linesGrob(x = unit(c(0.06, 0.98), "npc"), y = unit(c(0.277, 0.277), "npc")))

在此處輸入圖像描述

但是,這里有一些警告。 線條的確切位置由您決定,雖然如果您經常要這樣做,可以通過編程方式進行定位,但一次性調整 x 和 y 值以獲得線條會更快你想要它的地方,就像我在一分鍾內所做的那樣。

第二個需要注意的是,這條線位於 npc 空間中,而 ggplot 使用了固定間距和靈活間距的組合。 這樣做的結果是,只要調整 plot 的大小,該線就會相對於 plot 移動。 同樣,這可以通過編程方式修復。 如果你真的想打開那罐蠕蟲,你可以在我對這個問題的回答中看到一個類似的解決方案

我喜歡@Allan 的回答,但這是使用facet_wrap的另一種方法。

首先,我們需要將 pivot 數據更長,以便使用facet_wrap的形式。 然后黑客開始。 首先,我們需要使用strip.position = 'bottom'將刻面帶標簽移動到下方。 然后我們可以使用coord_cartesian(clip = 'off')關閉裁剪,以便在圖形區域之外繪制線條。 接下來我們修復xlim ,這樣當您嘗試 plot 圖形區域外的線段時,圖形繪制區域不會改變。

最后,大黑客,你 plot 一個帶有新數據的geom_segment所以它只在一個方面繪圖。 您在調用geom_segment中創建了一個新的data.frame ,其中的數據使其在最后一個要渲染的面板中為 plot,因此該行位於頂部。

最后,僅對theme()進行了一些更改,因此條形背景為空白,並且位置位於軸刻度之外。

library(ggplot2)
library(dplyr)
library(tidyr)
ggplot(pivot_longer(mtcars, -mpg) %>% filter(name %in% c("disp", "hp")),
       aes(x=value, y=mpg, group=name)) +
  geom_point() + 
  facet_wrap(.~name, strip.position = "bottom") + 
  geom_segment(data = data.frame(mpg = 15, name = "hp"),
               x=-650, xend=525, y=15, yend=15) +
  coord_cartesian(clip = 'off', xlim = c(0,500)) +
  theme(aspect.ratio = 1,
        strip.background = element_blank(),
        strip.placement = "outside") +
  labs(x = "") 

在此處輸入圖像描述

暫無
暫無

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

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