首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >R ggplot2:如何避免在PDF中切断标题和轴标签?

R ggplot2:如何避免在PDF中切断标题和轴标签?
EN

Stack Overflow用户
提问于 2017-10-15 12:30:11
回答 1查看 8K关注 0票数 4

我有一些困难,获得PDF版本的我的情节,以显示标题和轴标签。它们在RStudio绘图窗口中显示得很好,但在PDF中却被切断。我尝试了一些东西,包括不同的页边距设置、pdf()函数和dev.off(),但是不管我尝试什么,都会得到相同的结果。知道我哪里出问题了吗?

代码语言:javascript
复制
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")

谢谢

EN

回答 1

Stack Overflow用户

发布于 2017-10-15 14:07:40

不久前我回答了一个相似问题。我在这里给出了答案。

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

代码语言:javascript
复制
> windowsFonts()
$serif
[1] "TT Times New Roman"

$sans
[1] "TT Arial"

$mono
[1] "TT Courier New"

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

其次,给出了一个最小可重现性的例子;

代码语言:javascript
复制
 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()。看这个所以贴。使用任何其他字体保存为pdf,呈现的数字与字符之上的另一个。这也是一个用于ggsave的公开发行,自2013年以来一直没有得到解决。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46755052

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档