简体   繁体   English

R:导出为 PDF 时,图例文本超出绘图范围

[英]R: text of legend falls outside of plot when exporting to PDF

When I add a legend to my R plot (using the legend() function), then it works in Rstudio, but when I export the plot as a PDF with a different size, then sometimes the text inside the legend is larger than the legend box itself.当我向 R 图中添加图例时(使用legend()函数),它在 Rstudio 中工作,但是当我将图导出为具有不同大小的 PDF 时,有时图例中的文本大于图例盒子本身。

图片

What is going on here and how do I fix it?这里发生了什么,我该如何解决?

If I export the image with a larger width, then the legend box becomes larger too and manages to contain its text, but this is silly: I want the legend box and its text to automatically adjust to whatever width I choose, no matter how small it is.如果我以更大的宽度导出图像,那么图例框也会变大并设法包含其文本,但这很愚蠢:我希望图例框及其文本自动调整为我选择的任何宽度,无论有多小这是。

And please don't recommend ggplot2 .并且请不要推荐ggplot2

As @Gregor said - you should use pdf() .正如@Gregor 所说 - 你应该使用pdf() I am merely adding his suggestion as an answer.我只是添加他的建议作为答案。 Your code would be something like this:您的代码将是这样的:

pdf("picture.pdf", width=6, height=6)
plot(...)
legend(...)
dev.off()

Where pdf() opens a new device for plotting (of course you have to set file name as well as dimensions according to your needs), and dev.off() closes the device writing everything to a file. pdf()打开一个用于绘图的新设备(当然,您必须根据需要设置文件名和尺寸),而dev.off()关闭设备将所有内容写入文件。

I am not sure what causes the issue with legend in R-studio.我不确定是什么导致了 R-studio 中的图例问题。 But on my machine I noticed that legends sometimes have issues with updating after resizing the device.但是在我的机器上,我注意到图例在调整设备大小后有时会出现更新问题。 Probably this is something related.这大概是有关系的。

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

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