R - Common title and legend for combined plots - r

I would like to know how to provide a common title and legend for combined plots in R. I have four plots which I have combined into one. Each plot has its own Title. I want to specify a common Title on the top center and common legend on the top left corner of the combined plot. I generated the combined plot using par(). I have provided my plot below

You can use the oma parameter to increase the outer margins,
then add the main title with mtext,
and try to position the legend by hand.
op <- par(
oma=c(0,0,3,0),# Room for the title and legend
mfrow=c(2,2)
)
for(i in 1:4) {
plot( cumsum(rnorm(100)), type="l", lwd=3,
col=c("navy","orange")[ 1+i%%2 ],
las=1, ylab="Value",
main=paste("Random data", i) )
}
par(op) # Leave the last plot
mtext("Main title", line=2, font=2, cex=1.2)
op <- par(usr=c(0,1,0,1), # Reset the coordinates
xpd=NA) # Allow plotting outside the plot region
legend(-.1,1.15, # Find suitable coordinates by trial and error
c("one", "two"), lty=1, lwd=3, col=c("navy", "orange"), box.col=NA)

Related

Dual Y-Axis Base R Plot with different x-ticks

I want to make a plot of 4 sets of data points using dual y-axis. The first two are on the left y-axis and last two are on the right y-axis. The first two belong to a set of numbers ranging from 5000 to 50,000. Second two sets of data belong range from 1-100. I want to plot it so that it is easily discernable that the two axis are not only on different scales but also the height between points from the two different sets with distinct ranges is obviously big. I don't want to be able to draw a horizontal line that would suggest some number from the left-y-axis can be mapped bijectively to some number on the right y-axis. I want to make it such that a horizontal line through any points from the left y-axis and right y-axis would belong to only one set related to either left or right axis.
How can I plot with 2 different y-axes?. There's
I'd use twoord.plot
From plotrix v3.7-5
by Jim Lemon but that has the disadvantage than base R beacause I can't add 4 sets of data into one plot. I can only use 2 sets of (x,y) pairs with 2--ord plot. I can theoretically plot n sets of (x,y) pairs using base R.
None
Here's what doesn't work:
time <- seq(0,72,12)
betagal.abs <- c(0.05,0.18,0.25,0.31,0.32,0.34,0.35)
cell.density <- c(0,1000,2000,3000,4000,5000,6000)
## add extra space to right margin of plot within frame
par(mar=c(5, 4, 4, 6) + 0.1)
## Plot first set of data and draw its axis
plot(time, betagal.abs, pch=16, axes=FALSE, ylim=c(0,1), xlab="", ylab="",
type="b",col="black", main="Mike's test data")
axis(2, ylim=c(0,1),col="black",las=1) ## las=1 makes horizontal labels
mtext("Beta Gal Absorbance",side=2,line=2.5)
box()
## Allow a second plot on the same graph
par(new=TRUE)
## Plot the second plot and put axis scale on right
plot(time, cell.density, pch=15, xlab="", ylab="", ylim=c(0,7000),
axes=FALSE, type="b", col="red")
## a little farther out (line=4) to make room for labels
mtext("Cell Density",side=4,col="red",line=4)
axis(4, ylim=c(0,7000), col="red",col.axis="red",las=1)
## Draw the time axis
axis(1,pretty(range(time),10))
mtext("Time (Hours)",side=1,col="black",line=2.5)
## Add Legend
legend("topleft",legend=c("Beta Gal","Cell Density"),
text.col=c("black","red"),pch=c(16,15),col=c("black","red"))
Not quite sure what you're after but you can add an extra 'line per plot' by using lines.
I've edited your code
## Plot first set of data and draw its axis
plot(time, betagal.abs, pch=16, axes=FALSE, ylim=c(0,1), xlab="", ylab="",
type="b",col="black", main="Mike's test data")
lines(seq(0, 1, 0.02), type = 'o')
axis(2, ylim=c(0,1),col="black",las=1) ## las=1 makes horizontal labels
mtext("Beta Gal Absorbance",side=2,line=2.5)
box()
## Allow a second plot on the same graph
par(new=TRUE)
## Plot the second plot and put axis scale on right
plot(time, cell.density, pch=15, xlab="", ylab="", ylim=c(0,7000),
axes=FALSE, type="b", col="red")
lines(seq(0, 5000, 10), type = 'o', col = 'red')
## a little farther out (line=4) to make room for labels
mtext("Cell Density",side=4,col="red",line=4)
axis(4, ylim=c(0,7000), col="red",col.axis="red",las=1)
which produces this:
Please let me know if this wasn't what you were after.

