我想将标题相对于我使用此代码创建的绘图矩阵(而不是整个绘图)居中:
d <- 3
d2 <- d*d
layout.mat <- matrix(1:d2, byrow=TRUE, ncol=d) # plot matrix
layout.mat <- cbind(layout.mat, rep(0, d)) # space
layout.mat <- cbind(layout.mat, rep(d2+1, d)) # column on the right side
wspace <- 6*par("csi")*2.54 # width of the space in character height in cm
wside <- 3*par("csi")*2.54 # width of the right side in character height in cm
layout(layout.mat, respect=TRUE, widths=c(rep(1, d), lcm(wspace), lcm(wside)))
layout.show(d2+1)
par(mar=rep(0, 4), oma=c(4,4,6,4))
for(i in 1:d){
for(j in 1:d){
plot.new()
plot.window(xlim=c(0,1), ylim=c(0,1))
ll <- par("usr")
rect(ll[1], ll[3], ll[2], ll[4])
text(0.5, 0.5, paste("i=",i,", j=",j,sep=""), cex=1.4)
}
}
plot.new()
plot.window(xlim=c(0,1), ylim=c(0,1))
ll <- par("usr")
rect(ll[1], ll[3], ll[2], ll[4])
text(0.5, 0.5, "side", cex=1.4)
## title
mtext("This title should be centered according to the plot matrix", side=3,
line=2, outer=TRUE, adj=0.5, at=0.5)
如何确定(使用给定的固定距离wspace
和wside
)绘图区域的宽度,以便我可以减去wspace+wside
从中确定绘图矩阵的宽度?最终目标是确定 mtext
的 adj
的精确值,使标题位于绘图矩阵上方的中心,而不是整个绘图区域的中心。
最佳答案
如何在 for
循环中添加此代码:
if (i == 1 & j == 2){
mtext("This title should be centered according to the plot matrix", side=3,
line=2, outer=FALSE, adj=0.5, at=0.5)
}
请注意对 outer = FALSE
的更改。这是它的样子,标题文本较短(长版本在小图中的两侧延伸,但仍然居中):
当然,此技巧仅在列数为奇数时才有效。更通用的解决方案可能是更改布局,在顶部包含一个短而宽的水平区域,并直接在该区域中绘制文本:
d <- 4
d2 <- d*d
layout.mat <- matrix(1:d2, byrow=TRUE, ncol=d) # plot matrix
layout.mat <- cbind(layout.mat, rep(0, d)) # space
layout.mat <- cbind(layout.mat, rep(d2+1, d)) # column on the right side
layout.mat <- rbind(c(rep(18,d),0,0),layout.mat) #Add row on top
wspace <- 6*par("csi")*2.54 # width of the space in character height in cm
wside <- 3*par("csi")*2.54 # width of the right side in character height in cm
#Note adjustments to heights
layout(layout.mat, respect=TRUE, widths=c(rep(1, d), lcm(wspace), lcm(wside)),
heights = c(0.25,rep(1,nrow(layout.mat)-1)))
layout.show(d2+1)
par(mar=rep(0, 4), oma=c(4,4,6,4))
for(i in 1:d){
for(j in 1:d){
plot.new()
plot.window(xlim=c(0,1), ylim=c(0,1))
ll <- par("usr")
rect(ll[1], ll[3], ll[2], ll[4])
text(0.5, 0.5, paste("i=",i,", j=",j,sep=""), cex=1.4)
}
}
plot.new()
plot.window(xlim=c(0,1), ylim=c(0,1))
ll <- par("usr")
rect(ll[1], ll[3], ll[2], ll[4])
text(0.5, 0.5, "side", cex=1.4)
## title
plot.new()
plot.window(xlim=c(0,1), ylim=c(0,1))
ll <- par("usr")
#rect(ll[1], ll[3], ll[2], ll[4])
text(0.5, 0.5, "top", cex=1.4)
关于R,布局: How to determine the width of the parts of a plotting region in order to center a title?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9940994/