I recently came upon a problem in R which in that combination I have tried to solve and also searched for in the internet, but which I could not solve yet. I hope someone can help me.
I run R(x64) on Windows 7. The graphic device itself automatically uses Arial as font, and when I save graphs as bitmap the "font" naturally remains as it is. However, I prefer saving graphs as pdf, in which case the font in the resulting pdf is exchanged with Helvetica when I simply save via the GUI save button.
I found a solution for that in the internet, using the Arial afm-Files and pdf("Test_Auto.pdf", family = "Arial"), which resulted in a pdf using Arial as font---so far so good.
Now I also often have to/want to change the graph layout using win.graph, and that is where the problems start. Here is an example:
Arial <- Type1Font(family = "Arial", metrics = c("C:/R_Fonts/ArialPlain.afm", "C:/R_Fonts/ArialBold.afm", "C:/R_Fonts/ArialItalic.afm", "C:/R_Fonts/ArialBoldItalic.afm"))
pdfFonts(Arial = Arial)
setwd("C:/PDFCrop")
D1<-matrix(c(1,2,3,4,6,3),3,2)
D2<-matrix(c(1,2,3,5,3,1),3,2)
#pdf("Test_Auto.pdf", family = "Arial")
win.graph(8.3,12,12)
layout(matrix(c(1,2),1,2,byrow=TRUE))
plot(D1,type="l",main="Gobble R")
plot(D2,type="l",main="Gobble R")
#dev.off()
Now this code as it is works to create a graph that looks like I want it to look, but I have to save the graph manually (File->save as) and then I get Helvetica as font in the pdf.
Alternatively I can change the lower part in
pdf("Test_Auto.pdf", family = "Arial")
#win.graph(8.3,12,12)
layout(matrix(c(1,2),1,2,byrow=TRUE))
plot(D1,type="l",main="Gobble R")
plot(D2,type="l",main="Gobble R")
dev.off()
And that produces a pdf-file that actually uses Arial, but the graph has other dimensions as I was intending. When using both together I get a pdf which "cannot be opened because it does't contain any pages" (though it is not 0KB in size).
Is there any way to get this to work, or an alternative to win.graph which I can use between pdf() and dev.off()?
Thanks for you help.
Oh my god, I'm sorry, I was so stupid!
During all that I completely overlooked, that the pdf-device has its own size parameters.
Arial <- Type1Font(family = "Arial", metrics = c("C:/R_Fonts/ArialPlain.afm", "C:/R_Fonts/ArialBold.afm", "C:/R_Fonts/ArialItalic.afm", "C:/R_Fonts/ArialBoldItalic.afm"))
pdfFonts(Arial = Arial)
setwd("C:/PDFCrop")
D1<-matrix(c(1,2,3,4,6,3),3,2)
D2<-matrix(c(1,2,3,5,3,1),3,2)
pdf("Test_Auto.pdf", width=8.3, height=12, family = "Arial")
#win.graph(8.3,12,12)
layout(matrix(c(1,2),1,2,byrow=TRUE))
plot(D1,type="l",main="Gobble R")
plot(D2,type="l",main="Gobble R")
dev.off()
Thank you for the hint, DWin
Related
I'm trying to save a rather large ggpairs file. For some reason I can't get ggsave to work on my device (the file is created but it's blank no matter the plot, file type etc.) so I have been manually right clicking on save image as on the output.
However the resolution is so poor you can't read the correlation information as I've had to reduce the font size.
Appreciate any suggestions on how to get out a readable output.
TIPI_data<- vms_data[, c("cond","group_aff","personal_exp","outcomes","mechanics", "TIPI_O", "TIPI_C", "TIPI_E","TIPI_A","TIPI_N")]
ggpairs(TIPI_data, ggplot2::aes(colour=cond), upper = list(continuous = wrap("cor", size = 1.5)))
I don't know if this works for you, it worked for me. I have used this code to save as png with high resolution:
corrPlot <- ggpairs(df, diag=list(continuous="density"), axisLabels='show')
png(filename, height=1000, width=1000)
print(corrPlot)
dev.off()
I used this reference: https://github.com/tidyverse/ggplot2/issues/650#issuecomment-65086626
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.
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.
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
I'm having trouble with exporting eps files from R and importing into Word 2010.
I'm using ggplot2 plots, eg
library(ggplot2)
p <- qplot(disp,hp,data=mtcars) + stat_smooth()
p
Even after calling setEPS() neither of the following produce files which can be successfully imported.
ggsave("plot.eps")
postscript("plot.eps")
print(p)
dev.off()
The strange thing is that if I produce the plot using File -> Save As -> Postscript from the menu in the GUI, it can be imported correctly. However, when the Word document is subsequently exported as a pdf, the fonts in the graphic are a little jagged.
So my questions are:
What combination of (ggsave/postscript) settings allows me to produce eps files that can be imported into Word 2010?
How can I ensure the fonts remain clear when the Word document is exported as a pdf?
Update
After more investigation I have had more luck with cairo_ps to produce the plots. However, no text shows up when imported into Word.
Furthermore, after checking the various eps outputs (cairo_ps, save from the GUI, ggsave) in a latex document, it seems like the eps import filter in Word quite poor as the printed/pdf output doesn't match the quality of the latex'd document. The ggsave version (which uses postscript) did have some issues with colours that the other two methods didn't have though.
The conclusion is that this is a Word issue and therefore fortune(109) does not apply. I'd be happy to be proven otherwise, but I'll award the answer and the bounty to whoever can provide the commands that can replicate the output from the GUI in command form.
This worked for me... following advice in the postscript help page:
postscript("RPlot.eps", height = 4, width = 4, horizontal = FALSE, onefile = FALSE,
paper = "special")
library(ggplot2)
p <- qplot(disp,hp,data=mtcars) + stat_smooth()
p
#geom_smooth: method="auto" and size of largest group is <1000, so using loess. Use 'method = x' to #change the smoothing method.
#Warning message:
#In grid.Call.graphics(L_polygon, x$x, x$y, index) :
# semi-transparency is not supported on this device: reported only once per page
dev.off()
#quartz
# 2
The funny stuff at the end puts you on notice that this is only a Mac-tested solution, so far anyway.
Edit: I just tested it with R version 2.15.1 (2012-06-22) -- "Roasted Marshmallows": Platform: i386-pc-mingw32/i386 (32-bit) and MS Word 2007 in Win XP and it worked. Commands were Insert/Picture.../select eps format/select file.
Edit2: There is another method for saving besides directly using the postscript device. The savePlot method with an "eps" mode is available in Windows (but not in the Mac). I agree that the fonts are not as smooth as they appear on a Mac but I can discern no difference in quality between saving with savePlot and using save as from an interactive window.
savePlot(filename = "Rplot2", type = "eps", device = dev.cur(), restoreConsole = TRUE)
savePlot calls (.External(CsavePlot, device, filename, type, restoreConsole))
I solved the problem with exporting .eps files from R and importing into Word 2010 on Windows 7 using the colormodel="rgb" option (defaults to "srgb") of the postscript command.
postscript("RPlot.eps", height = 4, width = 4, horizontal = FALSE,
paper = "special", colormodel = "rgb")
library(ggplot2)
p <- qplot(disp,hp,data=mtcars) + stat_smooth(se=FALSE, method="loess")
p
dev.off()
You are probably better of using wmf as a format which you can create on Windows.
Word indeed doesn't support EPS very well.
A better solution is to export your graphs to Word or Powerpoint directly in native Office format. I just made a new package, export, that does exactly that, see
https://cran.r-project.org/web/packages/export/index.html and
for demo
https://github.com/tomwenseleers/export
Typical syntax is very easy, e.g.:
install.packages("export")
library(export)
library(ggplot2)
qplot(Sepal.Length, Petal.Length, data = iris, color = Species,
size = Petal.Width, alpha = I(0.7))
graph2doc(file="ggplot2_plot.docx", width=6, height=5)
graph2ppt(file="ggplot2_plot.pptx", width=6, height=5)
Output is vector format and so fully editable after you ungroup your graph in Word or Powerpoint. You can also use it to export statistical output of various R stats objects.
You can use R studio to knit html files with all of your plots and then open HTML files with Word.
knitr tutorial