How to save to png multiple plots created at one R script - r

I have few separate plots in one R script that I'd like to save to png files. I run the script at the terminal and out of the 4 plots, only the last one was created as png file.
How to fix it so it will create and save all 4 plots as png files?
library(data.table)
library("ggplot2")
setwd("C:\\Users\\Desktop\\R\\figure_1A-D")
final_df_older <- fread("C:\\Users\\Desktop\\R\\older.csv"),
select=c(3,4))
png("Figure 1a - older_samples.png", width = 500, height = 400)
figure_1_wo_new <- ggplot(data = final_df_older, aes(x=final_df_older$`quntity`, y=final_df_older$`count`))
dev.off()
list.files(pattern = "png")
getwd()
final_df_all <- fread("C:\\Users\\Desktop\\R\\all.csv"),
select=c(3,4))
png("Figure 1b - all)samples.png", width = 500, height = 400)
figure_1_all <- ggplot(data = final_df_all, aes(x=final_df_all$`quntity`, y=final_df_all$`count`))
dev.off()
list.files(pattern = "png")
getwd()
final_df_new <- fread("C:\\Users\\Desktop\\R\\new.csv"),
select=c(3,4))
png("Figure 1c - new_samples.png", width = 500, height = 400)
figure_1_new_only <- ggplot(data = final_df_new, aes(x=final_df_new$`quntity`, y=final_df_new$`count`))
dev.off()
list.files(pattern = "png")
getwd()
library("gridExtra")
library("grid")
png("Figure 1d - merged_plot.png", width = 1500, height = 500)
merged_plot <- grid.arrange(figure_1_wo_new, figure_1_all,figure_1_new_only, ncol=3,
top = textGrob("Merged plot",
gp=gpar(fontsize=30,font=3,cex=1,col="darksalmon"),vjust=0.4))
dev.off()
list.files(pattern = "png")
getwd()

Related

Multiple plots in one figure in a loop in R

I am trying to save 10 plots in PNG format, but it only shows me one plot. How can I fix the code below?
par(mfrow = c(3,4))
png(filename = "roc.png", width = 1200, height = 1200)
roc = list()
for(id in 1:10)
{
roc[[id]] = ModelCross[[id]]$roc
roc_ = ModelCross[[id]]$roc
coords_<- coords(roc_, best.method="closest.topleft") ## "youden", "closest.topleft"
par(pty = "s")
plot(roc_,col = "blue",print.thres="best", print.thres.best.method="closest.topleft")
print(paste0('roc',id))
}
dev.off()

displaying ggplot .png in RStudio viewer pane with correct dimensions

I'm writing a function to save a plot to the R temp directory, then display it in the viewer pane. (Based in part on the last paragraph of this question.) If I save the plot as an .svg, it saves and shows up in the viewer pane at just the right size, based on the current pane dimensions:
library(ggplot2)
library(grDevices)
plt <- ggplot(iris) +
geom_point(aes(Sepal.Width, Sepal.Length))
dev.size()
# 5.250000 2.927083
plt_path <- tempfile(fileext = ".svg")
ggsave(plt_path, plt)
# Saving 5.25 x 2.93 in image
viewer <- getOption("viewer")
viewer(plt_path)
If I save it as a .png, however, the displayed image is way too big. (Note that ggsave() still reports saving it to the correct size.)
plt_path <- tempfile(fileext = ".png")
ggsave(plt_path, plt)
# Saving 5.25 x 2.93 in image
viewer <- getOption("viewer")
viewer(plt_path)
The issue persists using type = "cairo", and even if I manually set the ggsave dimensions:
dims <- dev.size(units = "in")
plt_path <- tempfile(fileext = ".png")
ggsave(plt_path, plt, width = dims[[1]], height = dims[[2]], units = "in")
How can I save and display the .png image to match the viewer pane dimensions?
The resolution needs to match that of your device. Default dpi is 300 in ggsave, but monitors are typically 96 dpi:
dims <- dev.size(units = "in")
plt_path <- tempfile(fileext = ".png")
ggsave(plt_path, plt, width = dims[[1]], height = dims[[2]], units = "in",
dpi = 96)
viewer <- getOption("viewer")
viewer(plt_path)

saving multiple ggplots WITHOUT for loop

