Customize R base plot fonts (macOS) - r

I have followed this blog to customize base R plot font on macOS (using quartzFonts() in .Rprofile), with success to a certain degree. My problem with this approach is, defining a new font family has to be put in a function such as .define.fonts() and upon enter a R session (I use Rstudio), I have to manually invoke the following from the console:
.define.fonts()
par(family='new_font_family')
I can't simply define new font family by calling quartzFonts() in .Rprofile. My guess is that this command is not available until graphic device has been initialized. Is there anyway to automate this?

Related

How to successfully use {pkgdown} when `svglite` graphics device is used

To address an issue in my R package, I wish to try out an svglite graphics device for rendering ggplot plots:
knitr::opts_chunk$set(dev = "svglite")
But, if I do so, the {pkgdown} workflow fails (failure log) with the warning messages:
1: 'mode(bg)' differs between new and previous
==> NOT changing 'bg'
2: 'mode(bg)' differs between new and previous
==> NOT changing 'bg'
If I understand correctly, these warning messages are coming from par(), which is complaining about not being able to change the background colour (bg). But I am not explicitly calling par(), nor am I changing the background colour for the plot in question.
So I wish to know why exactly am I getting this error and how to resolve it?
I think you have a font mismatch issue.
Download necessary font files, make sure in the source package and register the necessary them with package 'systemfonts' and function systemfonts::register_font(). This is the right thing to do for packages 'svglite', 'ragg' (and 'ggiraph').
It looks like you have "greek" variant on your machine, but not on the GA remote machine.
In your package, I would add a new 'Suggests' entry with gdtools that can help you download the font and register it seamlessly (disclaimer, I am the author, but I really think it makes things easier). And in the vignette, before any graph production with 'ragg' or 'svglite', add the following code:
gdtools::register_gfont(family = "Open Sans", subset = c("latin", "latin-ext", "greek"))

How do I conveniently resize a ggplot2 plot on R+VSC?

