2012-09-17 47 views
12

如何使用一個基於因子的軸和一個數字軸增加圖表的灰色繪圖區域,以便geom_text()繪圖中的文本標籤在視圖中並且不會擴展在劇情區外面?在ggplot中增加繪圖區域以應對繪圖邊緣處的geom_text

ggplot showing geom_text() plot where labels extend outside the plot area

我特別想延長的灰色區域提供繪圖區,允許文本標籤出現在全內的邊緣區域。

或者還有更好的方法嗎?

+10

您可以嘗試將'expand'參數設置爲'scale_x_discrete'和/或'scale_y_continuous'。它需要一個長度爲2的數字向量,第一個是擴展因子,第二個是擴展擴展。嘗試不同的值,看看有什麼效果。 –

+0

我希望研究員的wordcloud與ggplot2兼容,因爲他的更新版本專門處理這個問題:http://blog.fellstat.com/?p=248 –

+0

@BrianDiggs感謝您的提示。 'expand'似乎可以訣竅,但我認爲需要對樣式進行一些調整,因此我試圖使用'theme_bw()'來開始...... – psychemedia

回答

1

您可以使用ggplot_gtable更改每個ggplot的佈局選項,然後使用grid.arrange顯示所有圖。

library(ggplot2) 
library(gridExtra) 
## create a dummy ggplot 
(g1 <- ggplot(mtcars, aes(wt, mpg)) + 
     geom_text(aes(label=rownames(mtcars)), size=6, angle=45) + 
     theme(plot.margin = unit(rep(1, 4), "cm"))) 

顯然,文本標籤不繪圖區外部延伸。但是,下面的代碼允許這一點:

gg_table <- ggplot_gtable(ggplot_build(g1)) 
gg_table$layout$clip[gg_table$layout$name=="panel"] <- "off" 
grid.draw(gg_table) 

創建每個面板gg_table,然後使用grid.arrange顯示所有:

grid.arrange(gg_table, gg_table, gg_table, gg_table, ncol=2) 

enter image description here

我知道這是勞動密集型的,但你可以編寫一個函數來創建多個ggplots和gg_tables來節省時間。