Save grid plots drawn within a loop automatically in R - r

I have time-series data of 6 months and I want to plot it in grid manner like this
As a reproducible example, let us the following code:
library(xts)
seq <- seq(as.POSIXct("2015-03-01"),as.POSIXct("2015-03-30"), by = "60 mins")
timeseries_ob <- xts(data.frame(rnorm(length(seq),30,2)),seq)
looplength <- length(unique(.indexmday(timeseries_ob)))
par(mfrow=c(4,3))
pdf("temp.pdf")
for(i in 1:looplength){
daydata <- timeseries_ob[.indexmday(timeseries_ob)%in%i,]
plot(daydata,type="l",main="")
}
dev.off()
With this code, plots get automatically saved, but they are not in the grid manner. Each plot gets saved in different page of pdf. Is there any other way to save above plots in a grid manner automatically.
Note: I don't want to use facet_grid, because these plots are generated within a loop and I believe with ggplot it might become complex to draw.

You have to use the par(mfrow = c(4,3)) command between pdf(...) and dev.off().
This will lead to your desired result!

Related

R: Plotting multiple qcc::cusum charts in one display

I am new to R and I am trying to plot multiple CUSUM charts in one display. I have tried par(mfrow=c(2,1)), layout(), cowplot() and it did not work.
The function mentioned does makes the 1st CUSUM chart smaller and be plotted like normal plot(); successfully plotted 1st CUSUM at top half. However, the 2nd CUSUM chart just refreshes the display automatically instead of being plot below the 1st chart in the same display. Any solution or just possible solution is welcomed, many thanks in advance.
To be clear, I am not talking about plotting 'cumsum' data but CUSUM charts with the cusum() function like the following:
cusum(data, std.dev = standard_deviation_of_data, center = center, add.stats=FALSE, xlab="Studies", title="CUSUM chart", labels=labels)
The issue is most likely associated with the fact that a plot of class "cusum.qcc" is generated.
I do not know how to make this work as a base r plot.
I tried various ways to plot in base r including: par(mfrow...), layout(...), and par(... new = TRUE)
Also tried to convert the cusum plot into a grob so as to use gridExtra::grid.arrange()
None of these efforts worked, so resorted to saving the plots as images and combining images
library(qcc)
library(magick)
data
data(pistonrings)
attach(pistonrings)
diameter <- qcc.groups(diameter, sample)
save as images
jpeg(file="q1.jpeg")
cusum(diameter[1:25,], decision.interval = 4, se.shift = 1)
dev.off()
jpeg(file="q2.jpeg")
cusum(diameter[1:25,], newdata=diameter[26:40,])
dev.off()
read and combine images
q1 <- image_read("q1.jpeg")
q2 <- image_read("q2.jpeg")
img <- c(q1, q2)
image_append(img)
Created on 2020-07-09 by the reprex package (v0.3.0)

How can I stop sapply dropping my barplot titles?

I'm wanting to make a barplot for the factor variables in my data set. To do this I've been running sapply(data[sapply(data, class)=='factor'],function(x) barplot(table(x))). To my annoyance, the plots remember their factor labels, but none of them have retained a title. How can I fix this without titling each graph by hand?
Currently, I'm getting humorously vague untitled graphs like this:
How about
## extract names
fvars <- names(data)[which(sapply(data,inherits,"factor"))]
## apply barplot() with main=
lapply(fvars, function(x) barplot(table(data[[x]]), main=x))
?
Example data:
data <- mtcars
for (i in c("vs","am","gear","carb")) data[[i]] <- factor(data[[i]])
Note that this creates all the plots at once. If you're working in a GUI with a plot history (RStudio or RGui) you can page back through the graphs. Otherwise, you might want to use par(mfrow=c(nr,nc)) (fill in number of rows and columns) to set up subplots before you start.
The numbers that are returned are the bar midpoints (see ?barplot): you could wrap the barplot() call in invisible() if you don't want to see them.

Julia - Displaying several plots in the same plot (not subplot)

Plotting several series in a same plot display is possible and also several subplots in a display. But I want several plots which can be completely different things (not necessarily a series or graph of a map) to be displayed exactly in one frame. How can I do that? In Maple you assign names for each plot like
P1:=...:, P2:= ...: and then using plots:-display(P1,P2,...); and it works. But I want to do this in Julia. Let's say I have the following plots as an example;
using Plots
pyplot()
x=[1,2,2,1,1]
y=[1,1,2,2,1]
plot(x,y)
p1=plot(x,y,fill=(0, :orange))
x2=[2,3,3,2,2]
y2=[2,2,3,3,2]
p2=plot(x2,y2,fill=(0, :yellow))
Now how to have both P1 and P2 in one plot? I don't one a shortcut or trick to write the output of this specific example with one plot line, note that my question is general, for example p2 can be a curve or something else, or I may have a forflow which generates a plot in each step and then I want to put all those shapes in one plot display at the end of the for loop.
Code for a simple example of trying to use plot!() for adding to a plot with arbitrary order.
using Plots
pyplot()
x=[1,2,2,1,1]
y=[1,1,2,2,1]
p1=plot(x,y,fill=(0, :orange))
x2=[2,3,3,2,2]
y2=[2,2,3,3,2]
p2=plot!(x2,y2,fill=(0, :orange))
p3=plot(x,y)
display(p2)
p5=plot!([1,2,2,1,1],[2,2,3,3,2],fill=(0, :green))
By running the above code I see the following plots respectively.
But what I expected to see is a plot with the green rectangle added inside the plot with the two orange rectangles.
The way to plot several series within the same set of axes is with the plot! function. Note the exclamation mark! It's part of the function name. While plot creates a new plot each time it is invoked, plot! will add the series to the current plot. Example:
plot(x, y)
plot!(x, z)
And if you are creating several plots at once, you can name them and refer to them in plot!:
p1 = plot(x, y)
plot!(p1, x, z)
Well, if you do that, what you will have is subplots, technically. That's what it means.
The syntax is
plot(p1, p2)
Sorry, I don't know how to plot a whole plot (conversely to a series) over an other plot.. For what it concerns the order of the plots, you can create as many plots as you want without display them and then display them wherever you want, e.g.:
using Plots
pyplot()
# Here we create independent plots, without displaying them:
x=[1,2,2,1,1]
y=[1,1,2,2,1]
p1=plot(x,y,fill=(0, :orange));
x2=[2,3,3,2,2]
y2=[2,2,3,3,2]
p2=plot(x2,y2,fill=(0, :orange));
p3=plot(x,y);
p5=plot([1,2,2,1,1],[2,2,3,3,2],fill=(0, :green));
# Here we display the plots (in the order we want):
println("P2:")
display(p2)
println("P3:")
display(p3)
println("P5:")
display(p5)
println("P1:")
display(p1)