How to adjust the space between 2 columns in a plot legend?

I want to have the plot legend for a pie chart as a single plot (6 graphics at a page - 5 plots, 1 legend). Now I have difficulties adjusting the space between the 2 columns.
I used the following code (by try and error):
#Colors
colors=c("blue","green","yellow","orange","red","purple","pink","grey")
legtext <- c("G","G*E","E","Source","Source*E",
"Table*E","Table*Block*E","Residual Error")
#Code for chart
pie3D(#data for pie
rooting1,
#specify labels vector
#labels=labels,
#specify labels size
labelcex=0.9,
#how much different pies go from each other
explode=0.1,
#height of chart
height=0.1,
#Main title
theta=pi/3,
#Colors
col=colors
)
#Code for legend
xcoords <- c(0.9,1,1.1,1.2)
secondvector <- (1:length(legtext))-1
textwidths <- xcoords/secondvector # this works for all but the first element
textwidths[1] <- 0
legend(-1, 0.9,ncol=2,
c("G","G*E","E","Source","Source*E","Table*E","Table*Block*E","Residual Error"),
cex = 0.8,
fill = colors,
text.width=textwidths)
The plot I get is this: I want to remove the vertical lines and if possible, remove the rest of the chart as I only want to display the legend.
Legend I get:
Can anybody help me?
Add bty="n" to your legend:
legend(-1, 0.9,ncol=2,
c("G","G*E","E","Source","Source*E","Table*E","Table*Block*E","Residual Error"),
cex = 0.8,
fill = colors,
text.width=textwidths,
bty="n")
As for the other question - how to get rid of the chart itself, this will take some fiddling. Basically, what you can do is to make an empty chart, but adjusting the xlim and ylim, as well as margins so that there is enough room for the legend:
par(mar=c(0.1,0.1,0.1,0.1)) # you don't need large margins
# but maybe you need more than 0.1
plot(NA, xlim=c(-1,1), ylim=c(-1,1), axes=FALSE, xlab="", ylab="")
# this makes an empty plot
# you may need to change xlim and ylim (or the x and y of your legend)
# ... so that the legend would start from the left/upper corner

R plot: How to control distance between horizontal axis and lower column? [duplicate]

How can I move the y axis label from the left to the right of the plot area and the x-axis label from below to above the plot area in the following graph? Thanks
xleft<-c(1,2,2.5)
xright<-c(2,2.5,2.75)
ybottom<-c(1,2,2.5)
ytop<-c(2,2.5,2.75)
par(mar = c(15,15,2.75,2.75) + 0.1)
plot(c(1,3),c(1,3),type="n",main="title",xlab="xlab-move me above plot",ylab="ylab-move me right of plot",axes=F,asp=1)
axis(1,pos=1)
axis(2,pos=1)
rect(xleft,ybottom,xright,ytop,col=c("blue","red","green"))
#Label position along  axes
x.label.position<-(xleft+xright)/2
y.label.position<-(ybottom+ytop)/2
#Labels
x.label<-c("Long species Name1","Long species Name2","Long species Name3")
y.label<-c("Long species Name4","Long species Name5","Long species Name5")
text(par()$usr[1]-0.5,y.label.position,y.label,xpd=TRUE,adj=1)
text(y=par()$usr[3]-0.5,x=x.label.position,x.label,xpd=TRUE,adj=1,srt=90)
par(xpd=TRUE)
legend(-0.1,0,legend=c("Species A","Species B","Species C"),fill=c("blue", "red", "green"))
Ploting axes on the right and top sides of a plot
By default R will plot the x-axis below the plot area and the y-axis to the left of it. You can change this behaviour in this way:
plot(1:100, cumsum(rnorm(100)), type="l", axes=FALSE) # Do not plot any axes
axis(3) # Draw the x-axis above the plot area
axis(4) # Draw the y-axis to the right of the plot area
box()
To also move the labels you set ann=FALSE or xlab="", ylab="" and add them afterwards with mtext, where side=1 is bottom, 2 is left, 3 is top, 4 is right. line controls the distance from the plot area.
plot(1:100, cumsum(rnorm(100)), type="l", axes=FALSE, ann=FALSE)
axis(3)
box()
mtext("Top axis", side=3, line=3)
Changing distance between labels, ticks and plot area.
Use the mgp parameter to control these details, either before the call to plot, like this
par(mgp=c(axis.title.position, axis.label.position, axis.line.position))
or in the plot command itself, like this
plot(1:100, cumsum(rnorm(100)), type="l", mgp=c(2,1,.5), las=1)
Also note the las parameter that turns all tick labels horisontal, which makes them easier to read.

