Reputation: 388
I'm having some difficulty getting the PDF version of my plot to show the title and axis labels. They show up fine in the RStudio plot window, but get cut off in the PDF. I've tried a few things, including different margin settings, the pdf() function with dev.off() but keep getting the same result no matter what I try. Any ideas where I'm going wrong?
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")
Thanks
Upvotes: 5
Views: 9481
Reputation: 2012
I answered a similar question some time ago. I provide that answer here.
First, you have to determine the available fonts with the command windowsFonts()
(execute this command in RStudio). The current fonts in my graphing device are;
> windowsFonts()
$serif
[1] "TT Times New Roman"
$sans
[1] "TT Arial"
$mono
[1] "TT Courier New"
Thereafter, you can import the extrafont library and the loadfonts(device = "win")
. I also recommend to execute these commands in the R console and not in RStudio. I suggest this because when you are importing the fonts using font_import() in RStudio, it may not show the y/n
prompt.
Next, I provide a minimum reproducible example;
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")
Its only the ArialMT
font that seems to work with ggsave(). See this SO post. Using any other font for saving to pdf, renders the figure with characters on top of another. This is also an open issue for ggsave and has not been solved since 2013.
Upvotes: 0