I want to generate R-Diagrams using a special font, namely Cormorant-Garamond-Light (Cormorant-Light is also possible). The problem is that it works with every other font, but with this one, all spaces are just ignored.
library(ggplot2)
library(extrafont)
data = data.frame(read.table(file="PATH/TO/FILE"))
p = ggplot(data = data, aes(x = data[1], y = data[2]))
p = p + xlab("Time t/s")
p = p + ylab("Temperature T/°C")
p = p + theme(text = element_text(family = "Cormorant Garamond Light"))
After compiling, there is a warning which contains the following:
1: In grid.Call(L_textBounds, as.graphicsAnnot(x$label), ... :
font width unknown for character 0x20
The resulting pdf-file looks as follows (the code is shortened to make it faster to read)
compiled pdf of the code above
Thanks for potential help!
Related
I am trying to embed the ≤ sign into the fonts of my pdf plot. The ≤ sign is shown in the plot when viewed within RStudio (p1). However, when I save the plot and embed the fonts the ≤ sign is converted to an = sign.
Using the extrafont package I want to save my plot with the CM Roman font. I have tried alternative methods with the device set as cairo_pdf in ggsave(). This embeds the ≤ sign into the pdf, but the font is no longer CM Roman.
What needs to be done so that the ≤ sign remains in the plot and the font is CM Roman?
library(ggplot2)
library(extrafont)
font_import()
font_install("fontcm")
loadfonts()
df <- data.frame(foo = c(2, 4, 8 , 16),
bar = factor(c(1:3, "4\u2264")))
p1 <- ggplot(df, aes(x = bar, y = foo)) +
geom_bar(stat="identity") +
labs(title = "p1: Equality sign shows in RStudio plot") +
theme(text = element_text(family = "CM Roman", size = 25))
p2 <- ggplot(df, aes(x = bar, y = foo)) +
geom_bar(stat="identity") +
labs(title = "p2: Equality sign not shown in .pdf file") +
theme(text = element_text(family = "CM Roman", size = 25))
print(p1)
[![p1 plot][1]][1] # there should be an image of p1 here...
# Sys.setenv(R_GSCMD = "C:/Program Files/gs/gs9.53.3/bin/gswin64c.exe") #~ run once at start of each R session
ggsave("p2.pdf", p2, width = 15, height = 10, units = "in")
embed_fonts("p2.pdf", outfile="p2.pdf")
[![p2 plot][1]][1] # there should be an image of p2 here...
ggsave losing unicode characters from ggplot+gridExtra
There are several solutions in this post. I think it has to do something with encoding, but I am not 100% sure.
I have added a font to my ggplot2-plot, and it works perfectly when viewed in RStudio's plot viewer. However, when I try to save the plot as a PDF, NO text at all is printed (see code and pictures below):
df <- data.frame(x = c(1:10), y = c(1:10)) # Dummy data
plot <- ggplot(df, aes(x, y)) + # Dummy plot
geom_point() +
labs(title = "Correct font in R, NO fonts at all in pdf :-(") +
theme(text = element_text(family = "latex"))
Then I try to ggsave() the plot with the following code:
ggsave("df_plot.pdf",
plot = plot,
device = "pdf",
dpi = 320)
But I get an error message:
Error in grid.Call.graphics(C_text, as.graphicsAnnot(x$label), x$x,
x$y, : invalid font type
Below is the plot with the correct fonts (in RStudio) + the plot that is written to my pdf file (with no fonts at all):
Plot with correct font
Plot witn NO text
What am I missing here? I've tried various stuff with the extrafont package, but the pdfs don't print the fonts there either (if something is printed, its just the default fonts).
Actually, ggsave() appears to work fine for me. The error is actually adding the theme(text = element_text(family = "latex")) to the plot.
Adjusting the example a little bit,
df <- data.frame(x = c(1:10), y = c(1:10)) # Dummy data
plot <- ggplot(df, aes(x, y)) + # Dummy plot
geom_point() +
labs(title = "Correct font in R, NO fonts at all in pdf :-(")
ggsave("df_plot.pdf",
plot = plot,
device = "pdf",
dpi = 320)
#Saving 10.7 x 8.01 in image
But,
plot + theme(text = element_text(size=10, family="LM Roman 10"))
produces the error you've found:
Error in grid.Call(C_textBounds, as.graphicsAnnot(x$label), x$x, x$y, :
polygon edge not found.
This question has already been answered here:
Error in grid.Call(L_textBounds, as.graphicsAnnot(x$label), x$x, x$y, : Polygon edge not found
Do these suggestions work for you?
you may consider using the extrafont package:
library(tidyverse)
library(extrafont)
fonts()
df <- data.frame(x = c(1:10), y = c(1:10)) # Dummy data
windowsFonts(Calibri = windowsFont("Calibri"))
plot <- ggplot(df, aes(x, y)) + # Dummy plot
geom_point() +
labs(title = "Correct font in R, NO fonts at all in pdf :-(") +
theme(text = element_text(size=15, family= "Tw Cen MT Condensed Extra Bold"))
ggsave("df_plot.pdf",
plot = plot,
device = cairo_pdf,
dpi = 320)
If I want to change the font size of a geom_text I can use the size parameter. But what if I have a ggplot object which is generated by somebody else (in a function say) and I want to change the font size afterwards? (I could rewrite the function and allow for an additional size parameter, but I want to avoid that).
I played with theme(text = element_text(size = 20)), but this changed every text, but the geom_text? I also tried to replace the respective layer by a new geom_text layer. However, since in the foreign function call the data argument for the geom_text was altered, I get an error about missing aesthetics.
Code
library(ggplot2)
functionICannotControl <- function() {
mdat <- mtcars
mdat$cyl2 <- LETTERS[mdat$cyl]
ggplot(mtcars, aes(x = hp, y = mpg)) + geom_text(aes(label = cyl2), data = mdat)
}
(bp <- functionICannotControl())
## changed only other text elements
bp + theme(text = element_text(size = 20))
## gives an error
bp2 <- bp
bp2$layers[[1]] <- geom_text(size = 20)
bp2
## Error: geom_text requires the following missing aesthetics: label
bp2$layers[[1]] <- geom_text(aes(label = cyl2), size = 20)
bp2
## Error in eval(expr, envir, enclos) : object 'cyl2' not found
OK, I found the solution (and for reference, if somebody is having the same problem). We can change the aes_params slot of the layer:
bp$layers[[1]]$aes_params
## named list()
bp$layers[[1]]$aes_params$size <- 20
bp
N.B. It does help to write a minimal working example because by posing a well structured question, you can learn something about your own problem ;)
Is there a good practice to insert unicode characters in a ggplot title and also save it as pdf?
I am struggling with expression, paste and sprintf to get a nice title...
So, what works is
ggtitle(expression(paste('5', mu, 'g')))
This will print an ugly greek mu. By ugly I mean a different font, but overall, it will be printed as pdf without problems. But the problems start, if you want to have new lines in the title. Or maybe I didn't found a solution for this.
My preferred solution would be to use sprintf with the unicode number, so for example
ggtitle(sprintf('5\u03BCg'))
It shows a nice result on the screen but it is not possible to save as pdf with ggsave. PNG works fine, but I would like to use the pdf save option.
Is there a possibility to plot the unicode characters with ggsave? I read about the cairo_pdf device, but this messes up the fonts and I can not save the plot properly.
Thanks in advance for any help.
EDIT:
Example PDF
I just uploaded an example PDF... So maybe my problem is somewhere else...
Try
library(ggplot2)
p <- ggplot(df, aes(x=date, y=value))
p <- p + geom_line()
p + ggtitle(sprintf('5\u03BCg'))
library(Cairo)
ggsave("newfile.pdf", device=cairo_pdf)
data
set.seed(42)
df <- data.frame(date = 1:10 , value = cumsum(runif(10 , max = 10)) )
Using the emojifont package fixes this issue for me.
library(emojifont)
I am sharing the tricks to have Unicode characters properly displayed on PDF files. I am currently running R-4.0.5 for Windows.
library(ggplot2)
library(gridExtra)
library(grid)
library(png)
#--- The trick to get unicode characters being printed on pdf files:
#--- 1. Create a temporary file, say "temp.png"
#--- 2. Create the pdf file using pdf() or cairo_pdf(), say "UnicodeToPDF.pdf"
#--- 3. Combine the use of grid.arrange (from gridExtra), rasterGrob (from grid), and readPNG (from png) to insert the
# temp.png file into the UnicodeToPDF.pdf file
test.plot = ggplot() +
geom_point(data = data.frame(x=1, y=1), aes(x,y), shape = "\u2191", size=3.5) +
geom_point(data = data.frame(x=2, y=2), aes(x,y), shape = "\u2020", size=3.5) +
geom_point(data = data.frame(x=1.2, y=1.2), aes(x,y), shape = -10122, size=3.5, color="#FF7F00") +
geom_point(data = data.frame(x=1.4, y=1.4), aes(x,y), shape = -129322, size=3.5, color="#FB9A99") +
geom_point(data = data.frame(x=1.7, y=1.7), aes(x,y), shape = -128515, size=5, color="#1F78B4") +
ggtitle(sprintf('5\u03BCg'))
ggsave("temp.png", plot = test.plot, width = 80, height = 80, units = "mm")
#--- Refer to http://xahlee.info/comp/unicode_index.html to see more unicode character integers
pdf("UnicodeToPDF.pdf")
grid.arrange(
rasterGrob(
readPNG(
"temp.png",
native=F
)
)
)
dev.off()
file.remove("temp.png")
This is a simple question.
I am trying to write a legend with text in small caps in R.
I can write the plot using tikzDevice and manually change the plot to small-caps in LaTex, but I want to know if it's possible in R itself?
Thanks.
This is the R code I am using so far:
legend("bottomright", inset=.05, c(expression(Delta*ZRT1), expression(Delta*ZRT2)), lty=1:2, pch=1:2)
This is the LaTex expression I am trying to get into the R legend:
\Delta Z\textsc{rt\oldstylenums{1}}
The Unicode standard does define a number of "small capital" characters in the IPA extensions.
E.g., using this Smallcaps Generator: http://fsymbols.com/generators/smallcaps/
plot(1L:10, main="Aʙᴄᴅᴇғɢʜɪᴊᴋʟᴍɴᴏᴘǫʀsᴛᴜᴠᴡxʏᴢ")
legend("bottomright", expression(\Delta Zʀᴛ1")
As of Unicode 5.1, the only characters missing to allow representation of the full Latin alphabet in small capital Unicode characters are small capital versions of Q and X.
See also here: http://en.wikipedia.org/wiki/Small_caps#Unicode
The small caps generated by Smallcaps Generator do not work for all fonts. For example, the Linux Libertine family (Libertine, Biolinum) have their small caps and Old Style numbers in the Unicode Private Use Area (E000-F8FF), as shown here (last page).
The example plots below use axis labels assembled from the small caps generator, plus the small_caps and small_nums string, assembled from the private use area. The first plot uses Times New Roman, which works with the generated small caps but does not have corresponding glyphs in the private use area. The second plot uses Linux Libertine O, which does not have all Unicode characters from the IPA extensions.
library(ggplot2)
x <- 1L:10
y <- 1L:10
df <- data.frame(x,y)
# assemble strings from Libertine's private use area.
small_caps <- "S\UE05D\UE051\UE05C\UE05C C\UE051\UE060\UE063"
small_nums <- "\UE020\UE021\UE022\UE023\UE024\UE025\UE026\UE027\UE028\UE029"
font <- "Times New Roman"
ggplot(df) +
geom_point(aes(x = x, y = y)) +
labs(x = paste("Sᴍᴀʟʟ Cᴀᴘs /", small_caps),
y = paste("Oʟᴅ Sᴛʏʟᴇ", small_nums)) +
theme(text = element_text(family = font)) +
annotate("text", x = 2, y = 9, label = font)
font <- "Linux Libertine O"
ggplot(df) +
geom_point(aes(x = x, y = y)) +
labs(x = paste("Sᴍᴀʟʟ Cᴀᴘs /", small_caps),
y = paste("Oʟᴅ Sᴛʏʟᴇ", small_nums)) +
theme(text = element_text(family = font)) +
annotate("text", x = 2, y = 9, label = font)
Created on 2018-12-08 by the reprex package (v0.2.1)