2012-04-02 138 views
8

舉一個非常簡單的例子,mfrow=c(1,3);每個圖都是不同的直方圖;我怎麼會畫一條水平線(類似於abline(h=10))那全是 3個數字? (即便是它們之間的差距)。顯然,我可以爲每個數字添加一個abline,但這不是我想要的。我可以想到一個非常複雜的方式,通過真的只有1個數字,並使用polygon等繪製其中的每個'圖',這將是荒謬的。有沒有一種簡單的方法來做到這一點?如何在R中的多圖環境中繪製一條線?

回答

13

由於@joran指出的那樣,電網圖形化系統提供了更靈活控制單個設備上多個圖的排列。

在這裏,我首先使用grconvertY()查詢的50上的y軸的高度的位置中的「歸一化設備座標」單位。 (即作爲繪圖裝置總高度的一部分,其中0 =底部,1 =頂部)。然後我使用grid函數來:(1)推動填充設備的viewport;和(2)在由grconvertY()返回的高度繪製一條線。

## Create three example plots 
par(mfrow=c(1,3)) 
barplot(VADeaths, border = "dark blue") 
barplot(VADeaths, border = "yellow") 
barplot(VADeaths, border = "green") 

## From third plot, get the "normalized device coordinates" of 
## a point at a height of 50 on the y-axis. 
(Y <- grconvertY(50, "user", "ndc")) 
# [1] 0.314248 

## Add the horizontal line using grid 
library(grid) 
pushViewport(viewport()) 
grid.lines(x = c(0,1), y = Y, gp = gpar(col = "red")) 
popViewport() 

enter image description here

編輯:@joran問到如何繪製,從第1情節在第三情節的最後一棒的邊緣的y軸延伸的線。這裏有幾個選擇:

library(grid) 
library(gridBase) 
par(mfrow=c(1,3)) 

# barplot #1 
barplot(VADeaths, border = "dark blue") 
X1 <- grconvertX(0, "user", "ndc") 
# barplot #2 
barplot(VADeaths, border = "yellow") 
# barplot #3 
m <- barplot(VADeaths, border = "green") 
X2 <- grconvertX(tail(m, 1) + 0.5, "user", "ndc") # default width of bars = 1 
Y <- grconvertY(50, "user", "ndc") 

## Horizontal line 
pushViewport(viewport()) 
grid.lines(x = c(X1, X2), y = Y, gp = gpar(col = "red")) 
popViewport() 

enter image description here

最後,這裏是一個幾乎相當於,一般多用的方法。它採用了功能grid.move.to()grid.line.to()由保羅·馬雷爾在@ mdsumner的答案鏈接到文章中demo'd:

library(grid) 
library(gridBase) 
par(mfrow=c(1,3)) 

barplot(VADeaths); vps1 <- do.call(vpStack, baseViewports()) 
barplot(VADeaths) 
barplot(VADeaths); vps3 <- do.call(vpStack, baseViewports()) 

pushViewport(vps1) 
Y <- convertY(unit(50,"native"), "npc") 
popViewport(3) 

grid.move.to(x = unit(0, "npc"), y = Y, vp = vps1) 
grid.line.to(x = unit(1, "npc"), y = Y, vp = vps3, 
      gp = gpar(col = "red")) 
+0

+1不錯!你知道一種按摩單位/座標/剪裁的方法,這條線從最左邊的y軸延伸到綠色條的右邊緣嗎? – joran 2012-04-03 01:55:49

+0

我確實有一個想法,如果能解決問題,我會添加它。現在,我在太陽下山前剪草坪... – 2012-04-03 02:03:08

+0

謝謝,這真的很有幫助!我很欣賞你願意推遲我的帳戶上的割草;-) – gung 2012-04-03 02:38:27

6

這是不困難想着它,我能做的最好的:

par(mfrow = c(1,3),xpd = NA) 

for (i in 1:3){ 
    x <- rnorm(200,i) 
    hist(x) 
    if (i == 1) segments(par("usr")[1],10,30,10) 
} 

enter image description here

我不知道如何確保行結束在正確的位置,而不修修補補。繪製每個區域的細分將解決這個問題,但會引入高度正確排列的問題。但這至少是一個很好的起點。

我想這在grid圖形更容易,但我不得不做一些研究來驗證。

+0

感謝您的幫助。 – gung 2012-04-03 02:39:24

4

本文由保羅的Murrell示出了使用的grid圖形到兩個不同的座標系之間畫線,在具有兩個分離的子圖的天然空間中指定的端點這種情況下的行:

保羅的Murrell 。網格圖形包。 [R新聞,2(2):14-19,2002年6月

它的PDF文章的第17頁:

http://cran.r-project.org/doc/Rnews/Rnews_2002-2.pdf

+0

謝謝,我正在閱讀文章。 – gung 2012-04-03 02:39:02

+0

是的,感謝那個偉大的鏈接。我剛剛在我的答案中添加了第三個代碼塊,它使用了Murrell文章中演示的幾個函數('grid.move.to()'和'grid.line.to()')。 – 2012-04-03 05:00:26