包装图例文本以适合绘图窗口

时间:2012-08-23 14:27:01

标签: r ggplot2

我正在使用ggplot来绘制一些数据,我注意到传说文本很长而且不适合窗口。

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

ggplot中是否有一个选项可以包含图例文本以适合窗口。

1 个答案:

答案 0 :(得分: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")替换为实际保存的绘图尺寸。