I dealt with a similar situation recently. I think my solution should be applicable to your situation as well. I accomplished this by using the layout()
function to create a multi-pane plot, in which the legend()
was placed in a narrow empty pane.
The important part of the code I used is as follows
#####################
# Set up the plots
BARPLOT_COLORS<-c("blue","purple","red")
# setup the matrix for the plot layout
# it is easier to create this in a csv file in Excel, etc., then read it into R as a matrix
# here is the dput() code for the matrix I made
Counts_matrix<-structure(c(1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 2L,
2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 2L, 2L, 2L, 2L, 2L, 3L,
3L, 3L, 3L, 3L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L),
.Dim = c(11L,4L),
.Dimnames = list(NULL, c("V1", "V2", "V3", "V4")))
# looks like this
# > Counts_matrix
# V1 V2 V3 V4
# [1,] 1 1 1 1
# [2,] 2 2 2 2
# [3,] 2 2 2 2
# [4,] 2 2 2 2
# [5,] 2 2 2 2
# [6,] 2 2 2 2
# [7,] 3 3 3 3
# [8,] 3 3 3 3
# [9,] 3 3 3 3
# [10,] 3 3 3 3
# [11,] 3 3 3 3
# the numbers here correspond to contiguous areas in which the plots will be placed
# in the numerical order specified
# since the OP wants the legend on the right side, make a matrix like this with 1's along that side
# setup the panel layout by passing the matrix to layout()
layout(Counts_matrix)
# layout.show(max(Counts_matrix)) # use this to preview the layout
par(mar=c(0,0,4,0)) # need to set this for some reason
# on mar: A numerical vector of the form c(bottom, left, top, right) which gives the number of lines of margin to be specified on the four sides of the plot.
# The default is c(5, 4, 4, 2) + 0.1.
# call blank plot to fill the first panel
plot(1,type='n',axes=FALSE,xlab="",ylab="",main = "Quality Counts",cex.main=2)
# set up the Legend in the first panel
legend("bottom",legend=c("Good","Bad","Ugly"),fill=BARPLOT_COLORS,bty = "n",ncol=length(BARPLOT_COLORS),cex=1.0)
# set the mar for the remaining panels
par(mar=c(6,5,0,4))
# create barplot for the two matrices
barplot(Raw_Counts,horiz = T,col=BARPLOT_COLORS,border=NA,las=1,cex.names=1,xlab="Number of counts (millions)")
barplot(Pcnt_Counts,horiz = T,col=BARPLOT_COLORS,border=NA,las=1,cex.names=1,xlab="Percent of counts")
I did a lot of reading to figure this one out; some relevant links can be found here:
http://seananderson.ca/courses/11-multipanel/multipanel.pdf
Common legend for multiple plots in R
The entire code that I used can be found here:
https://github.com/stevekm/Bioinformatics/blob/master/scripts/alignment_summary_muti_panel_barplot.R
You should be able to copy/paste that right into RStudio and run it to see how it works