positioning plots and table

I would like to plot two histograms and add a table to a pdf file. With the layout function I managed to plot the histograms (plotted them using hist function) where I want them to be but when I used grid.table function from the gridExtra package to add the table the table is laid out on the histograms and I am not able to position them properly. I have tried addtable2plot function but I dont find it visually appealing.
Any thoughts on How do I get around this?
I want my pdf to look like this
histogram1 histogram2
t a b l e
Essentially, one row with two columns and another row with just one column. This is what I did.
require(gridExtra)
layout(matrix(c(1,2,3,3),2,2,byrow=T),heights=c(1,1))
count_table=table(cut(tab$Longest_OHR,breaks=c(0,0.05,0.10,0.15,0.20,0.25,0.30,0.35,0.40,0.45,0.50,0.55,0.60,0.65,0.70,0.75,0.80,0.85,0.90,0.95,1.00)))
ysize=max(count_table)+1000
hist(tab$Longest_OHR,xlab="OHR longest",ylim=c(0,ysize))
count_table=table(cut(tab$Sum_of_OHR.s,breaks=c(0,0.05,0.10,0.15,0.20,0.25,0.30,0.35,0.40,0.45,0.50,0.55,0.60,0.65,0.70,0.75,0.80,0.85,0.90,0.95,1.00)))
ysize=max(count_table)+1000
hist(tab$Sum_of_OHR.s,xlab="OHR Sum",ylim=c(0,ysize))
tmp <- table(cut(tab$Length_of_Gene.Protein, breaks = c(0,100,200,500,1000,2000,5000,10000,1000000000)), cut(tab$Sum_of_OHR.s, breaks = (0:10)/10))
grid.table(tmp)
dev.off()
Any help will be appreciated.
Ram
Here's an example of how to combine two base plots and a grid.table in the same figure.
library(gridExtra)
layout(matrix(c(1,0,2,0), 2))
hist(iris$Sepal.Length, col="lightblue")
hist(iris$Sepal.Width, col="lightblue")
pushViewport(viewport(y=.25,height=.5))
grid.table(head(iris), h.even.alpha=1, h.odd.alpha=1,
v.even.alpha=0.5, v.odd.alpha=1)
The coordinates sent to viewport are the center of the panel. Too see exactly where its boundaries are you can call grid.rect().

save multiple plots in R as a .jpg file, how?

I am very new to R and I am using it for my probability class. I searched for this question here, but it looks that is not the same as I want to do. (If there is already an answer, please tell me).
The problem is that I want to save multiple plots of histograms in the same file. For example, if I do this in the R prompt, I get what I want:
library(PASWR)
data(Grades)
attach(Grades) # Grade has gpa and sat variables
par(mfrow=c(2,1))
hist(gpa)
hist(sat)
So I get both histograms in the same plot. but if I want to save it as a jpeg:
library(PASWR)
data(Grades)
attach(Grades) # Grades has gpa and sat variables
par(mfrow=c(2,1))
jpeg("hist_gpa_sat.jpg")
hist(gpa)
hist(sat)
dev.off()
It saves the file but just with one plot... Why? How I can fix this?
Thanks.
Also, if there is some good article or tutorial about how to plot with gplot and related stuff it will be appreciated, thanks.
Swap the order of these two lines:
par(mfrow=c(2,1))
jpeg("hist_gpa_sat.jpg")
so that you have:
jpeg("hist_gpa_sat.jpg")
par(mfrow=c(2,1))
hist(gpa)
hist(sat)
dev.off()
That way you are opening the jpeg device before doing anything related to plotting.
You could also have a look at the function layout. With this, you can arrange plots more freely. This example gives you a 2 column layout of plots with 3 rows.
The first row is occupied by one plot, the second row by 2 plots and the third row again by one plot. This can come in very handy.
x <- rnorm(1000)
jpeg("normdist.jpg")
layout(mat=matrix(c(1,1,2,3,4,4),nrow=3,ncol=2,byrow=T))
boxplot(x, horizontal=T)
hist(x)
plot(density(x))
plot(x)
dev.off()
Check ?layout how the matrix 'mat' (layout's first argument) is interpreted.

Resources