High resolution autoplot function in R studio - r

I get one good plot with autoplot function in R studio. If I click in zoom a get a expected picture of my plot. However i would like to export in high resolution. This was my last command.
autoplot(bed, layout = "karyogram", aes(color = score, fill = score), res = 1200)

Put tiff("figurename.tif", units="in", width=11, height=8.5, res=300) before start the comands. After, put dev.off() to write a plot as tiff format in your disk.

Related

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)

How can I re-scale a forest plot in RStudio?

I am trying to reproduce the plot from the example dataset in the robumeta package in R Studio. While the script works (as expected), I can only see a fraction of the graph. When I increase the size of the window, I get to see more but never the whole thing because apparently, my computer screen is too small and there is no option to scroll up or down. Is there a way to re-scale the forest plot or to print it to pdf (with several pages, if needed)?
Here's the code from package description file:
install.packages("robumeta")
library(robumeta)
data(oswald2013.ex1)
oswald_intercept <- robu(formula = effect.size ~ 1, data = oswald2013.ex1, studynum = Study, var.eff.size = var.eff.size, rho = 0.8, small = TRUE)
forest.robu(oswald_intercept, es.lab = "Crit.Cat", study.lab = "Study",
"Effect Size" = effect.size, # optional column
"Weight" = r.weights) # optional column
png(filename, height, width, pointsize)
#your plot code
dev.off()
in which you play around with the height, width, and pointsize parameters should allow you to save the graph to your desired view size. It won't save as a pdf, but rather a png, which should be ok if your goal is just to view the entire forest plot.

Save ggplot object as image in the environment as object/value

I have a ggplot object. Let's call it plot. I would like to convert it to png format, but I don't want to save it to a file on my local drive. I'm trying to work with that png object but I want to keep everything in the environment. Everything I've found, including ggsave, appears to force one to save the image as a file on the local drive first. I know image files can be stored as values, but I can't seem to get over the "save as" image and "import" image steps.
Here's some code for repoducibility:
library(tidyverse)
df <- as.data.frame(Titanic)
gg <- ggplot(data = df, aes(x = Survived, y = Freq))
plot <- gg + geom_bar(stat = "identity")
Now, I'd like to convert plot to a png to png without having to save it to a file. Something like:
png <- save.png(plot)
Thanks for the help!
It looks like the goal here would be to convert plot (the ggplot object) directly to a Magick image that you can operate on with functions in the magick package. Something like this:
mplot = image_graph(width=400, height=500)
plot
dev.off()
image_graph opens a graphics device that produces a Magick image and assigns it to mplot so that you'll have the object available in your environment. Then, when you type mplot in the console, you'll see the following:
format width height colorspace matte filesize density
1 PNG 400 500 sRGB TRUE 0 +72x+72
However, when I try to display the mplot image (type mplot in the console), I see the following:
even though the original plot looks like this:
I'm not sure what's going wrong, but hopefully someone with greater familiarity with magick will drop by and provide a solution.
I was faced with a similar issue and followed #eipi12 approach of using magick. The code bellow should work:
library(ggplot2)
library(magrittr)
ggsave_to_variable <- function(p, width = 10, height = 10, dpi = 300){
pixel_width = (width * dpi) / 2.54
pixel_height = (height * dpi) / 2.54
img <- magick::image_graph(pixel_width, pixel_height, res = dpi)
on.exit(utils::capture.output({
grDevices::dev.off()}))
plot(p)
return(img)
}
p <- data.frame(x = 1:100, y = 1:100) %>%
ggplot(aes(x = x, y = y)) +
geom_line()
my_img <- ggsave_to_variable(p)
my_img %>%
magick::image_write("my_img.png")

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:

Resources