Copy R plot to clipboard with custom size - r

Is there a way to get R / RStudio to copy a plot to the clipboard with a custom size?
RStudio has this function, but you have to define the size everytime and there is some extra clicking which I am sure is avoidable.
I tried my best with saving as jpeg or else with file="clipboard" and then - after plotting - dev.off(). No error messages, but also nothing in the clipboard.
Here is an example:
data(mtcars)
jpeg(file = "clipboard",width = 800, height = 600, units = "px", pointsize = 12,
quality = 100,
bg = "white", res = NA, family = "", restoreConsole = T)
hist(mtcars$mpg)
dev.off()
Any ideas on how this can be achieved?

The best way would be to be able to control the size in Rstudio, but as you have found out yourself from the Rstudio-website, Rstudio doesn't support that. The following code saves your plot to wmf. There is also a workaround to a save to bitmap, which involves some clicking, but at least you don't have to specify the size any more:
data(mtcars)
windows(800, 600, pointsize = 12) #opens a separate window with the size you want
hist(mtcars$mpg) #draw to this (active) window
savePlot("clipboard", type="wmf") #saves plot to WMF
Unfortunately, it seems to be impossible to save to jpg format to the clipboard. You can copy it to a bitmap by going to this window, click CTRL-C and the graph is on the clipboard as bitmap with 800:600.
EDIT:
The windows command only works on Windows.
For Mac, it should be replaced by: quartz(width=8,height=6,pointsize=12,dpi=100) (width/height in inches!)
For linux try x11(width=8,height=6,pointsize=12,dpi=100) (untested).

I know this is an old post, but recently looking to do the same I came across this Gist which worked well:
https://gist.github.com/dpashouwer/4223903d3ed5783158b7e63992155649
library(tidyverse)
gg_to_clipboard <- function(plot = last_plot(), width = 1000, height = 600, pointsize = 40){
win.graph(width = width, height = height, pointsize = pointsize)
plot %>% print()
savePlot("clipboard", type = "wmf")
dev.off()
}
ggplot(data = mtcars, aes(x = mpg)) + geom_histogram()
gg_to_clipboard()
Making the function makes it very simple.

With Windows and RStudio, you click Export, click Copy Plot to Clipboard, and Copy Plot.
Then, paste into Word or PowerPoint or whatever.
No need to change sizes unless you want to.
This is not command line, but hardly seems onerous.

Related

How to reduce the size of a plot in Jupyter Notebook?

I'm trying out R with Jupyter Notebook and for some reason the plots are huge. How can I reduce the size of the plot? I tried changing the plot_scale option via: options(jupyter.plot_scale=.25) but nothing happened. I've tried other numbers besides .25, but it has no effect.
I also tried
options(repr.plot.width = 1, repr.plot.height = 0.75, repr.plot.res = 100)
as well as options(jupyter.plot_mimetypes = c("text/plain", "image/png" )), but both gave the following error:
Error in value[[3L]](cond): invalid graphics state
Traceback:
plot without title
Ideally, I'm looking for a global solution (i.e. one that changes the default plot size, rather than having to individually scale each plot). Any suggestions?
Try the following:
options(repr.plot.width = 5, repr.plot.height = 5)
x = seq(0,2*pi, length = 50)
y = sin(x)
plot(x,y)
Then compare it to the output from the following in another cell or after restarting the kernel:
options(repr.plot.width = 15, repr.plot.height = 15)
x = seq(0,2*pi, length = 50)
y = sin(x)
plot(x,y)
You should see a difference.
If you set the width and height to you get plot without title error.
Should be good with 2 or above because ~1.8 or above worked in my tests.
Based on this post.
simply run
dev.off()
then rerun your code for plotting.
Alternativly use ggplot. If the error persists you should still try dev.off() and rerun your code.
Otherwise you still have the option to restart your notebook or reinstall R.

ggplot2: CairoSVG changes point size

