简体   繁体   English

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

[英]wrapping legend text to fit the plot window

I am using ggplot to chart some data and I noticed that legends text are very long and not fitting the window.我正在使用 ggplot 绘制一些数据图表,我注意到图例文本很长并且不适合窗口。

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

Is there an option in ggplot to wrap the legend text to fit the window. ggplot 中是否有选项可以包装图例文本以适合窗口。

Not as far as I know, so I have resorted to a workaround using strwidth() , which calculates the width of text in base graphics.据我所知,所以我求助于使用strwidth()的解决方法,它计算基本图形中文本的宽度。

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

Use par("din") to get the width of the device, and strwidth() to calculate the text size:使用par("din")获取设备的宽度,并使用strwidth()计算文本大小:

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

Use it in a function and plot:在函数和绘图中使用它:

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"

The plot:剧情:

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

在此处输入图片说明


If you want to save the plot to file, then you can replace par("din") with the actual saved plot dimensions.如果要将绘图保存到文件,则可以将par("din")替换为实际保存的绘图尺寸。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM