by Andrie de Vries
A few weeks ago I wrote about the Jupyter notebooks project and the R kernel. In the comments, I was asked how to resize the plots in a Jupyter notebook.
The answer is that the IRKnernel project contains not only the IRKernel package itself, but also the repr package. The repr package provides "String and byte representations for all kinds of R objects".
I had to dig a little to uncover the meaning behind this rather cryptic description. What I found was that the package provides wrappers around all kinds of R objects, including plots. Now, anybody who has used R has at some point asked the question "How to save a plot as image on the disk?". The answer is well-known: use a device like png() to capture the output and save the plot to a png file on disk.
Now, the IRKernel uses exactly this technique, and the repr package gives you control over the device.
Very simply, you need to modify two repr setting, using a call to options(). The default repr settings are for plots to be 7 inches wide and 7 inches high.
To set the plot width and height to something else, e.g. 4 inches wide and 3 inches high, use:
options(repr.plot.width=4, repr.plot.height=3)
Example in Jupyter
Here is an example of setting the plot width to different sizes in the same notebook. In the first plot I set the width to 4 inches, and in the second I set the width to 8 inches. In both cases the height is the same: 3 inches rather than the default 7 inches.
The code
Here is the full code listing:
Just FYI - that isn't at all what repr does.
When you embed R inside another language or whatever, you need a way to talk to R and get results back. Usually the way you do that is by opening a network socket (on the same machine) from R to whatever it's talking to. That's how Jupyter works too. So you tell R to do things by writing commands to the socket and then sending the "enter" code (im simpifying). But how do you get the result back?
If the result from R is just some text it's easy you can just read from the socket.
If its anything else, it has to be converted into a byte representation so it can be sent through the socket and decoded.
That's what repr does. It's not a graphics device. It's a way of encoding non-textual R data in a form that can be transmitted through a socket and decoded.
Posted by: Amos | October 10, 2015 at 08:47