I am trying to understand how to make sure the font i am exporting from both base and ggplot2 plots is the same. The best would be to be able to have all plots from ggplot2 but for some reason, one plot i need to do with base R. I wrote an example code that exports svg for both ggplot and base r. I found a previous post suggesting the font that is normally used by base R is Helvetica. For ggplot it seems more tricky.
The first link suggests to have a look at available fonts. Here the output:
> X11Fonts()
$serif
[1] "-*-times-%s-%s-*-*-%d-*-*-*-*-*-*-*"
$sans
[1] "-*-helvetica-%s-%s-*-*-%d-*-*-*-*-*-*-*"
$mono
[1] "-*-courier-%s-%s-*-*-%d-*-*-*-*-*-*-*"
$Times
[1] "-adobe-times-%s-%s-*-*-%d-*-*-*-*-*-*-*"
$Helvetica
[1] "-adobe-helvetica-%s-%s-*-*-%d-*-*-*-*-*-*-*"
$CyrTimes
[1] "-cronyx-times-%s-%s-*-*-%d-*-*-*-*-*-*-*"
$CyrHelvetica
[1] "-cronyx-helvetica-%s-%s-*-*-%d-*-*-*-*-*-*-*"
$Arial
[1] "-monotype-arial-%s-%s-*-*-%d-*-*-*-*-*-*-*"
$Mincho
[1] "-*-mincho-%s-%s-*-*-%d-*-*-*-*-*-*-*"
This is the code i am using to export the plots as svg images:
# load libraries
library("ggplot2")
# declare function to export plots
export_svg <- function(filename, a_plot, base=FALSE) {
# if plot is made with ggplot2
if (base==F) {
# plot
svg(filename, width=10, height=10)
plot(a_plot)
dev.off()
# else with base R
} else {
# plot
svg(filename, width=10, height=10)
a_plot
dev.off()
}
}
# create a basic data frame
df <- data.frame(x=c(1, 3, 7), y=c(2, 4, 6), label=c("a_label", "a_second_label", "a_third_label"))
# declare plotting function for base plots
base_plot <- function(df){
par(mar = c(5, 5, 4, 2))
plot(df$x, df$y, xlim=c(-5, 10), ylim=c(-5, 10))
text(df$x, df$y, labels=df$label)
}
# declare plotting function for ggplot
ggplot_plot <- function(df) {
ggplot(df, aes(x=x, y=y)) + geom_point() + geom_text(aes(label=label),hjust=0, vjust=0) + xlim(-5, 10) + ylim(-5, 10) + theme_bw()
}
# export base
export_svg("base.svg", base_plot(df), base=TRUE)
# export ggplot
export_svg("ggplot.svg", ggplot_plot(df), base=FALSE)
How do i make sure if the two fonts exported are the same font? They may be the same, but the look slightly different, which may be a problem related to the exporting of pdfs, as suggested by the developer of extrafont. It seems, to me, that svg suffers from the same problem. Do you have any ideas?