positioning plots and table - r

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().

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)

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)

Add multiple curves between ggplot2 plots

I have two ggplot2 plots and I want to draw a series (10-100) slightly different curves between them. That is, I will have a two-panel layout and want to draw connecting lines from the left plot to the right plot. So far I have tried doing this by converting things to grob's and using the gtable package to add curves.
To illustrate, I have something like:
library(ggplot2)
library(gtable)
library(grid)
library(gridExtra)
p1 = ggplot(data.frame(x=1:10,y=1:10),aes(x=x,y=y))+geom_point()
p2 = ggplot(data.frame(x=1:10,y=1:10),aes(x=x,y=y))+geom_point()
g1 = ggplotGrob(p1)
g2 = ggplotGrob(p2)
gt = gtable:::cbind.gtable(g1,g2,size='first')
gt$heights = unit.pmax(g1$heights,g2$heights)
for(i in 1:10) {
gt = gtable_add_grob(gt,curveGrob(0,0.5,1,0.5,ncp=5,square=FALSE,curvature=i/10),l=5,r=8,b=3,t=3)
}
grid.newpage()
grid.draw(gt)
producing a plot like this:
which is almost right, except only the last of the curveGrob objects is shown. I've tried playing around with the z-index for the added grobs and the last one plotted always overwrites the others. I want my plot to look the same, except it should show all 10 curves between the two plot areas, instead of just the one that is showing with my existing code.
So how can I either modify my existing code to show all 10 curves or achieve the same effect by using a different method? I am stuck using ggplot2 for the main plots, as they are considerably more complex than the toy example shown.
gtable wants unique names for grobs that are in the same position
gt = gtable_add_grob(gt,curveGrob(0,0.5,1,0.5,ncp=5,square=FALSE,curvature=i/10),
l=5,r=8,b=3,t=3, name=paste(i))

Produce single plot and conditioning plot in trellis graphics

Hi there: I'm playing around with the ``tips'' data set for a course that I'm teaching. I'd like to produce one .png file that has the plot of tip as a function of size on the top row of the plotting device (ideally in the center-top, of the window) and the bottom row being the conditioning plot of tip as a function of size grouped by a categorical variable recoded from the total_bill variable contained in the data set. I'm much more familiar with the ggplot2 environment, although I can't quite figure out how to do this there, either.
Thanks!
library(reshape2)
library(grid)
library(lattice)
data(tips)
tips$bill2<-cut(tips$total_bill, breaks=3, labels=c('low', 'medium', 'high'))
#Create one plot window with this plot on the top row, ideally in the center
xyplot(tip~size, data=tips,type=c('r', 'p'))
#With this plot in the second row
xyplot(tip~size|bill2, data=tips, type=c('r', 'p'))
You can use the split argument to print
p1 <- xyplot(tip~size, data=tips,type=c('r', 'p'))
p2 <- xyplot(tip~size|bill2, data=tips, type=c('r', 'p'))
print(p1,split=c(1,1,1,2),more=TRUE)
print(p2,split=c(1,2,1,2),more=FALSE)
see ?print.trellis
Update: to adjust size
That also is in ?print.trellis.
print(p1,split=c(1,1,1,2),more=TRUE,position=c(.3,0,.7,1))
print(p2,split=c(1,2,1,2),more=FALSE)
Tweak the position if you like.
By the way, lattice might not always arrange your second plot as 3 panels in one row, depending on the shape of your graphics window. You can force this by
p2 <- xyplot(tip~size|bill2, data=tips, type=c('r', 'p'),layout=c(3,1))

Exporting graphs in R

I have two graphs that I plotted in R and I want to export it as a high-resolution picture for publication.
For example:
a<-c(1,2,3,4,5,6,7)
b<-c(2,3,4,6,7,8,9)
par(mfrow=c(2,1))
plot (a,b)
plot(a,b)
I usually export this graph by:
dev.copy(jpeg,'test.jpeg',width=80,height=150,units="mm",res=200)
dev.off()
However I always find this process a bit troublesome. The graph that was plotted in R does not necessarily look like the one that I exported. Therefore, I am wondering if there is a way to specifiy the dimensions and resolution of graphs before I plot them so that I can visually inspect the graphs before I export them?
Thank you
You can try:
png('out.png')
a<-c(1,2,3,4,5,6,7)
b<-c(2,3,4,6,7,8,9)
par(mfrow=c(2,1))
plot (a,b)
plot(a,b)
dev.off()
As baptiste said, jpeg is the worst format you can choose. You should take a look at the help for the bmp and png functions (with ?bmp and ?png). Both bmp and png have height, width, and res arguments that you can use to specifiy the dimensions and resolution of the output. Also, I wouldn't recommend the use of dev.copy. As you could see, the result of the output is not always what you expect.
To add to Bonifacio2's answer, you if you call the function first to make the plot, you can also define your margins and window size etc before doing any actual plotting. That way you have full control over all fig specs.
pdf(file='test.jpeg',width=80,height=150,units="mm") #I prefer pdf, because they are editable files
a<-c(1,2,3,4,5,6,7)
b<-c(2,3,4,6,7,8,9)
par(mfrow=c(2,1))
plot (a,b)
plot(a,b)
dev.off()
You can use cowplot package to combine multiple panels in several different ways. For example, in your case, we export one plot with two panels arranged in two rows and one column. I assume that you prefer to use base-R 'plot' function instead of ggplot.
library(cowplot)
p1 <- ~{
plot(a,b)
}
p2 <- ~{
plot(b,a)
}
png("plot.png",
width = 3.149606, # 80 mm
height = 5.905512, # 150 mm
units = 'in',
res = 500)
plot_grid(p1, p2, labels = "AUTO", nrow = 2, ncol = 1)
dev.off()
Note that you can either remove the labels if not needed or print small letters by using "auto". Regarding size of the text, axis-labels etc, use the standard arguments for generic plot function of base-R. I hope this answer helps you. Best wishes.

Resources