Home > Enterprise >  Aligning the text and lines in legend table/matrix in plot
Aligning the text and lines in legend table/matrix in plot

Time:07-01

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("","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])

enter image description here

Here we can see that "foo" and "bar" are not aligned with the colored lines. Also there is a gap left of the "T"s.

How do you align the text with the lines?

CodePudding user response:

We can use adj. Read more ?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)

CodePudding user response:

You could overlay a base legend with transparent bty='n' legends and fine-tune using 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)))

enter image description here

  • Related