2012-08-23 24 views
7

我正在使用ggplot繪製一些數據圖表,並注意到圖例文本非常長,並且不適合窗口。將圖例文本包裝爲適合繪圖窗口

+ opts(legend.position = 'bottom', legend.direction = 'horizontal', size=0.1) + 
    guides(colour = guide_legend(nrow = 3), size=1) 

ggplot中是否有一個選項來包裝圖例文本以適應窗口。

+2

好問題:a * reproducible *例子可能會加快答案... –

+2

很難發佈沒有數據的答案。但是AFAIK在'ggplot2'中沒有選項,但是你可以寫一個函數在一定長度之後插入'\ n'。 –

回答

7

據我所知,我不得不使用strwidth()來計算基本圖形中文本寬度的解決方法。

title <- "This is a really excessively wide title for a plot, especially since it probably won't fit" 

使用par("din") to get the width of the device, and strwidth()`來計算文字大小:

par("din")[1] 
[1] 8.819444 
strwidth(title, units="inches") 
[1] 11.47222 

使用它的功能和情節:

wrapTitle <- function(x, width=par("din")[1]){ 
    xx <- strwrap(x, width=0.8 * nchar(x) * width/strwidth(x, units="inches")) 
    paste(xx, collapse="\n") 
} 

wrapTitle(title) 
[1] "This is a really excessively wide title for a plot, especially since it\nprobably won't fit, meaning we somehow have to wrap it" 

情節:

ggplot(mtcars, aes(wt, mpg)) + geom_point() + opts(title=wrapTitle(title)) 

enter image description here


如果要將繪圖保存到文件,則可以用實際保存的繪圖尺寸替換par("din")

+0

我喜歡你的意見,但據我所知,OP想包裝傳說文本而不是標題或傳奇標題。有沒有辦法知道傳說文字所在的grob的尺寸? –

+0

@Iselzer艾哈,我沒有引起足夠的重視...... – Andrie