【问题标题】:R ggplot2: How do I avoid title and axis labels being cut off in PDF?R ggplot2:如何避免 PDF 中的标题和轴标签被截断?
【发布时间】:2018-03-27 01:46:13
【问题描述】:

我在获取我的绘图的 PDF 版本以显示标题和轴标签时遇到了一些困难。它们在 RStudio 绘图窗口中显示良好,但在 PDF 中被截断。我尝试了一些东西,包括不同的边距设置、带有 dev.off() 的 pdf() 函数,但无论我尝试什么,都会得到相同的结果。有什么想法我哪里出错了吗?

library(ggplot2)

#Plot
par(mar=c(6, 6, 6, 2))
ggplot(data = paymentsNY, aes(x = Average.Covered.Charges/1000, y = 
Average.Total.Payments/1000, alpha = 0.25))+ 
geom_point()+
xlab("Mean covered charges ($'000s)")+
ylab("Mean total payments ($'000s)")+
ggtitle("Mean covered charges and mean total payments - NY")+
theme(title = element_text((size = 16)))+
theme(legend.position = "none")+
geom_smooth(method = "lm")

#Write plot as PDF
ggsave("payments_NY.pdf")

谢谢

【问题讨论】:

  • 我总是使用 Rstudio 中的绘图查看器窗格。在那里,您可以使用窗口管理绘图的大小,然后导出 -> 另存为 pdf。保存的绘图的大小将与查看器窗格的大小相同。
  • 怕这解决不了问题。如果我通过绘图查看器窗口上的“导出”按钮导出,会发生同样的事情:虽然标题和标签正确显示在查看器窗口中,但它们不会出现在 PDF 中。

标签: r pdf ggplot2


【解决方案1】:

我前段时间回复了similar question。我在这里提供这个答案。

首先,您必须使用命令windowsFonts() 确定可用的字体(在 RStudio 中执行此命令)。我的绘图设备中的当前字体是;

> windowsFonts()
$serif
[1] "TT Times New Roman"

$sans
[1] "TT Arial"

$mono
[1] "TT Courier New"

之后,您可以导入额外字体库和loadfonts(device = "win")。我还建议在 R 控制台而不是在 RStudio 中执行这些命令。我建议这样做是因为当您在 RStudio 中使用 font_import() 导入字体时,它可能不会显示 y/n 提示符。

接下来,我提供一个最小可重现的例子;

 library(ggplot2)
 library(extrafont)
 # tell where ghostscript is located. This is required for saving the font in pdf
 Sys.setenv(R_GSCMD = "C:\\Program Files\\gs\\gs9.21\\bin\\gswin64c.exe") # I have installed 64-bit version of GhostScript. This is why I've used gswin64c.exe. If you have installed 32-bit version of GhostScript, use gswin32c.exe. Failure to specify the correct installed GhostScript will yield error message, "GhostScript not found"
 # create a plot object
p <- ggplot(mtcars, aes(x=wt, y=mpg)) + 
geom_point()+
ggtitle("Fuel Efficiency of 32 Cars")+
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
theme_bw()+
theme(text=element_text(family="ArialMT", size=14))
# show the plot
print(p)

# save the plot as pdf  
ggsave("figures//ggplot_arialmt.pdf", p, width=20, height=20, 
   device = "pdf", units = "cm")

似乎只有ArialMT 字体可以与ggsave() 一起使用。请参阅此SO post。使用任何其他字体保存为 pdf,将图形呈现在另一个字符之上。这也是 ggsave 的open issue,自 2013 年以来一直没有解决。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 2011-10-10
    • 2017-04-13
    • 2020-04-19
    • 1970-01-01
    相关资源
    最近更新 更多