I build scatterplots using ggplot2 in R. I then want to save them as svg files with Cairo::CairoSVG. It seems to work fine except for the point size, which is enlarged in the resulting .svg file.
Here comes some example code:
library (ggplot2)
my_plot <- ggplot(mpg, aes(cty, hwy)) +
geom_point(size = 0.5)
x11 (width = 6, height = 6)
my_plot
Cairo::CairoSVG (file = "my_path",
width = 6, height = 6)
print (my_plot)
dev.off()
And this is what I get: on the right hand, the plot printed in R and on the left side the saved .svg-file opened in Inkscape. It looks fine except for the point size, which is a pity. Are there any ideas on how to get the right point-size? I tried different point sizes and also shapes, with similarly unmatched results.
Note that I seek to stick with Cairo::CairoSVG, beacuse in the final plots I wish to use custom fonts which are printed nicely with Cairo::CairoSVG. Any help is appreciated.
EDIT: I am working on a Windows machine.
Preliminary remark: when you pass width = 6, height = 6 in the Cairo::CairoSVG() parameters, you provide potentially different parameters (resolution and display) from the ones used in the RStudio plot panel.
To get the exact same image than the one rendered in the panel as well as using Cairo, you can use this alternative (dev.size('px') returns the dimensions of the current plot panel):
library (ggplot2)
my_plot <- ggplot(mpg, aes(cty, hwy)) +
geom_point(size = 0.5)
my_plot
mirror <- recordPlot()
png(filename = "mypath",
width = dev.size('px')[1]/96,
height = dev.size('px')[2]/96,
res = 96, # base RStudio resolution
units = "in",
type = "cairo") # calls CairoSVG
replayPlot(mirror)
dev.off()
(Note : I prefer the use of png() rather than ggsave() because it will save the entire last plot. I have observed that ggsave() would save only the last facet of a grid, for example)

Output Stem and Leaf Plot to Image

I'm trying to output a Stem and Leaf plot in R as an image. I'm not sure if there's a nice library which can accomplish this but below is some of the code I've tried.
jpeg(filename="stem.jpeg",width=480,height=480, units="px",pointsize=12)
plot.new()
tmp <- capture.output(stem(men, scale = 1, width = 40))
text( 0,1, paste(tmp, collapse='\n'), adj=c(0,1), family='mono' )
dev.off()
This above code resulted in the data being saved, but it looks very blurry and the plot gets cut off pretty badly. When adding a histogram to an image, R seems to do a good job to scale everything to fit in the size of the image.
jpeg(filename="stem.jpeg",width=480,height=480,
units="px",pointsize=12)
stem(men, scale = 1, width = 40)
dev.off()
This created the image but had no content within it.
Any ideas? Thanks!
That's because stem and leaf plots produce text not images. You can save the text as follows using the sink command: http://stat.ethz.ch/R-manual/R-devel/library/base/html/sink.html
sink(file=“Stem.txt”)
stem(men, scale = 1, width = 40)
sink(file=NULL)
unlink("stem.txt")
To export a stemplot as graphics, you can use a vector graphics format, such
as .eps, .pdf, or .emf. For example, a windows metafile:
win.metafile("stem.wmf", pointsize = 10)
plot.new()
tmp <- capture.output(stem(mtcars$mpg))
text(0,1,paste(tmp,collapse='\n'),family='mono',adj=c(0,1))
dev.off()

Can't increase title and x/y label size in a ggplot2 plot saved as a PNG file, but it works fine on screen

