I'm making a chart in ggplot2 and ggsave()
does not do what I expect.
require(ggplot2)
require(showtext)
showtext_auto()
hedFont <- "Pragati Narrow"
font_add_google(
name = hedFont,
family = hedFont,
regular.wt = 400,
bold.wt = 700
)
chart <- ggplot(
data = cars,
aes(
x = speed,
y = dist
)
) +
geom_point() +
labs(
title = "Here is a title",
subtitle = "Subtitle here"
) +
theme(
plot.title = element_text(
size = 20,
family = hedFont,
face = "bold"
),
axis.title = element_text(
face = "bold"
)
)
ggsave(
filename = "myplot",
plot = chart,
device = "png",
path = "~/Desktop",
width = 300,
height = 200,
units = "mm",
dpi = 72
)
What I expected was for the chart's title to have the custom font. Instead, ggsave()
makes a chart where all the text has the font. I expected the axis titles to be bold, but they are not.
Here's what I see in RStudio viewer when I run the ggplot()
code in it.
Here's what ggsave()
produces.
I want ggsave()
to make a chart where only the chart's title has the font and the axes' titles are bold.
UPDATE: I tried Tung's suggestion. I downloaded the Google Font onto my computer. Here's my new code.
font_import(
paths = "/usr/share/fonts/truetype/google-fonts/",
recursive = T,
prompt = F,
pattern = "Pragati"
)
loadfonts(device = "pdf")
loadfonts(device = "postscript")
myFont <- "Pragati Narrow"
chart <- ggplot(
data = cars,
aes(
x = speed,
y = dist
)
) +
geom_point() +
labs(
title = "Here is a title",
subtitle = "Subtitle here"
) +
theme(
plot.title = element_text(
size = 20,
family = myFont,
face = "bold"
),
axis.title = element_text(
face = "bold"
)
)
ggsave(
filename = "myplot2.png",
plot = chart,
device = "png",
path = "~/Desktop",
width = 300,
height = 200,
units = "mm",
dpi = 72
)
Doesn't seem to have changed anything.
I don't see any errors or warnings in the RStudio console either.
This worked on my Linux Mint Rosa machine. You need to download and import the desired font to extrafont
database per this answer
library(extrafont)
library(ggplot2)
hedFont <- "BitstreamVeraSansMono"
chart <- ggplot(
data = cars,
aes(
x = speed,
y = dist
)
) +
geom_point() +
labs(
title = "Here is a title",
subtitle = "Subtitle here"
) +
theme(
plot.title = element_text(
size = 20,
family = hedFont,
face = "bold"
),
axis.title = element_text(
face = "bold"
)
)
chart
ggsave(
filename = "./output/myplot.png",
plot = chart,
type = "cairo",
height = 4,
width = 6,
dpi = 150)