R ggplot2:如何避免在PDF中切断标题和轴标签?
问题描述:
我有一些困难让我的情节的PDF版本显示标题和轴标签。它们在RStudio绘图窗口中显示正常,但在PDF中被截断。我已经尝试了一些东西,包括不同的边距设置,使用dev.off()的pdf()函数,但不管我尝试什么,都会得到相同的结果。任何想法,我要去错了吗?R ggplot2:如何避免在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")
感谢
答
前一段时间我回答了similar question。我在这里提供了答案。
首先,您必须使用命令windowsFonts()
(在RStudio中执行此命令)确定可用字体。我的图形设备中的当前字体是;
> windowsFonts()
$serif
[1] "TT Times New Roman"
$sans
[1] "TT Arial"
$mono
[1] "TT Courier New"
此后,您可以导入extrafont库和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格式,将字符渲染为另一个字符。这也是一个open issue为ggsave和2013年以来
我一直做的是使用Rstudio的情节,观众窗格中尚未解决。在那里你可以用窗口管理你的情节的大小,然后导出 - >另存为pdf。保存的图的大小将与查看器窗格的大小相同。 –
害怕没有解决问题。如果通过图表查看器窗口上的“导出”按钮导出,则会发生同样的情况:当标题和标签在查看器窗口中正确显示时,它们不会显示在PDF中。 – hawkaterrier