[英]wrapping legend text to fit the plot window
我正在使用 ggplot 繪制一些數據圖表,我注意到圖例文本很長並且不適合窗口。
+ opts(legend.position = 'bottom', legend.direction = 'horizontal', size=0.1) +
guides(colour = guide_legend(nrow = 3), size=1)
ggplot 中是否有選項可以包裝圖例文本以適合窗口。
據我所知,所以我求助於使用strwidth()
的解決方法,它計算基本圖形中文本的寬度。
title <- "This is a really excessively wide title for a plot, especially since it probably won't fit"
使用par("din")
獲取設備的寬度,並使用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))
如果要將繪圖保存到文件,則可以將par("din")
替換為實際保存的繪圖尺寸。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.