corrupted UTF characters in pdf plots generated by R - r

I am trying to save plots with legends containing UTF characters for Males and Females to pdf in R. When I plot to graphics device :
plot(1)
legend('topright', bty = 'n',
expression(italic("legend"~"\u2640"~"\u2642")))
the legend of plot looks as expected
I can even save it to pdf by right click and "save to pdf". However, when I use inbuilt function pdf
pdf('test.pdf')
plot(1)
legend('topright', bty = 'n',
expression(italic("legend"~"\u2640"~"\u2642")))
dev.off()
it drops a warning and shows corrupted characters instead:
cairo_pdf does not drop a warning, but it does not show the correct symbols either:
According to this post, I should specify encoding that would support my symbols, however I have no idea how to find out which it does (besides default Helvetica I tried MacRoman without success).
It is apparent that it is possible for R to generate pdf that contains these symbols (because I am able to do so by the right click). However, I would like to achieve that in automatized manner.
My R session settings:
R version 3.3.1 (2016-06-21)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.11.5 (El Capitan)
locale:
[1] en_US.UTF-8/C/en_US.UTF-8/C/en_US.UTF-8/C
attached base packages:
[1] stats graphics grDevices utils datasets methods base
I also managed to reproduce same behaviour on another computer with macOS Sierra 10.12.1.

A working answer on OS X is using quartz:
quartz(type = 'pdf', file = 'test.pdf')
Source : https://stackoverflow.com/a/19610909/2962344
cairo_pdf seems to work on Linux.

hi this is working for me (on windows)
cairo_pdf('test.pdf' , family="DejaVu Sans")
plot(1)
legend('topright', bty = 'n',
paste("legend",quote("\u2640") ,quote("\u2642") ))
dev.off()
Unicode Characters in ggplot2 PDF Output
on mac try this
pdf('test.pdf',encoding="MacRoman")
Plotting symbols fails in PDF

I had the same problem, the other solutions did not work for me, and finally I used png instead of pdf:
png('test.png', units="in", width=11, height=10, res = 600)
plot(1)
legend('topright', bty = 'n',
expression(italic("legend"~"\u2640"~"\u2642")))
dev.off()

Related

R: Suppress base graphics plot but return plot as object

I have a function that both returns some statistics and makes a plot using R base graphics. I want to suppress the plotting from that function and instead return the plot as an object, so that plotting or not can be controlled from outside the function.
I've tried:
Using the gridGraphics package I can convert a base graphics plot to an object as suggested in this question:
plot(1:10)
grid.echo()
a = grid.grab()
grid.draw(a)
The remaining problem is that plot() command draws the plot that I want to suppress. Thus I tried to suppress it by plotting to a device in a temp file like answer here suggests. Code becomes:
ff = tempfile()
svg(filename = ff)
plot(1:10)
grid.echo()
a = grid.grab()
dev.off()
unlink(ff)
but now, grid.echo() can not find any graphics to echo, and throws warning:
Warning message:
In grid.echo.recordedplot(recordPlot(), newpage, prefix, device) :
No graphics to replay
I've traced this problem back to grid.echo() not being able to echo graphics from other devices than the Rstudio default device, regardless of being in a temp file or not. This is in itself strange, since grid.echo() docs says it echoes graphics from the current device, not mentioning any restrictions.
Can anyone help me to solve the problem of suppressing base graphics plot and returning it as object, either by suggesting how to fix my broken attempt, or with another approach?
LocoGris solved the problem in this related question about the behaviour of grid.echo.
The following code will plot the unwanted graphics output into a tempfile, save the plot as a grid object using grid.echo and grid.grab before unlinking the tempfile so that only the plot object remains, thereby producing the besired behaviour:
ff = tempfile()
svg(filename = ff)
plotfun <- function() plot(1:10)
grid.echo(plotfun)
a = grid.grab()
dev.off()
unlink(ff)
The difference to code in question is that the plotting in R base graphics is put into a function and passed to grid.echo, instead of relying on grid.echo to automatically find what it needs from the current device.
Potentially useful note: grid.echo will plot two times, which can be seen if using regular svg() without tempfiles, as two files will appear with the same plot. I assume that the first plot is in R base graphics and the second one is the echo using the grid system.

Why is locator() broken in RStudio?

Does anyone know how to fix when RStudio is breaking the locator() function? If I plot
plot(1:10)
then use locator() to click on the same points (1:10), this is what I get after I click the Finish button.
locator(type = 'p', col = 'red')
$x
[1] 1.265369 2.226131 3.172336 4.147655 5.064746 6.040065
[7] 6.986270 7.947032 8.893237 9.868556
$y
[1] 1.437224 2.361029 3.265178 4.169328 5.093133 5.997282
[7] 6.901432 7.825237 8.729386 9.633536
However, if I do the same thing in the R GUI rather than RStudio, then it works just fine:
I've tried restarting my session, using dev.off(), and restarting RStudio but the problem persists. Am I missing something simple here, or maybe it's a bug in RStudio?
R version 3.3.1
RStudio 0.99.903
Mac OSX 10.11.6

R plots some unicode characters but not others