using ggsave and a for loop, I know I can save multiple ggplots onto an excel spreadsheet
For example from Save multiple ggplots using a for loop :
for (i in uniq_species) {
temp_plot = ggplot(data= subset(iris, Species == i)) +
geom_point(size=3, aes(x=Petal.Length, y=Petal.Width )) + ggtitle(i)
ggsave(temp_plot, file=paste0("plot_", i,".png"), width = 14, height = 10, units = "cm")
}
But would I would like to do is avoid the loop, as I have a list of plots.
Using lapply I have ( I presume) a list of plots:
y.plot = lapply(1:nrow(df), function(row)
{
...
}
my question is, is there a way to take y.plot from above, and shove all of the graphs in there onto one excel spreadsheet, without a loop?
something like: ggsave(pic_path,plot=y.plot,width = 20,height=20,units='cm')
but this doesn't work
Perhaps, you are looking for this
dfs <- c("cars","pressure","mtcars")
my_plots <- list()
y.plot <- list()
en <- length(dfs)
y.plot <- lapply(1:en, function(i){
df <- get(dfs[i])
varname <- colnames(df)
x=df[,1]
y=df[,2]
my_plots[[i]] <- ggplot(data=df,aes(x=x,y=y)) + geom_point() +
labs(x=varname[1], y=varname[2]) + theme_bw()
})
myplots <- do.call(grid.arrange, c(y.plot, ncol = en))
location <- "C:\\_My Work\\RStuff\\GWS\\"
ggsave(plot=myplots, file=paste0(location,"myplots.png"), width = 14, height = 10, units = "cm")
Please note that ggsave currently recognises the extensions eps/ps, tex (pictex), pdf, jpeg, tiff, png, bmp, svg and wmf (windows only).
If you wish to save it to a excel file, you need to save the image as a jpeg file and then use openxslx as shown below
ggsave(plot=myplots, file=paste0(location,"myplots.jpeg"), width = 14, height = 10, units = "cm")
pic_path <- paste0(location,"myplots.jpeg")
# Add to a new work book -------------
wb <- openxlsx::createWorkbook()
addWorksheet(wb, "Plots")
insertImage(wb, "Plots", pic_path)
openxlsx::saveWorkbook(wb, file=paste0(location,"myplots.xlsx"), overwrite = TRUE)
# Kill pic
unlink(pic_path)

How to export R plots to multipage PDF with renderPlot() in Shiny?

I am forced to output multiple plots not in the static device. But I dynamically create variable number of plots in Shiny with renderPlot. I can successfully create separate pdf files for each device using the function pdf() within the renderPlot.
I have tried to make multipage pdf file as it is specified here and in other similar posts. However in my case the created pdf file has the damaged contents (size of 7 kb) and can't be open. My code after simplification looks as follows.
for (PlotI in 1:PlotN)
{
poObject <- plotOutput(outputId = PlotI)
insertUI(selector = '#AnyPlaceHolder', where = "beforeBegin",
ui = poObject, multiple = FALSE, immediate = FALSE)
} # for PlotI
fnPDF <- paste0(tempdir(), '\\', 'plot.pdf')
pdf(file = fnPDF, width = 7, height = 4, onefile = TRUE, title = 'R output',
paper = 'a4', pointsize = 1/PlotResolution, compress = TRUE)
for (PlotI in 1:PlotN)
{
local(
{
PlotJ <- PlotI
output[[PlotJ]] <- renderPlot(
{
opar <- par(no.readonly = TRUE)
par(mar = c(2,4,2,0.5))
plot(AnyTimeSeries[[PlotJ]])
par(opar)
}
) # renderPlot
}
) # local
} # for PlotI
dev.off()
What is wrong?

How to Save as png with ChartJSRadar in R?

I'm trying to save my plot with resolution of 300 for publication purposes. The usual methods to save plots with png device isn't working and saves a blank png. Is there something else I can try, or a different package that does something similar?
library(radarchart)
data<-data.frame(Field=c("Age","Sex","Submission"), y=sample(1:100,3), x=sample(1:100,3))
path<-"C:\\Desktop\\R\\"
png(file=paste0(path,"Radar",".png"), width=500, height=500, res=300)
plot<-chartJSRadar(scores=data, labelSize= 10, main="Completeness Radar", maxScale = 100)
print(plot)
dev.off()
I've also tried:
png(file=paste0(path,"Radar",".png"), width=500, height=500, res=300)
chartJSRadar(scores=data, labelSize= 10, main="Completeness Radar", maxScale = 100)
dev.off()
library(radarchart)
library(webshot)
library(htmlwidgets)
dat <- data.frame(
Field = c("Age","Sex","Submission"),
y = sample(1:100,3),
x = sample(1:100,3)
)
plt <- chartJSRadar(
scores = dat,
labelSize= 10,
main="Completeness Radar",
maxScale = 100
)
saveWidget(plt, "plt.html")
webshot("plt.html")
magick::image_read("webshot.png")
radar charts are very difficult for folks to grok
data and plot are suberbad variable names
whitespace is your bff
webshot can limit target area
various magick ƒ()s can crop target area
consider using http://www.ggplot2-exts.org/ggradar.html

Resources