rgl.postscript: file saved without varying text sizes - r

From #DWin and #Ben Bolker, we can change the scatter3d function in R to plot "prettier" (http://stackoverflow.com/questions/8204972/carscatter3d-in-r-labeling-axis-better), however, saving the plot is a trickier. rgl.snapshot saves the image as a png but to save a high resolution image (PDF) rgl.postscript must be used. Using rgl.postscript will not save the image with font/text size/axis sizes as specified (I edited the scatter3d function to increase text/axis sizes). rgl.snapshot works as it should so why doesn't rgl.postscript? Does anyone know an alternative saving method or is there a way to save the plot with larger text/axis etc?

A simple example works for me with the a more recent version of rgl than the CRAN one (CRAN has 0.92.798, r-forge now has 0.92.836, this is with 0.92.829). It looks like versions are numbered by SVN revision, so this is one version after the update mentioned in the comments above ...
library(rgl)
set.seed(1001)
n <- 20
text3d(runif(n),runif(n),runif(n),LETTERS[1:n],cex=seq(0.5,5,length=n))
rgl.postscript(file="tmp.ps")
However, a big warning is that the resulting PS, PDF, files etc. are a bit wonky. The bounding boxes are a little odd, although I could text-edit that manually. ps2pdf and ps2png mangled it .. epstopdf seems to have worked (these are all tools that are available on Linux boxes, don't know about for other OS). In principle rgl.postscript() allows you to export as PDF, but it might be weird PDF ... StackOverflow doesn't recognize the file as being in a valid upload format.
R Under development (unstable) (2012-01-01 r58032)
Platform: i686-pc-linux-gnu (32-bit)
[snip]
other attached packages:
[1] rgl_0.92.829

Related

Rmarkdown fails to render inline plots when opened within an R project on GoogleDrive

I have an R project held onto a Google Drive. I access both the R project and associated markdowns using the Google Drive desktop app. I recently updated my macOS to Monterey 12.2.1 and since then, I haven't been able to render plots inline within a markdown. I get the following error message when trying to print any plot:
Error in dev.off() :
QuartzBitmap_Output - unable to open file '/Volumes/GoogleDrive/Shared drives/.../.Rproj.user/shared/notebooks/-.../1/s/cqgw7b5dagxzw_t/_rs_chunk_plot_001.png'
This seems to be specific when opening a markdown, within an R project, onto a Google Drive. I have tried having a project on my local machine and opening the same markdown, plots display inline fine. I have tried opening the markdown outside of a project, again, can display plots inline fine. The plots also display in the viewer pane fine regardless and knitting is also not an issue.
The only clue I have is that when I go within the .Rproj.user directory, I can find a folder with the naming 'cqgw7b5dagxzw' (see path above), but it is missing the '_t'. Not sure what that could mean though.
Since updating the OS I have also reinstalled XQuartz.
I can still get to the plots, so it's not a HUGE issue, but the inline display feature is rather handy to make quick modifications to my visualisations.
Below are some session info.
Thanks!!!
PS: Plot twist! I can display plots inline with ggplotly?!?!
Workaround
I found this workaround which displays the plots in the viewer pane instead. It is definitely an improvement, but displaying plots inline allows you to get an idea of the proportions of the plot you will eventually knit.
> sessionInfo()
R version 4.1.2 (2021-11-01)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Monterey 12.2.1
Matrix products: default
LAPACK: /Library/Frameworks/R.framework/Versions/4.1/Resources/lib/libRlapack.dylib
locale:
[1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8
I found an issue someone logged on Rstudio github relates to this, linked here.
It seems you're right about the niche scenario of Rmarkdown + R Project + Google Drive + Inline plotting.
Someone in the comments suggested going to Preferences>General>Graphics and changing the back end option to Cairo instead of Quartz. Tried that on my end and seems to work when I tried a basic histogram with GGplot2.
Not sure if using Cairo makes anything else worse though.
Using MacOS Monteray (12.3.1) if that helps.

Getting anti-aliased plots with R on Ubuntu

I upgraded my system and reinstalled R, and now my standard X-11 plots are not anti-aliased -- they look jagged and the font looks bad.
I seem to recall a problem like this in the past but don't remember what I did about it.
Some other info:
qplot also comes out non-anti-aliased
plotting to a png device produces non-anti-aliased output as well
plotting to a pdf device, however, produces nice looking anti-aliased output
Another thing: I've been running this version of R/Ubuntu for a while now, a couple months or so. I don't know if this plotting problem started immediately with the new R install, or if I did something after that to break it. I don't remember noticing the lack anti-aliasing before, but I may not have been paying attention or doing a lot of plotting.
Anyone know what the fix is? Currently I am running R 3.2.1, compiled from the source, with Ubuntu 14.04.3 LTS.
A few more things. Following the discussion here I tried installing Cairo, but it failed. Also, I've been able to get non-anti-aliased plots in R/linux without installing Cairo in the past, and I'd rather not install extra things if not necessary.
Here are my X11.options():
$display
[1] ""
$width
[1] NA
$height
[1] NA
$pointsize
[1] 12
$bg
[1] "transparent"
$canvas
[1] "white"
$gamma
[1] 1
$colortype
[1] "true"
$maxcubesize
[1] 256
$fonts
[1] "-adobe-helvetica-%s-%s-*-*-%d-*-*-*-*-*-*-*"
[2] "-adobe-symbol-medium-r-*-*-%d-*-*-*-*-*-*-*"
$family
[1] "sans"
$xpos
[1] NA
$ypos
[1] NA
$title
[1] ""
$type
[1] "Xlib"
$antialias
[1] "default"
I'm running R 3.4.0 and I get anti-aliased lines, "points", and plot axes by default for X11() and png() devices.
However, there are certain "Microsoft fonts" packages which needs to be installed on my system in order to get anti-aliased text. I can't speak for Ubuntu, but on Arch Linux the package names were "ttf-ms-fonts" and "fontconfig-ttf-ms-fonts", both in AUR. A good Google search should turn up similar packages for your own system.
Here is are some plots produced by the png() device with and without "ttf-ms-fonts" installed.
Without "ttf-ms-fonts":
With "ttf-ms-fonts":
I hope it is possible to see that the lines and circles in both plots are anti-aliased, but only the second plot has anti-aliased text.
Here is the code I used to produce the above plots:
set.seed(1);
brownian=cumsum(runif(1e3,min=-1));
png("brownian-no-msfonts.png",height=400);
par(cex=1.3);
plot(brownian,ylim=c(-10,15),
ylab="Position",xlab="Time",main="Brownian Motion");
lines(brownian+7);
dev.off()
I've confirmed that I need both "ttf-ms-fonts" and "fontconfig-ttf-ms-fonts" (the latter I think configures certain fonts to be used by default) in order to get the anti-aliased text in R, although only the first package is needed to e.g. get anti-aliased text in Firefox.
However, I've been playing with the "knitr" package and I noticed that if I compile my documents using "render" from the "rmarkdown" package, then it can produce anti-aliased plots with or without the "ttf-ms-fonts" package installed. I haven't figured out how it does this. I know that it runs Pandoc which produces HTML with embedded fonts, but I'm not sure if the "rmarkdown" package itself includes fonts, or if it just has a better idea of where to find good ones on my system.
I feel superficial for spending time on this, but whatever.

R effects plot displays OK on screen but generated pdf contains no pages

I am using the effects package in R to derive (and plot) the effects of a complicated linear model.
When I use allEffects(linearModel) I can see the results on screen and save it to a pdf file as usual. Since the model has many terms, the output is not useful as it stands.
Therefore I use effects(someTerm, linearModel) to focus on the terms of interest and the results on screen are what I need. However, when saving it to a pdf file, the file contains no useful output (though it does take up 3.5Kb of space). There is no error message from R at the console.
To ease understanding, I created a simple data set and a script for generating the effects plots, in the same way that I tried with the "real" model.
factorData.csv
A,B,C,y
a1,b1,c1,3
a1,b2,c1,4
a2,b1,c1,5
a2,b2,c1,6
a1,b1,c1,2
a1,b1,c2,3.5
a1,b2,c2,4
a2,b1,c2,5.1
a2,b2,c2,6.2
plotEffect.r
require(effects)
dataFile <- '/tmp/factorData.csv'
effectABfile <- '/tmp/effect_AB.pdf'
effectABCfile <- '/tmp/effect_ABC.pdf'
allEffectFile <- '/tmp/lm_eff.pdf'
df <- read.csv(file=dataFile,header=TRUE,sep=',')
linearModel <- lm(y~A*B*C,data=df)
lm_eff <- allEffects(linearModel)
pdf(file=effectABfile)
plot(effect('A:B',linearModel))
dev.off()
pdf(file=allEffectFile)
plot(lm_eff)
dev.off()
pdf(file=effectABCfile)
plot(Effect(c('A','B','C'),linearModel))
dev.off()
As you can see, I tried allEffects, effect and Effect; allEffects is the only one that works for me. Please note that the script assumes that the data is placed in /tmp/factorData.csv - you might need to change the path of course. I also randomised the order in which the plots are generated, with no effect.
I had a look elsewhere on stackoverflow and saving plots to pdfs fails was the closest but the advice there (to issue dev.off() after each plot to 'close' the pdf file) is something I do already, as seen in plotEffect.r.
I tried this script on 2 machines, each running Lubuntu 14.04.1 64-bit with R version 3.0.2 and the latest effects package installed within R using install.packages. The results were the same.
I would be very grateful for advice on how to fix the problem of saving (instances of) this plot type to a pdf.
Fix/workaround
As suggested by #Roland in the comments below, if you wish to save grid plots (such as the output from the effects plots in this instance) into pdf files, it is better/more reliable to generate the plots separately/manually (rather than in a script). It does not appear to be (as much of) an issue for base graphics or even ggplot2 graphics, where I for one have never encountered this problem/needed this workaround in the past. Thanks to #Roland for suggesting this fix!
#Roland also added that Sys.sleep() might help in scripts. Although it did not do so in my case, I discovered that it was possible to paste several such plotting commands and R would run them as a batch, saving the plots to pdf correctly. Therefore, I believe it should be possible to recover much of the benefits of running the script by taking these steps:
Use R to create the text representation of the pdf(), plot() and dev.off() triad of commands
The main script outputs this plotting command text (specific to each instance of a plot) to a file
Open the plotting command text in a text editor
Copy the entire contents of the commands file and paste it into the R console
Optionally, you may wish to use the command line in Step 3 and 4 - How can I load a file's contents into the clipboard? has useful advice.
This two stage procedure is a reasonable workaround, but arguably there should be no need for it.

Why doesn't savePlot("file.pdf", type="pdf") work by default?

Does anyone know why savePlot can't save to pdf in linux by default?
> savePlot("rv-3.pdf", type="pdf")
Error in match.arg(type) :
'arg' should be one of “png”, “jpeg”, “tiff”, “bmp”
lizard:~images$ R --version
R version 2.14.1 (2011-12-22)
...
?savePlot is pretty clear about this:
This works by copying the image surface to a file.
Hence you start with a raster representation and therefore can only go to a raster representation. It would be somewhat perverse to pipe a raster version of the plot in a PDF, which is a vector format (yes I know you can have rasters inside PDFs).
The functionality is limited to cario-based X11 devices and the documentation refers to copying the "on screen" representation hence the restrictions.
I suppose the other Answer to your question is: that functionality has not been implemented yet.
dev.copy2pdf does what you want:
plot(1:10)
dev.copy2pdf(file="~/test.pdf")
From reading the help files, I take it this will effectively replot your figure as a vector image in the file, which will usually be preferable to exporting your vector image into a raster format, as savePlot appears to do.
Try this:
pdf(file="rv-3.pdf")
plot(x,y)
dev.off()
you can also change the size by by adding height= or width= to the pdf function.

How do I resuscitate a ggplot that was saved to disk inside a list?

I created several hundred plots using ggplot and saved them all to a list. I saved the list to disk using:
save(list_of_plots,file="list_of_plots.rdata")
Now I want to display those plots and save some using ggsave. However, calling a list item just shows me components of the plot.
> names(plots00_t2[[1]])
[1] "data" "layers" "scales" "mapping" "options"
[6] "coordinates" "facet" "plot_env"
Update: My dumb mistake was not loading ggplot2 when I reopened these files. However, when attempting to display these plots, I get:
Error in get("make_aesthetics", env = x, inherits = TRUE)(x, ...) :
could not find function "calc_aesthetics"
So short of recreating these plots, how would I fix this?
the last version using the internal function calc_aesthetics was ggplot2 version 0.8.2. If possible, check which version of ggplot2 is used for creating the plots and load that one. Otherwise, try with version 0.8.2 or earlier.
Download the file from http://cran.r-project.org/src/contrib/Archive/ggplot2/ and save it somewhere on your computer (I used G:/Temp here). Then use this code to install and call the specific version :
install.packages(
"G:Temp/ggplot2_0.8.2.tar.gz",
lib="G:/Templibs",
repos=NULL,
type="source")
library(ggplot2,lib.loc="G:/Templibs")
After this, you should be able to print the graphs. See also this question and the help files of ?library and ?install.packages
It might happen that the code of ggplot2 was changed in meanwhile and "calc_aesthetics" is no longer available. In this case you should install an older version of ggplot2, to recover your work.
Though, the above is quite unlikely. The problem seems to stem from the fact that some parts of your plots have not been saved properly.
You should produce the traceback(), it might cast some light on the problem.

Resources