our sysadmin just upgraded our operating system to SLES12SP1. I reinstalled Rv3.2.3 and tried to make plots. I use cairo_pdf and try to make a plot with the x-label being \u0298 i.e. the solar symbol, but it doesn't work: the label just comes out blank. For example:
cairo_pdf('Rplots.pdf')
plot(1, xlab='\u0298') # the x-label comes up blank
dev.off()
This used to work, but for some reason it does not anymore. It works with other characters, e.g.
cairo_pdf('Rplots.pdf')
plot(1, xlab='\u2113') # the x-label comes up with the \ell symbol
dev.off()
When I just paste in the solar symbol, i.e.
plot(1, xlab='ʘ')
then I get the warning
Warning messages:
1: In title(...) :
conversion failure on 'ʘ' in 'mbcsToSbcs': dot substituted for <ca>
The machine is German, but I am using the US English UTF-8 locale:
> sessionInfo()
R version 3.2.3 (2015-12-10)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: SUSE Linux Enterprise Server 12 SP1
locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
[3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
[5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
[7] LC_PAPER=en_US.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
Any tips on how I can get the solar symbol to appear?
Note: I suppose with a new system you should first do:
capabilities() #And see what the result for cairo is.
A couple of ideas although one of them requires knowing what fonts you are using so the output of l10n_info()$MBCS and names(X11Fonts()) might be needed.
Option 1) The Hershey fonts have all the astrological signs as special escape characters. Page 4 of the output of :
demo(Hershey) # has \\SO as the escape sequence for the "solar" symbol.
So looking at the code for the draw.vf.cell function we see that it's using the text function to plot those characters and therefore using it to label an axis will require adding xpd=TRUE to the arguments:
plot(1, xlab="") ; text(1, .45, "\\SO" , vfont=c("serif", "plain"), xpd=TRUE )
Option 2) find the solar symbol in the font of your choice. You might try setting the font to something other than "Helvetica". See ?X11 that has a section on Cairo fonts. The points function's help page has a function called TestChars that lets you print character glyphs in various fonts to your output device. In this case your output device might be either cairopdf or x11. On my device (the Mac fork of UNIX) the Arial font has this output:
png(type="cairo-png");plot(1, xlab="\u0298");dev.off()
My observation over the years of similar questions leads me to believe that Cairo graphics are more reliably cross-platform. But since R can be compiled without cairo support, it's not a sure thing.
Maybe your text editor is using latin1, therfore you would send latin1 characters to your console.
Look at the encoding
Encoding('ʘ')
and / or try
plot(1, xlab=iconv('ʘ', from='latin1', to="UTF-8"))
but be carefull the encoding could change while coping.
If you use Notepad++ you can convert in the text editor between the different encodings.

X11 forwarding over ssh for R: why this warning?

I need to use R (3.0.2 from pkgsrc) on a remote server (NetBSD) over a ssh connection with X11 forwarding. plot(1) is generating the expected graphic on my local machine, however R is also returning warnings in my terminal session as below.
> plot(1)
Warning messages:
1: In (function (display = "", width, height, pointsize, gamma, bg, :
locale not supported by Xlib: some X ops will operate in C locale
2: In (function (display = "", width, height, pointsize, gamma, bg, :
X cannot set locale modifiers
I don't know whether this bodes problems that I may encounter later, but I'd like to get everything set up and configured correctly. Would someone please clarify the meaning of the warnings and explain how to address them?
Edit for more info:
> sessionInfo()
R version 3.0.2 (2013-09-25)
Platform: x86_64--netbsd (64-bit)
locale:
[1] C
attached base packages:
[1] stats graphics grDevices utils datasets methods base
> names(X11Fonts())
[1] "serif" "sans" "mono" "Times" "Helvetica"
[6] "CyrTimes" "CyrHelvetica" "Arial" "Mincho"
The errors are saying that the X11 graphics driver does not know what font to use (see this discussion). By default, R installs with the C locale set. For linux, you need to set a UTF-8 locale which is prefixed by the language.
For example, for the English in the US, you would set it to 'en_US.UTF-8'.
Try setting the system locale with the Sys.setlocale command like so:
Sys.setlocale("LC_CTYPE", "en_US.UTF-8")
Sys.setlocale("LC_ALL", "en_US.UTF-8")
This can be done through the .bashrc configuration file like so:
export LC_CTYPE=en_US.UTF-8
export LC_ALL=en_US.UTF-8
(source)

Problems printing .tiff files using ggsave

I am trying to print .tiff files and am getting an error here is an example:
ratings <- qplot(rating, data=movies, geom="histogram")
qplot(length, data=movies, geom="histogram")
ggsave(file="length-hist.tiff")
This code produces this error:
Saving 7 x 7 in image
Error in grDevices::tiff(..., width = width, height = height, res = dpi, :
argument "antialias" is missing, with no default
What am I doing wrong? I am using R version 2.15.0 for Mac OS X Leopard and ggplot 0.9.0
With ggplot2 0.9.1 and R version 2.14.1 on Linux, your code works and I can't reproduce this problem. Maybe you should try updating ggplot2?

Resources