В последнее время я столкнулся с аналогичной ситуацией. Я думаю, что мое решение должно быть применимо и к вашей ситуации. Я выполнил это с помощью функции layout()
, чтобы создать многопанельный график, в котором legend()
был помещен в узкую пустую панель.
Важной частью кода я использовал это следующим образом
#####################
# 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")
Я сделал много читать, чтобы понять это; некоторые соответствующие ссылки можно найти здесь:
http://seananderson.ca/courses/11-multipanel/multipanel.pdf
Common legend for multiple plots in R
Весь код, который я использовал, можно найти здесь:
https://github.com/stevekm/Bioinformatics/blob/master/scripts/alignment_summary_muti_panel_barplot.R
Вы должны иметь возможность копировать/вставить что прямо в RStudio и запустите его, чтобы увидеть, как он работает
Вы посмотрели на '? mtext'? –
У меня есть и не совсем понятно, как mtext отличается от текста. – Genetics
Он предназначен для записи на полях. Подожди. вам также нужно прочитать '? par' ... особенно параметр' mar', а также 'xpd'. –