我很难获得我的情节的PDF版本来显示标题和轴标签。它们在RStudio绘图窗口中显示正常,但在PDF中被截断。我尝试过一些东西,包括不同的边距设置,pdf()函数和dev.off(),但无论我尝试什么,都会得到相同的结果。我出错的任何想法?
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")
由于
答案 0 :(得分:0)
前一段时间我回答了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,使用另一个字符顶部呈现图形。这也是ggsave的open issue,自2013年以来一直没有得到解决。