2013-05-02 93 views
1

我想將子文本(一個textGrob)添加到gridViewport - 這可能嗎?將子文本添加到視口

我想通了如何子文本添加到一個圖表:

require(ggplot2) 
require(gridExtra) 

# make the data 
timeSeries <- data.frame(date = seq(as.Date("2001-01-01"), as.Date("2012-01-01"), by = "mon"), 
        value = 1:133 + rnorm(133, 0, 10) 
        ) 


# make the ggplots 
gpLine <- ggplot(timeSeries, aes(x = date, y = value)) + 
       geom_line() 

gpBar <- ggplot(timeSeries, aes(x = date, y = value)) + 
       geom_bar(stat = 'identity') 

# ggplot + subtext 
grid.arrange(gpBar, sub = textGrob("why is this at the bottom?")) 

,我還可以使用gridViewport

# two plots, one view 
vplayout <- function(x,y) viewport(layout.pos.row = x, layout.pos.col = y) 

pushViewport(viewport(layout = grid.layout(3,1))) 
print(gpLine, vp = vplayout(1:2, 1)) 
print(gpBar, vp = vplayout(3, 1)) 

兩個圖表粘在一起......但我不知道如何將文本添加到生成的視口的底部。

Grid如此完整的,我敢肯定有必須一種方式,但它是隱藏在我身上。

回答

3

您是非常接近:

popViewport() # brings you to the top viewport for the whole plotting area 
grid.text("Hello Vicar", x = unit(0.5, "npc"), y = unit(0.25, "npc")) 

所有上述命令後。

+0

+1,感謝 - 現在的文字是中期的情節。我可能會完全愚蠢,但是我怎樣才能把它放到底部,因爲'grid.arrange'是用'sub'調用的呢? – ricardo 2013-05-02 11:12:57

+1

只需調整x和y值。在整個繪圖區域中x = y = 0.5是死點。 – 2013-05-02 11:21:31

+1

upViewport一般是優於彈出 – baptiste 2013-05-02 11:51:07

3

也許我失去了一些東西,因爲我只想做到以下幾點,

grid.arrange(gpLine, gpBar, heights = c(2/3, 1/3), 
    bottom = textGrob("this is my signature", x=1, hjust=1, vjust=0)) 

enter image description here

編輯(23/07/2015):從V> = 2.0.0 gridExtra的參數已從sub改爲bottom以保持一致性

+0

+1,謝謝。感謝也很好地解決了這個問題。 – ricardo 2013-05-06 07:31:16

+0

感謝您對'sub'被修改爲'bottom'的編輯。試圖按照推薦'sub'的其他解決方案來敲打我的頭。 – ecoe 2015-12-17 19:21:16

0

在當前版本的ggplot2中,使用gridExtra::grid.arrange不是必需的:

p <- ggplot(...) + labs(caption = 'text at the bottom') 

的伎倆。