Overlapping histograms on one page in R

I am a beginner with R. I managed to plot my data into overlapping histograms. However, I would like to place all the histograms on one page. I am struggling as I am not able to tell R, which sets to pick (only manage to plot one of the plots).
This is the code:
df<-read.csv("Salt dshalo sizes.csv",header=T)
#View(df)
library(ggplot2)
DSA<-df[,1]
DS1<-df[,2]
DSB<-df[,5]
DS2<-df[,6]
DSC<-df[,9]
DS3<-df[,10]
#remove the NA column by columns separately or it will chop the data
DSA=na.omit(DSA)
DS1=na.omit(DS1)
DSB=na.omit(DSB)
DS2=na.omit(DS2)
DSC=na.omit(DSC)
DS3=na.omit(DS3)
#plot histograms for DSA, DSB and DSC on one same graph
hist(DSA, prob=TRUE, main="Controls", xlab="Sizes (um)", ylab="Frequency", col="yellowgreen",xlim= c(5,25), ylim=c(0,0.5), breaks=10)
hist(DSB, prob=TRUE, col=rgb(0,0,1,0.5),add=T)
hist(DSC, prob=TRUE, col=rgb(0.8,0,1,0.5),add=T)
#add a legend to the histogram
legend("topright", c("Control 1", "Control2", "Control3"), text.width=c(1,1,1),lwd=c(2,2,2),
col=c(col="yellowgreen", col="blue", col="pink",cex= 1))
box()
#plot histograms for DS1, DS2 and DS3 on one same graph
hist(DS1, prob=TRUE, main="Monoculture Stressed", xlab="Sizes (um)", ylab="Frequency", col="yellowgreen",xlim= c(5,25), ylim=c(0,0.5), breaks=10)
hist(DS2, prob=TRUE, col=rgb(0,0,1,0.5),add=T)
hist(DS3, prob=TRUE, col=rgb(0.8,0,1,0.5),add=T)
#add a legend to the histogram
legend("topright", c("DS1", "DS2", "DS3"), text.width=c(1,1,1),lwd=c(2,2,2),
col=c(col="yellowgreen", col="blue", col="pink",cex= 1))
box()
# put both overlapping histograms onto one page
combined <- par(mfrow=c(1, 2))
plot(hist(DSA),main="Controls")
plot(hist(DS1),main="Monoculture stressed")
par(combined)
Basically, I get two separate overlapping histograms, but cannot put them on the same page.
EDIT: I evidently didn't read your question thoroughly. I see you figured out the add =T.
I assume what you are looking for then is the comment I made first:
par(mfrow = c(a,b)) where a and b are the number of rows and columns you want the graphics objects to be printed. I used c(2,2) for this pic.
I made a comment, but sounds like you may be talking about the add=T option.
a=rnorm(100, 2, 1)
b=rnorm(100, 4, 1)
hist(a, xlim=c(0,10), col="yellow")
hist(b, add=T, col="purple" )
you can play around with transparency options on colors to see both overlap. Such as rgb(1,0,0,1/4) as the color.
With transparency colors:
a=rnorm(100, 2, 1)
b=rnorm(100, 4, 1)
hist(a, xlim=c(0,10), col=rgb(1,1,0,1/4))
hist(b, add=T, col=rgb(1,0,0,1/4) )

Common main title of a panel of plots

I have 2 plots in a panel via par(mfrow=c(1,2))
op <- par(
oma=c(0,0,3,0),# Room for the title and legend
mfrow=c(1,2)
)
for(i in 1:2) {
plot( cumsum(rnorm(100)), type="l", lwd=3,
col=c("navy","orange")[ 1+i%%2 ],
las=1, ylab="Value",
main=paste("Random data", i) )
}
I would like to plot main title "Random plots" which will fit nicely in the middle of the 2 plots.
I tried the solution from here R - Common title and legend for combined plots using mtext and a lot of experimenting but the mtext solution does not get the title exactly in the middle, just like the main argument of plot().
Is there any alternative?

Resources