如何在图例表/矩阵中对齐文本和线条?

3
我正在尝试对图例中的表格(由矩阵定义)中的行和文本进行对齐。
到目前为止,我尝试过以下方法:
plot(1,type="n",col=2)
legend_order <- matrix(1:12,ncol=3,byrow = TRUE)
legend("topright",
ncol=3,
legend=c("","long label 1","long label 2",
"T=1","","",
"T=2","","",
"T=3","","")[legend_order],
lty=c(0,0,0,0,1,1,0,1,1,0,1,1)[legend_order],
col=c(0,0,0,0,2,5,0,3,6,0,4,7)[legend_order])

enter image description here

在这里,我们可以看到“长标签1”和“长标签2”与彩色线条不对齐。此外,“T”左侧有一段空隙。
如何将文本与线对齐?

请查看我的更新答案,链接如下:https://dev59.com/y8Tsa4cB1Zd3GeqPErkZ#72817428,这是针对您最近的编辑所做出的回应。 - jay.sf
2个回答

2
我们可以使用adj。阅读更多?legend
plot(1,type="n",col=2)
legend_order <- matrix(1:12,ncol=3,byrow = TRUE)
legend("topleft",
       ncol=3,
       legend=c("","foo","bar",
                "T=1","","",
                "T=2","","",
                "T=3","","")[legend_order],
       lty=c(0,0,0,0,1,1,0,1,1,0,1,1)[legend_order],
       col=c(0,0,0,0,2,5,0,3,6,0,4,7)[legend_order],
       adj = 2)


2
您可以使用透明的bty='n'图例覆盖基本legend,并使用adj=进行微调。
plot(1, type="n", col=2)
legend('topright', legend=rep('', 9), lty=c(rep(NA, 3), rep(1, 6)), title='',
       ncol=3, col=c(rep(NA, 3), 2, 5, 3, 6, 4, 7))
legend('topright', legend=c(paste0('T=', 1:3), rep('', 6)), title='', bty='n', 
       adj=.3, ncol=3, col=c(rep(1, 3), rep(NA, 6)))
legend('topright', legend=c('', 'foo', ' bar'), adj=.6, bty='n', ncol=3, 
       col=c(rep(1, 3), rep(NA, 6)))

这里输入图片描述

更新

为了更加灵活,你可以使用par()$usr坐标系统并定义三个调整参数p*。为了稳定起见,我强烈建议使用png设备或类似设备,以固定的宽度和高度进行操作。

png('foo.png', width=480, height=480)

plot(matrix(1:12, 3, 4), type="n", col=2)
pu <- par()$usr
p1 <- 2.1; p2 <- 1.9; p3 <- 1.4
legend(pu[3] - p1, pu[4], legend=rep('', 21), lty=rep(1, 21), title='',
       ncol=7, col=rep(NA, 21))
legend(pu[3] - p1, pu[4], legend=c(paste0('T=', 1:3), rep('', 6)), title='', bty='n', 
       adj=.3, ncol=3, col=c(rep(1, 3), rep(NA, 6)))
legend(pu[3] - p2, pu[4], legend=rep('', 3), lty=1, title='', col=c(2, 5, 3), bty='n')
legend(pu[3] - p3, pu[4], legend=rep('', 3), lty=1, title='', col=c(6, 4, 7), bty='n')
legend(pu[3] - p2, pu[4], legend='fooooooooooo', bty='n', ncol=3, adj=.12)
legend(pu[3] - p3, pu[4], legend='baaaaaaaaaar', bty='n', ncol=3, adj=.12)
box()

dev.off()

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接