Font Family Won't Change in Ggplot

Changing fonts in ggplot2

You just missed an initialization step I think.

You can see what fonts you have available with the command windowsFonts(). For example mine looks like this when I started looking at this:

> windowsFonts()
$serif
[1] "TT Times New Roman"

$sans
[1] "TT Arial"

$mono
[1] "TT Courier New"

After intalling the package extraFont and running font_import like this (it took like 5 minutes):

library(extrafont)
font_import()
loadfonts(device = "win")

I had many more available - arguable too many, certainly too many to list here.

Then I tried your code:

library(ggplot2)
library(extrafont)
loadfonts(device = "win")

a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
theme(text=element_text(size=16, family="Comic Sans MS"))
print(a)

yielding this:

Sample Image

Update:

You can find the name of a font you need for the family parameter of element_text with the following code snippet:

> names(wf[wf=="TT Times New Roman"])
[1] "serif"

And then:

library(ggplot2)
library(extrafont)
loadfonts(device = "win")

a <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
theme(text=element_text(size=16, family="serif"))
print(a)

yields:
Sample Image

Can't change fonts in ggplot/geom_text

I would try"

windowsFonts(Times=windowsFont("TT Times New Roman"))

In doing this your specifying explicitly the Windows Font mapping.

Is there a way to change font family in geom_net?

This is gnarly b/c the pkg author used either gpar() or hard-coded bits internally with the label grob (https://github.com/sctyner/geomnet/blob/master/R/geom-net.r) and didn't have any way to set the family (technically fontfamily). That means the "family" (yay, inconsistency b/c this is how you specify it in a bit) is picked up from the defaults for the graphics device.

Both:

cairo_pdf("test.pdf", family="Roboto Condensed")
ggplot(data = net, aes(from_id = from, to_id = to)) +
geom_net(aes(linewidth = weight), layout.alg = "kamadakawai",
labelon = TRUE, ecolour = "grey60", labelgeom="text",
directed = FALSE, fontsize = 10, ealpha = 0.5,
repel = TRUE)
dev.off()

(I have Roboto Condensed loaded b/c of hrbrthemes but I include it there to show it picks up extra installed fonts.)

and:

cairo_pdf("test.pdf", family="Times")
ggplot(data = net, aes(from_id = from, to_id = to)) +
geom_net(aes(linewidth = weight), layout.alg = "kamadakawai",
labelon = TRUE, ecolour = "grey60", labelgeom="text",
directed = FALSE, fontsize = 10, ealpha = 0.5,
repel = TRUE)
dev.off()

both ended up with the correct font for the labels. I didn't try other font-oriented theme changes, but it def worked for the labels (though you can see the font change impacted the axis text, but I didn't explicitly set it either so give that a try as well):

Sample Image

Sample Image

Any real, useful fix is going to require a PR for the package which I'd love to hack on tonight but won't be able to get to for a while (though there are scads of other folks who are more capable than I am to make the PR). At the very least you should file an issue referencing this.

RMarkdown won't knit ggplot2 plot after changing font

Usually quite easy to solve. The problem should be, that the font is not installed in your computer.

You have to download the .otf file for the font e.g. (https://fonts2u.com/lmroman10-regular.font) and install it on your Operating System.

If you don't know how to do this, just google it (e.g. "install extra font Windows"), there are plenty of tutorials on it online.

-edit-
I was a little to quick - didn't realize the problem just comes from running it in rmarkdown. Try the following:

```{r, fig.showtext=TRUE, echo=FALSE}
library("tidyverse")
library("showtext")

x <- rexp(100)

font_add("LM Roman 10", regular = "lmroman10-regular.otf")

data.frame(info = x) %>%
ggplot() +
geom_histogram(aes(x = info), col = "red", fill = "red", alpha = 0.5) +
theme_minimal() +
theme(text = element_text(family="LM Roman 10"))

```

It's important that you add fig.showtext=TRUE, library("showtext") and font_add("LM Roman 10", regular = "lmroman10-regular.otf").

I just placed the .otf in my project folder - but I think you can also give it another path.

ggsave() does not bolden text, and it changes font of all text instead of just plot title

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)

Sample Image

How to change font size for all text in a ggplot object relative to current value?

ggplot objects are displayed through grid graphics, and grid graphics inherit the parent viewport's cex setting as a multiplier,

print(p, vp=grid::viewport(gp=grid::gpar(cex=2)))

or (to only affect the theme elements, but won't affect e.g. geom_text layers),

p + theme(text=element_text(size=24))

Changing font family of geom_text located inside a package

Re comment, you can edit the grobs to change the fontfamily in the geom_text calls.

Code is wrapped in a function as you are wanting to replicate the graphs.

library(likert)

# example
data(pisaitems)
items28 <- pisaitems[, substr(names(pisaitems), 1, 5) == "ST24Q"]
l28 <- likert(items28)

# helper function - takes likert plot as input
# loops through the geom_text calls editing the font family
grid_fam <- function(p, fam="Georgia")
{
g <- ggplotGrob(p)
px <- which(g$layout$name=="panel")
id <- grep("text", names(g$grobs[[px]]$children))
for(i in id) g$grobs[[px]]$children[[i]]$gp$fontfamily <- fam
grid::grid.newpage()
grid::grid.draw(g)
invisible(g)
}

Plots

# original
plot(l28, plot.percents=TRUE, plot.percent.low = FALSE,
plot.percent.high = FALSE)
# with changed font
grid_fam(plot(l28, plot.percents=TRUE, plot.percent.low = FALSE,
plot.percent.high = FALSE))

There is most likely a simpler way to do this.


EDIT Update from comments: please feel free to improve

# initial plot
p <- plot(l28, plot.percents=TRUE, plot.percent.low = FALSE,
plot.percent.high = FALSE)

# Look at structure of returned ggplot -
# it does not contain all the info used to generate the plot
str(p)

# g is a gtable which contains the grobs that make up the plot
g <- ggplotGrob(p)
g

# Get the list of parent grobs
g$grobs

# layout details
g$layout

# we are interested in the grobs with layout name 'panel'
g1 <- g$grobs[[which(g$layout$name=="panel")]]

# have a look at the children within this gTree
childNames(g1)

# look at the structure - we are interested in the grobs with
# name 'GRID.text.###'
# have a look at fontfamily and its position in the list structure
str(g1)

# extract the position of the grobs with names with 'text' in then
id <- grep("text", names(g$grobs[[which(g$layout$name=="panel")]]$children))

# check
childNames(g1)[id]

# look at grobs to be changed
str(g$grobs[[which(g$layout$name=="panel")]]$children[id])

# loop through the text grobs changing the fonts
for(i in id) g$grobs[[which(g$layout$name=="panel")]]$children[[i]]$gp$fontfamily <- "Georgia"

# plot grid obkects
grid::grid.newpage()
grid::grid.draw(g)

# the use of invisible returns the updated gtable if it assigned to a variable
out <- grid_fam(plot(l28, plot.percents=TRUE, plot.percent.low = FALSE,
plot.percent.high = FALSE))

out


Related Topics



Leave a reply



Submit