R: using libertine font in eps - error message - r

I am building a map in R that I would like to have the text to be shown in Linux Libertine font. Package extrafont is loaded, fonts have been loaded and the path to ghostscript is correctly set.
When I use the following command, R saves the output and everything works fine.
ggsave(file = foo.eps, plot = map, width = 15, height = 10, units = "cm", family='Linux Libertine Display')
However when I instead use family='Linux Libertine', I receive the following error message:
Error in grDevices::postscript(..., onefile = FALSE, horizontal = FALSE, :
unknown family 'Linux Libertine'
It seems that it can't find the font, which is weird as it is listed in the return of fonttable(). Any ideas how I can make R to use the font?

The link provided by user TomNash does indeed explain the problem and the solution:
The problem is that some fonts (and this includes Linux Libertine) have distinct font face names (Linux Libertine Bold, Linux Libertine Italics, etc.) but all share the same family name (Linux Libertine). The extrafont package cannot distinguish between those fonts, because it only looks at the family name (and in the above example Linux Libertine Display works, because this is a unique family name).
The easiest way to fix this is to locate the directory of the font table: system.file("fontmap", "fonttable.csv", package="extrafontdb") and then open the fonttable.csv and copy for all Linux Libertine fonts (or whatever fonts this concerns) the font name into the font family cell. Then return to R and execute loadfonts() again to make sure R rebuilds the font table.

Related

Graph label issue with displaying Korean

I'm currently trying to display Korean in my graph (a simple histogram), which I've generated in R.
But it won't display Korean correctly.
Could someone please help? Many thanks in advance!
hist(df$var, main = "abc가나다", xlab = "def마바사")
You are probably using the default font — Helvetica — which is missing Hangul glyphs. You can either configure a font which has these via par(family = …).
Or you can use the ‘ragg’ package to plot to a graphics device which supports font fallback: this means that the graphics device will automatically select a font that supports the glyphs you’re using.
With ‘ragg’, you can do the following:
capture = ragg::agg_capture()
hist(df$var, main = "abc가나다", xlab = "def마바사")
plot_data = capture()
dev.off()
plot(as.raster(plot_data))
Admittedly, this is a bit cumbersome. However, for plotting to a file, using ‘ragg’ is no more effort than using base R: you just replace the device, e.g. agg_png instead of png.

ggplot2 Font on PDF error message: "Font Family not found"

I am having a problem of getting Fontawesome5 to work in R. I have installed the latest version of R, and therefore all have updates all the packages used as well, and I can't get the font to work in R. It is used to make info graphics, see the website here: https://www.listendata.com/2019/06/create-infographics-with-r.html
Once I upload the ttf. files into R i get this error message:
In grid.Call.graphics(C_text, as.graphicsAnnot(x$label), ... :
font family 'FontAwesome5Free-Solid' not found, will use 'wqy-microhei' instead
This means that I get a plot back with no font in it, just a dot. (see picture) [R plot without font1
It would appear R can't put Fontawesome5(5th version) onto the ggplot2/pdf. Is there a way to make this font work in R with ggplot?, regards James.
library(ggplot2)
library(waffle)
library(extrafont)
library(tidyverse)
library(echarts4r)
library(echarts4r.assets)
install.packages("extrafontdb", repos = "http://cran.rstudio.com/")
library(extrafont)
#font download: https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/fonts/fontawesome-webfont.ttf
extrafont::font_import (path="C:/file/location/Documents/R", pattern = "awesome", prompt = FALSE)
install_fa_fonts()
extrafont::font_import (path="C:/Users/User/Documents/R/win-library/4.0/waffle/fonts") #path is where R installs file:
loadfonts(device = "win") #loads in fonts
fonts()[grep("Awesome", fonts())] # should say Awesome fonts 5 in installed.
waffle(
c(`Poor=10` =10, `Average=18` = 18, `Excellent=7` =7), rows = 5, colors = c("#FD6F6F", "#93FB98", "#D5D9DD"),
use_glyph = "female", glyph_size = 12 ,title = 'Girls Performance', legend_pos="bottom"
)
This happened to me after I had updated my Mac OS to Catalina. After weeks of research (and minutes after I had commented on your post here), I found a solution that at least worked for me.
It seems (but please correct me if I'm wrong) that the R package extrafont can only deal with .ttf font files. And it seems like Catalina converted my fonts to .ttc, so I had to convert these back into .ttf and copy paste these .ttf into the System fonts folder.
In short, convert your fonts from .ttc to .ttf
Similar to what they figured out here:
https://github.com/wch/extrafont/issues/32
I used transfonter.org to convert my fonts.

Is it possible in R to test for the existence of specified `grDevices::windowsFonts` and specify a backup if the test fails?

I am working on a ggplot2 extension package for my organization to use, to apply our design guidelines to all of our R charts. Part of this requires the use of specific fonts. We use the Whitney typeface on our published visualizations, but not all users have the required fonts installed on their computers. I would like the package to check whether Whitney is installed and, if not, specify an alternate, widely-available font (e.g. Calibri) to use as a backup.
The following code will run successfully, without warnings, regardless of whether "Whitney Medium" is actual installed on the PC. If it is not installed, the plotted text will display in Arial.
grDevices::windowsFonts(font_reg = "Whitney Medium")
graphics::plot(c(0,2), c(0,2), type="n", xlab="", ylab="")
graphics::par(family="font_reg")
graphics::text(1, 1, "font_reg", cex=4)
How can I verify that "Whitney Medium" is a valid font on a given PC, and specify a backup if it's not?
Note: Our Whitney font files are OTF, not TTF, so I can't use the extrafont package. I also would like to avoid using showtext because I really want to find a solution that works in the RStudio plotting window.
The code for windowsFonts might need to be overwritten if you need to make this automatic. When called with no arguments, the available fonts are returned as a named list. Otherwise you might try something like as a preamble to your plotting call:
if ("Whitney Medium" %in% names( windowsFonts()) ) { .. proceed as usua } else {
windowsFonts("sans" = "Arial") }
If you have font_reg as a text value passed to the graphics functions, then you might use that instead of "sans".
I ended up using sysfonts::font_files() to identify installed/available fonts, and using Calibri if Whitney is not in the results.
whitney_fonts <- dplyr::filter(sysfonts::font_files(),
family == "Whitney Medium"
)
if (length(whitney_fonts$family) > 0) {
grDevices::windowsFonts(font_reg = "Whitney Medium")
} else {
grDevices::windowsFonts(font_reg = "Calibri")
}

r wordcloud external ttf vfont not recognized

I've installed the 'extrafont' package in order to install an external font library Duality via the ttf_import() method. However, when specifying the font via the wordcloud method, I receive the following error:
Installation command:
# Assuming the font file, DUALITY_.ttf, is in the working directory (see link to font above)
font_import(".",FALSE,pattern="DUALITY")
Wordcloud command:
wordcloud(ap.d$word, ap.d$freq, scale=c(8,2), min.freq=10, vfont=c("Duality","plain"),
random.order=FALSE, rot.per=0, use.r.layout=FALSE, colors=pal2, fixed.asp=FALSE)
Output:
Error in strwidth(words[i], cex = size[i], ...) :
invalid 'vfont' value [typeface -2147483648]
In order to verify that the font is indeed installed, I issued the following commands
> choose_font("Duality")
[1] "Duality"
> fonts()
....[49] "Waree" "Duality"
How come the Duality font is not visible to the vfont parameter of wordcloud? And how do I make it visible to Cairo (the default renderer). TIA!
I've been able to overcome the same problem using the parameters passed to text family and font and described in ?par instead of vfont. Also I needed to load the font first. So the thing goes:
Import the font (sorry, the link to Duality provided in OP is no longer available, I use Lucida Handwriting instead, available in windows):
library(extrafont)
font_import(pattern="LHANDW")
Load (see this blog for details):
loadfonts() # loadfonts(device = "win") if you are working in windows
Wordcloud:
wordcloud(ap.d$word, ap.d$freq, scale=c(8,2), min.freq=10, family="Lucida Handwriting", font=1,
random.order=FALSE, rot.per=0, use.r.layout=FALSE, colors=pal2, fixed.asp=FALSE)
To complement previous answers, and explain how one can actually choose which fonts to use. First, import fonts (it is possible to set a path different from the default in font_import()
library(extrafont)
font_import(prompt = FALSE)
To know which fonts are available:
unique(fonttable()$FamilyName)
This presents the exact reference for what to include as "font family". You can then issue the wordcloud command like this:
wordcloud(c(letters, LETTERS, 0:9), seq(1, 1000, len = 62), family = "Carlito", font = 1)
Why font = 1? From ?par(), here's what it says about the font parameter:
An integer which specifies which font to use for text. If possible,
device drivers arrange so that 1 corresponds to plain text (the
default), 2 to bold face, 3 to italic and 4 to bold italic.

Can't change fonts in ggplot/geom_text

I can't set my fonts in geom_text. Here is what I tried:
labels_test<-data.frame(a=c("a","b","c"),b=c(1:3),c=c(3:1))
# works
ggplot () + geom_text(data=labels_test,aes(b,c,label=a),color="blue")
# does not work:
ggplot () + geom_text(data=labels_test,aes(b,c,label=a),color="blue",family="Times")
# error message: In grid.Call.graphics(L_text, as.graphicsAnnot(x$label), x$x, x$y,:
# Font family not found in Windows font database
I already imported all fonts as indicated here. Any ideas what is still going wrong?
The other answers didn't solve my problem (Windows 10).
The key for my system was to call extrafont::loadfonts(device="win") prior to library(ggplot2).
extrafont::loadfonts(device="win")
#extrafont::fonttable()
#extrafont::font_import("C:/Windows/Fonts/", pattern = "RobotoCondensed")
library(ggplot2)
Common problem with font locations:
I had installed the fonts from a random folder with extrafont::font_import() previously. As such extrafont::fonttable() referenced the files in my C:\Windows\Fonts\ folder. To fix this I reset my extrafonts::fonttable() with install.packages("extrafontdb") in order to clear a reference to the fonts in a different location.
Edit regarding saving:
Deeper down the rabbit hole. Saving was an additional challenge. In order to extrafont::loadfonts(device="pdf") I had to make sure no fonts in my extrafont::fonttable() had identical family names and bold/italic status. I edited extrafont:::fonttable_file() to resolve any duplicate bold/italic fonts within my family. Using Roboto Condensed I renamed the light fonts' font family to "Roboto Condensed Light".
Saving with ggsave(device="pdf") then worked. Opening the files in acrobat the fonts did not display correctly. I tried embedding the fonts with ghostscript as well as using the cairo_pdf device. The easiest and most functional solution was to open the .pdf files in Illustrator (the fonts display fine there) and immediately re-save them again as .pdf.
Edit 2 regarding saving:
Saving as .eps was the only way to preserve the file in both illustrator and acrobat. The result is perfect. ggsave(g, file="Figure.eps", fonts=c("FONT FAMILIES USED", "Roboto Condensed", "Roboto Condensed Light"))
Final plotting code:
Here is my final set of calls I use before plotting. Comments are setup commands that need to be run once only.
# Plotting
extrafont::loadfonts(device="pdf")
extrafont::loadfonts(device="postscript")
# extrafont::font_import("C:/Windows/Fonts/", pattern = "RobotoCondensed", prompt = F)
# extrafont::fonttable()
# C:/Program Files/R/R-3.3.1/library/extrafontdb/fontmap/ - Change lights to "Roboto Condensed Light"
# After ggsave(device="pdf") or ggsave(device="eps") open and resave the file in Illustrator
library(hrbrthemes)
library(ggplot2)
I would try"
windowsFonts(Times=windowsFont("TT Times New Roman"))
In doing this your specifying explicitly the Windows Font mapping.
You must import the system fonts using the command:
font_import(paths = NULL, recursive = TRUE, prompt = TRUE,pattern = NULL)
I tried the different solutions here but none worked for me (win10, R 3.4.3).
This is what worked for me:
install.packages("extrafont")
library(extrafont)
loadfonts(device = "win")
It did not matter if I did it before or after library(ggplot2)
Sources:
https://cran.r-project.org/web/packages/extrafont/extrafont.pdf
Changing fonts in ggplot2

Resources