tflutre
tflutre

Reputation: 3546

In R, how to combine an expression with a string on two lines in legend labels?

I want to plot on the same figure the results returned by two methods, m1 and m2. In my particular case, the label of the first method is an expression (because it has a subscript) and the label of the second method is on two lines (because it is long). However, having these two requirements doesn't work:

l <- list("m1"=list(data=1:10, col=2, label=expression(paste("method 1 (", X[a], ")"))))
l[["m2"]] <- list(data=rep(3,10), col=3, label="method 2 (with a\nlong explanation)")
plot(l[["m1"]]$data, col=l[["m1"]]$col); points(l[["m2"]]$data, col=l[["m2"]]$col)
legend("topleft", legend=c(l[["m1"]]$label, l[["m2"]]$label), col=c(l[["m1"]]$col, l[["m2"]]$col), pch=1)

As you can see in the legend, the 2nd label (the one on two lines) overlaps with the first label.

The problem disappears when I don't use an expression for the first label:

legend("topleft", legend=c("method 1 (Xa)", l[["m2"]]$label), col=c(l[["m1"]]$col, l[["m2"]]$col), pch=1)

The problem also disappears when the second label is on a single line:

legend("topleft", legend=c(l[["m1"]]$label, "method 2 (with a long explanation)"), col=c(l[["m1"]]$col, l[["m2"]]$col), pch=1)

However, I really need both the expression and the two lines. Any idea?

ps: I'm using R 2.14.1 on Lubuntu.

Upvotes: 2

Views: 1026

Answers (1)

agstudy
agstudy

Reputation: 121568

You can play with y.intersep and cex parameters.

legend("topleft", 
       legend=c(l[["m1"]]$label, 
                l[["m2"]]$label),
       col=c(l[["m1"]]$col,l[["m2"]]$col), 
       pch=0.5,title.adj=100,cex=0.8,y.intersp=2
       )

enter image description here

Upvotes: 3

Related Questions