I am hitting a small, but not insignificant brick wall with this oft asked and answered question.
I am using Rstudio 0.97.336 and R 3.0.0 on Linux. I am making a (much more complex) graph to put in a paper. The default size of the title and x/y labels are too small to be easily read. However the obvious method for fixing this using the theme function on element_text
theme(axis.title.y = element_text(size = rel(1.8))
does not work, if I save the image as a PNG file. It does however work, exactly as expected, when I'm looking at the images in RStudio. The code below reproduces my problem exactly.
##Libraries
library(ggplot2)
set.seed(15612)
##Generate data
Year <- seq(2000,2010)
data <- -2*(Year - 2005) + 10 + runif(11,min=-3,max=3)
Title <- "Title for our graph"
xlab <- "X label"
ylab <- "Y label"
df <- data.frame(Year,data)
##Plot
##First image with small title, xlab, ylab
image1 <- ggplot(df) +
geom_line(aes(x=Year,y=data)) +
theme_bw() +
labs(title=Title,xlab=xlab,ylab=ylab)+
theme(panel.border = element_rect(fill = NA, colour="grey70"))
image1
ggsave("Image1.png",image1, width=15,height=10,units='cm')
##Second image with larger title, xlab, ylab
image2 <- image1 +
theme(axis.title.y = element_text(size = rel(1.8), angle = 90)) +
theme(axis.title.x = element_text(size = rel(1.8), angle = 00)) +
theme(plot.title = element_text(size = rel(2.0), angle = 00))
image2
ggsave("Image2.png",image2, width=15,height=10,units='cm')
dev.off()
image1
image2
These images look exactly as expected on the screen in Rstudio. Image 1 has small font sizes for the title, etc. and image 2 has larger more legible font sizes. Unfortunately, when saved as png files, they are identical, and both have small fonts for the title, x and y labels.
I can't (yet) post images, so if you look at these two urls, you will see the problem.
Image 1 - small title font
Image 2 - still a small title font, but ought to be bigger
I cannot see where I am going astray. I know there are issues (or features!) with lazy evaluation in ggplot2, but I don't see where this is biting me. I would be very grateful for any help with this,
Regards,
Anthony Staines
Using RStudio, I am also seeing some strange behaviour (but I need to look into the docs a bit more to decide if it is not as we should expect), however, I think you can get the output you expect by calling ggsave, letting it use it's default plot = last.plot(), then running the plot then calling dev.off() between the plots. i.e.
The workaround
ggsave("~/Image1.png", width=15,height=10,units='cm')
image1
dev.off()
ggsave("~/Image2.png", width=15,height=10,units='cm')
image2
dev.off()
A reproducible example of this behaviour
If we try the following example in RStudio I can get the same behaviour as the OP. Running the first code block below in RGui 3.0.0 gives us what we expect, i.e. the 3rd picture. However this is what happens in RStudio:
## Make plot and save
qp <- qplot(1:5, rnorm(5), size = I(2) )
qp
ggsave("~/Image1.png", width=15,height=10,units='cm')
## Make new plot
qp <- qplot(1:10, rnorm(10), size = I(5) )
qp
ggsave("~/Image2.png", width=15,height=10,units='cm')
At this point if we try to open the files that are saved we get:
Then we just run dev.off()
## Without calling dev.off() plot 1 is still open and displays nothing
## Plot two is accessible from the filesystem
## Calling dev.off() we then get both plots, but BOTH plots
## use settings from plot 2
dev.off()
And we get:
Now if we try and save the plots by calling ggsave then printing the plots to screen and then calling dev.off() it works as expected:
## Now we try calling dev.off() between plots:
qp <- qplot(1:5, rnorm(5), size = I(2) )
ggsave("~/Image1.png", width=15,height=10,units='cm')
qp
dev.off()
## Make new plot
qp <- qplot(1:10, rnorm(10), size = I(5))
ggsave("~/Image2.png", width=15,height=10,units='cm')
qp
dev.off()
We then get:

How do I prevent Rplots.pdf from being generated?

I am working with some R code that generates a number of images as png files; however, a Rplots.pdf file keeps on being generated in the working directory, is there a way to prevent this from happening?
library(Cairo)
CairoPNG(file = "graphs.png")
nf <- layout(matrix(c(1:8), 2, 4, byrow=T), c(1, 1), c(1, 1, 1, 1), TRUE)
for (k in 1:num.k) {
plotMatrix(connect.matrix.ordered[k,,], log = F, main = paste("k=", k.vector[k]), sub = paste("Cophenetic coef.=", rho[k]), ylab = "samples", xlab ="samples")
}
y.range <- c(1 - 2*(1 - min(rho)), 1)
plot(k.vector, rho, main ="Cophenetic Coefficient", xlim=c(k.init, k.final), ylim=y.range, xlab = "k", ylab="Cophenetic correlation", type = "n")
lines(k.vector, rho, type = "l", col = "black")
points(k.vector, rho, pch=22, type = "p", cex = 1.25, bg = "black", col = "black")
dev.off()
I know this is a very old post and surely the OP has solved this. But I encountered this similar situation while working with plotly. Converting a ggplot output into a plotly output generated the similar error of not being able to open file 'Rplots.pdf'.
I solved it by simply including :
pdf(NULL)
I'm not sure of the reason for the error, have not been able to figure that out, but this small line helped removing the error and displaying my plots as I would expect in plotly and ggplot combinations.
I wonder if you have another command that opens a device before or after the code snippet you've given us. When you're all done run dev.cur() to see if there was a device left open. If not, it should return the null device.
Here are ways you can recreate getting a Rplots.pdf or a Rplot001.png; the layout and par commands open a device if one isn't open, and since no filename has been given, it uses the default filename.
options(device="pdf")
layout(1:4)
dev.off()
options(device="png")
par()
dev.off()
Maybe seeing that happen here will give you a clue as to what's happening with your code.
Here is the source code for CairoPNG:
function (filename = "Rplot%03d.png", width = 480, height = 480,
pointsize = 12, bg = "white", res = NA, ...)
{
Cairo(width, height, type = "png", file = filename, pointsize = pointsize,
bg = bg, ...)
}
This tells you that CairoPNG takes filename=... as a parameter, and passes this to Cairo as the file parameter.
I can see how this can lead to confusion, but the point is that your call to CairoPNG should be:
CairoPNG(filename="graphs.png")
See if that works...
I had a similar problem recently after upgrading to R-3.0.3 (yes we're a little behind!). It turns out that palette("default") opens a device now, though it didn't used to.

Resources