Export to pdf not displaying properly in ggplot2

别等时光非礼了梦想. 提交于 2019-12-23 23:26:17

问题


I have a complex figure P made up of figures Fig_NPK and Barchart_fert, they were made using a datasheet "Fert" with columns including "Vil", "N", "P", and "K". My goal is to create a pdf file and use ghostscript to embed the "Times New Roman" font family in the pdf file. When I use ggsave to export "P" to a pdf file it doesn't display properly. The code used were:

library(extrafont)
library(ggplot2)

Figures, Fig_N as an example (Fig_N, P, and K form Fig_NPK)

Fig_N<-ggplot(aes(y = N, x = factor(Vil)), data = Total_fac[which(Total_fac$N<quantile(Total_fac$N,0.95)&Total_fac$N>quantile(Total_fac$N,0.05)),])+stat_boxplot(geom ="errorbar") + geom_boxplot() +ggtitle("N requirement")+labs(x="Village",y="Amount used (kg)") +theme(text=element_text(family="Times New Roman", face="plain", size=14))
Fig_NPK<-plot_grid(Fig_N,Fig_P,Fig_K, nrow=3,align = "v")
Barchart_fert<-ggplot(Fert, aes(x=Village, y=Amount, fill=Fertilizer)) + geom_bar(stat = "identity", width=0.4)+ggtitle("Fertilizer usage")+ylab("Amount used (kg)")+theme(axis.text.x=element_text(vjust = 0.5))+scale_fill_discrete(name="Fertilizer type", breaks=c("N-Eq.", "P2O5-Eq.", "K2O-Eq."),labels=c("N Eq.", expression('P'[2]*'O'[5]~~Eq.), expression('K'[2]*'O'~~Eq.)), c=60, l=80)+theme(text=element_text(family="Times New Roman", face="plain", size=14))
P<-ggdraw() + draw_plot(Fig_NPK,0,0,.4,1)+draw_plot(Barchart_fert,.4,0,.6,1) + draw_plot_label(c("A", "B"), c(0,.4), c(1,1), size=14)
ggsave("FigP.pdf", plot=P, width=5, height=5)

Error message after ggsave:

Error in grid.Call.graphics(L_text, as.graphicsAnnot(x$label), x$x, x$y,  : Metric information not available for this family/device In addition: There were 50 or more warnings (use warnings() to see the first 50)

The resulting pdf file is incomplete. The same thing happens when I try exporting "P" to a postscript file. I have been following the help file and other answers on embedding fonts but can't seem to solve my issue.


回答1:


Found a solution in this answer. Adding

device=cairo_pdf

in ggsave does solve the problem of not display the correct font in pdf and tiff files, though as @user1092247 pointed out, the kerning seems awkward. Would still appreciate it if anyone could perfect this solution, and explain a bit more on what the problem actually was.




回答2:


Indirect way- Save the image as png in R-studio. Covert png to pdf using other software (such as inkspace - change settings in Document properties).



来源:https://stackoverflow.com/questions/40826684/export-to-pdf-not-displaying-properly-in-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!