I have a linebreak in a legend in R and my problem is that the graphic looks not as expected. My minimal example is as follows:
plot(1)
legendLabel<-c("t\nu ","tu","wh","trr\nni")
legend("top",legend=legendLabel,horiz=TRUE,fill=c("red","blue","gray","black"))
I would expect that the upper and lower margin of the legend is equal, but this is not the case.
As you can see in the attached image, the lower margin is smaller then the upper.
Does anybody have an idea how to fix it or can anyone tell me what the problem is?
Thanks.
OK, I believe I have a solution for you. I saved the information of the legend position in an object called ld
and then create a polygon
based on these coordinates. It's a bit tricky to understand, but I am basically expanding the polygon by a few pointsize lengths. In order to do this, I had to first get the character size in inches with par()$cin
and covert the pointsize to these dimensions (divide by 72 and multiply by par()$ps
. Then, convert this to the units of the plot by scaling with par()$usr
to get character width in units (I think this is correct - in any case it works!). I added 3 of these units to the left of the ld
coordinates, 2 to the right, 1 up and 1 down. Here's the result and code:
plot(1)
legendLabel<-c("t\nu ","tu","wh","trr\nni")
ld <- legend("top",legend=legendLabel,horiz=TRUE,fill=c("red","blue","gray","black"), bty="n")
CIN <- par()$cin
PS <- par()$ps
USR <- par()$usr
CIN.USR <- c((CIN[1]/72*PS)/(USR[2]-USR[1]), (CIN[2]/72*PS)/(USR[4]-USR[3]))
xs <- c(ld$text$x[1], ld$text$x[1], ld$text$x[length(ld$text$x)], ld$text$x[length(ld$text$x)])
ys <- c(ld$text$y[1], ld$text$y[1], ld$text$y[length(ld$text$x)], ld$text$y[length(ld$text$x)])
polygon(
x = xs + c(-3*CIN.USR[1], -3*CIN.USR[1], 2*CIN.USR[1], 2*CIN.USR[1]),
y = ys+c(-1*CIN.USR[2], 1*CIN.USR[2], 1*CIN.USR[2], -1*CIN.USR[2])
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With