R在多个图的外部边缘上绘制中心图例 [英] R-plot a centered legend at outer margins of multiple plots

查看:79
本文介绍了R在多个图的外部边缘上绘制中心图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在具有多个绘图的设备中在绘图区域之外绘制居中的图例.关于更改R图中图例的位置,SO中存在许多问题(略有不同).

I want to plot a centered legend outside of the plotting area in a device having multiple plots. There has been many questions (with slight variations) asked in SO about changing the position of legend in a R plot.

例如:

1) R-组合地块的通用标题和图例

2) R中多个图的通用图例

3)情节基本图形中绘图区域之外的图例?

现在我从上述问题中了解到,我必须设置选项xpd = Txpd = NA以便在外边缘处绘制图例.但是,当我尝试此操作时,它对我不起作用..

Now what I understood from the above questions is that I got to set the option xpd = T or xpd = NAto plot legends at the outer margins. However when I try this, it somehow does not work for me ..

par(mfrow=c(1,2),oma=c(0,3,0,0),xpd=TRUE)

plot(c(5,10),col=c("red","blue"),pch=20,cex=2,bty="n",xlab="",ylab="")
barplot(c(5,10),col=c("red","blue"))

mtext(text="My two plots",side=3,cex=2,outer=TRUE,line=-3)

legend("top",legend=c("A", "B"),fill=c("red","blue"),ncol=2,xpd=NA,bty="n")  # Option 1
legend(x=0.01,y=11,legend=c("A", "B"),fill=c("red","blue"),ncol=2,xpd=TRUE,bty="n") # Option 2

现在我的问题是,xpd到底如何工作?因为我无法弄清楚为什么不应该使用xpd=T将图例放置在绘图区域之外.

Now my question is, how does xpd exactly work ? as I am unable to figure out why shouldn't the legend not be placed outside the plot area with xpd=T.

如果有人认为这是上述问题的重复,我事先表示歉意!

I apologize in advance if some consider this as a duplicate of the above questions !!

非常感谢您的帮助

Ashwin

推荐答案

选项#1可能是您应该使用xpd=NA采取的路线.它不会自动将图例放置在外边距中,但是会 允许您 将图例放置在所需的任何位置.因此,例如,您可以使用此代码将图例放置在页面顶部的大致居中位置.

Option #1 is likely the route you should take, with xpd=NA. It does not automatically place the legend in the outer margins, but it allows you to place the legend anywhere you want. So, for example, you could use this code to place the legend at the top of the page, approximately centered.

legend(x=-1.6, y=11.6, legend=c("A", "B"), fill=c("red", "blue"), ncol=2, xpd=NA, bty="n")

我通过反复试验选择了这些x和y值.但是,您可以定义一个函数,在创建的图上覆盖一个(不可见的)图.然后,您可以使用legend("top", ...).例如

I chose these x and y values by trial and error. But, you could define a function that overlays a single (invisible) plot on top of the ones you created. Then you can use legend("top", ...). For example

reset <- function() {
    par(mfrow=c(1, 1), oma=rep(0, 4), mar=rep(0, 4), new=TRUE)
    plot(0:1, 0:1, type="n", xlab="", ylab="", axes=FALSE)
    }

reset()
legend("top", legend=c("A", "B"), fill=c("red", "blue"), ncol=2, bty="n")

这篇关于R在多个图的外部边缘上绘制中心图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