R

Getting the cool symbols onto graphs in R

In theory, R is very comfortable with unicode (individual operating systems and locales may vary this) so it should be possible to type in unicode and graph in unicode. But the process is limited by the palettes of the default fonts. So if you see what symbols will actually plot, the results can be disappointing.

was made with the code

df <- data.frame(a=rep(1:20, times=20),b=rep(1:20, each=20))
start=9500
df$utf_sym <- sapply((9500 + 0:399),intToUtf8)

png(filename = "testutf_default.png", width=800, height=800)
plot(df$a,df$b, pch=df$utf_sym)
dev.off()

It is OK if I want to use playing card symbols, but for most things in the symbol range I am out of luck, even though I have fonts that can cope on my computer.

So this is what you do.

Work out a font that has the symbol you want in it (this is your problem). I suggest installing the google Noto fonts if you seem lacking in choice.

https://www.google.com/get/noto/help/install/

Install the showtext package. Activate it.

library(showtext)

Add the path to the regular version of font you want to use, if the font is in a default location, as shown by

font.paths()

you only need the path from the default location to the font. To add the path use the font.add() command.

font.add(family="Noto", regular="NotoSansSymbols-Regular.ttf")

make the graph, only activating the added family when you need it (I am also using the Cairo package for a sharper looking PNG)

library(Cairo)
CairoPNG("Cairo_Noto_Unicode.png", width=800, height=800)
showtext.begin() 
plot(df$a,df$b, pch=df$utf_sym, family="Noto")
showtext.end() 
dev.off()

I am specifically creating an image file for this, and in writing to the image R can draw on all of the symbols in the font.

 

Which means I can now set plot symbols by typing the unicode (if I know how to type the unicode)

library(Cairo)
CairoPNG("Cairo_Noto_Umbrella.png", width=800, height=800)
showtext.begin() 
plot(1:10,1:10, pch="☂", family="Noto")
showtext.end() 
dev.off()

The umbrella type inside the pch=”” might not show if your web browser cannot cope with unicode. But the result is:

for all those examples, the Noto Symbol font doesn’t include letter characters, so we would be better only putting it on for the point plotting.

library(Cairo)
CairoPNG("Cairo_Noto_points.png", width=800, height=800)
plot(1:10,1:10, type="n")
showtext.begin()
points(1:10,1:10, pch="☂", family="Noto")
showtext.end() 
dev.off()

We could define several different families and use them all in the one graph in different places.

 

Leave a comment