I'm in the process of learning R (I'm still a newcomer on SO as well). Being very used to using Visual Studio Code, I decided to choose that over RStudio or RStudio Cloud.
One of the best parts of RStudio was that plots automatically resized/reshaped themselves if we resized the right pane. Moreover, in the tutorials I watched, plots involving map data automatically rendered in the correct aspect ratio (as seen on physical maps).
I replicated the code to make my own plot of the world map. Unfortunately it rendered as a square shape, and resizing the right pane does not affect its shape:
enter image description here
Am I missing any commonly used VSC extensions which can make plots resizeable like in RStudio? (I've installed only the most downloaded extension for R, by Yuki Ueda)
If not, can I modify my code to specify the exact dimensions I need the plot to have?
Thanks in advance!
You can add robust plot viewing options for R in VSCode by installing the httpgd package and then amending your JSON settings.
First, install httpgd via the R console:
install.packages("httpgd")
Then, open your JSON settings in VSCode by opening the Command Palette (either via Ctrl+Shift+P or via View > Command Palette) and then searching for "Preferences: Open Settings (JSON)", where you'll insert the following:
"r.plot.useHttpgd": true
You can add a comma after 'true' if needed (i.e. if there are other lines below that in your JSON settings).
Following that, restart VSCode and launch the R terminal inside it, and plot something using either ggplot2 or base R graphics:
plot(mtcars$mgp, mtcars$wt)
A plot viewer should then pop up in VSCode. You can either manually resize the window there, zoom in or out, or, my preference (particularly if I'm cycling through a series of already-plotted graphs), open it in an external browser where it'll automatically adjust to however you resize the window. After that, you can save or copy the image as needed.
You can specify the dimensions when you save the file. I usually use (approximately) the golden ratio:
ggsave("./earth.png", width = 16, height = 10)
The ggsave function reference explains how you can change units - options are c("in", "cm", "mm", "px").

Disable GUI, graphics devices in R

Is there an easy way to turn of all GUI elements in R and run it solely from the command line on OSX?
I'm trying to replicate the behavior of a remote linux terminal on my OSX machine. Thus plot() should just save a file and things like CRAN mirror selection should be text, not a Tk interface. I'm having trouble finding where to set this behavior.
I had this exact question and wanted a way to do it without changing my existing code. I usually run with graphics support but sometimes I'll run a script on the server for a larger dataset and then I just want the plots to be output somewhere automatically.
In Dirk's answer Ian Fellows gives the simple solution. On the command line in R type:
options(device=pdf)
And then any plots will be written to the current directly to an Rplots.pdf file.
If you want the files to not be plotted at all then use
options(device=NULL)
For the plots you can just direct the output to a file using the pdf() command (or png(), jpeg()...).
I don't own an OS X box, but did you try to unset the X11 environment variable DISPLAY:
DISPLAY="" R --vanilla
When I do that on Linux and query R for capabilties(), x11 comes up as FALSE as desired.
I don't run OSX but you could attempt to run R from the Terminal application, rather than the Mac OSX launcher, and see whether that runs as you need.
As Matti writes, you can send output to files using the following commands; but I don't know if that's really the substance of your question.
png("pngfile.png")
plot(foo)
title(main="bar")
dev.off()
So instead of the quartz graphical object, your output goes to the file.
Similarly, you can output what would normally appear in the terminal to a file.
sink("foo.file")

PgDn and PgUp Keys in R Graphics Viewer

I've never been able to figure out how to get the PgDn/PgUp keys to work in the R Graphics Viewer.
Even the demo() programs don't seem to support it.
Anyone able to point me to some code that shows how this can be implemented?
Dirk is right.
Another thing to look at are the following functions:
x <- recordPlot()
replayPlot(x)
From the R for Windows FAQ:
The graphics has a history mechanism. As README.R-2.9.2 says:
The History menu allows the recording of plots. When plots have been recorded they can be reviewed by and , saved and replaced. Recording can be turned on automatically (the Recording item on the list) or individual plots can be added (Add or the key). The whole plot history can be saved to or retrieved from an R variable in the global environment. The format of recorded plots may change between R versions. Recorded plots should not be used as a permanent storage format for R plots.
There is only one graphics history shared by all the windows devices.
The R console and graphics windows have configuration files stored in the RHOME\etc directory called Rconsole and Rdevga; you can keep personal copies in your HOME directory. They contain comments which should suffice for you to edit them to your preferences. For more details see ?Rconsole. There is a GUI preferences editor invoked from the Edit menu which can be used to edit the file Rconsole.
As I recall you have to turn 'recording' or 'History' on. This is platform-specific and I am not near a Windows machine.
On a mac, one can use the command key with the back arrow (and forward arrow) to cycle through plots.
Make sure you've plotted at least two plots to the same quartz device, then with the plotting window in focus, hit ⌘ ← to see the previous plot.

How to source file.R without output

Is it possible to source a file without printing all the charts etc (already tried with echo=F)?
In my case I call the png("filename%03d.png") device early in the script. It is not to big a hassle to comment this out - but all the charts do take a lot of time to render. (the specific file I am working with now uses base-graphics - but mostly I'll be using ggplot2 - which makes the issue somewhat more important (ggplot2 is excellent, but in the current implementation not the fastest))
Thanks
It's not a problem for ggplot2 or lattice graphics - you always have to explicitly print them when they are called in non-interactive settings (like from within a script).
Good practise for coding R means wrapping as much of your code as possible into functions. (See, e.g., Chapter 5 of the R Inferno, pdf.) If you place your plotting code inside a function, it need not be displayed when you source it. Compare the following.
File foo.r contains
plot(1:10)
When you call source('foo.r'), the plot is shown.
File bar.r contains
bar <- function() plot(1:20)
When you call source('bar.r'), the plot is not shown. You can display it at your convenience by typing bar() at the command prompt.
Perhaps this might be of some help...
"A package that provides a null graphics device; includes a vignette, "devNull", that documents how to create a new graphics device as an add on package. "
from http://developer.r-project.org/
It's not the best sounding solution, but If you might be running this script often like this, you could declare a boolean whether graphics are required (graphics_required=TRUE) and then enclose all your plot commands in if/then clauses based on your boolean, then just change the boolean to change the behaviour of the script

Resources