简体   繁体   English

对齐图例表/矩阵中的文本和行

[英]Aligning the text and lines in legend table/matrix in plot

I'm trying to align lines and text in a table (defined by a matrix) inside a legend.我正在尝试在图例中对齐表格(由矩阵定义)中的线条和文本。

What I've tried so far:到目前为止我已经尝试过:

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])

在此处输入图像描述

Here we can see that "long label 1" and "long label 2" are not aligned with the colored lines.在这里我们可以看到“长标签 1”和“长标签 2”没有与彩色线条对齐。 Also there is a gap left of the "T"s. “T”的左边也有一个间隙。

How do you align the text with the lines?你如何将文本与线条对齐?

We can use adj .我们可以使用adj Read more ?legend ;阅读更多?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)

You could overlay a base legend with transparent bty='n' legends and fine-tune using adj= .您可以使用透明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)))

在此处输入图像描述

Update更新

To be even more flexible you could use the par()$usr coordinates and define three adjustment parameters p* .为了更加灵活,您可以使用par()$usr坐标并定义三个调整参数p* For sake of stability I strongly recommend to use the png device or similar with fixed width and height.为了稳定起见,我强烈建议使用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()

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM