简体   繁体   中英

Changing Plot Font with Cairo in R

I have found R's default plots to be poorly aliased. As a solution, I set Cairo as the graphics device, and now the plots look much better.

Unfortunately, using Cairo has created another issue, which is that for some reason, I am not able to apply the font that I was using when the graph was displayed in the plot window (in the left-hand diagram above, Cambria is used, but the right-hand diagram fails to apply this font).

Here is my code:

library(readxl)
library(scales)
library(ggplot2)
library(dplyr)
library('Cairo')

windowsFonts(Cam = windowsFont("Cambria"))

dataset <- read_excel('CW Data.xlsx')
colnames(dataset)[4] <- "Broadband Subs (%)"

options(scipen = 1000)

# Scatter plot FDI~GDP with regression line
CairoWin()
ggplot(dataset, aes(x=`2019 GDP ($bn)`, y=`2019 FDI ($m)`)) + 
  geom_point(size=3, shape=1) +
  geom_smooth(method='lm',formula=y~x, se=FALSE, color='black') +
  scale_x_continuous(label = comma) + scale_y_continuous(label=comma) +
  theme(panel.background = element_rect(fill="peachpuff"), 
        plot.background = element_rect(fill="peachpuff")) +
  theme(panel.grid.major = element_line(colour = "gray72"), 
        panel.grid.minor = element_line(colour = "gray72")) + 
  theme(text = element_text(family = "Cam")) 

ggsave("FDI~GDP.png", device="png", type = "cairo") 

And here is a OneDrive link for the Excel data that I am using

https://1drv.ms/x/s!AvGKDeEV3LOs4gNr714Ie0KbOjhO?e=bkdPvk

Please don't consider this an answer to the question, but rather a motivating example for the bounty.

I found that the PDF device gives absolutely atrocious results using custom fonts. With regards to the bounty, here is a more minimal reprex.

library(ggplot2)

p <- ggplot(iris, aes(Sepal.Width, Sepal.Length, colour = Species)) +
  geom_point() +
  theme(text = element_text(family = "mono"))

ggsave("font_test.pdf", p, device = cairo_pdf)
#> Saving 7 x 5 in image

Created on 2022-02-04 by the reprex package (v2.0.1)

A screenshot of the PDF output:

在此处输入图像描述

I needn't explain to the keen typographer that the displayed mono font is not 'Courier New' or system default monospaced font. Moreover, the left axis title is mangled and the legend title is out of whack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM