Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linebreak in R plot legend behavior

Tags:

plot

r

legend

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.enter image description here

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.

like image 262
steffenmauch Avatar asked Nov 22 '12 15:11

steffenmauch


1 Answers

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 ldcoordinates, 2 to the right, 1 up and 1 down. Here's the result and code:

enter image description here

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])
)
like image 85
Marc in the box Avatar answered Oct 09 '22 17:10

Marc in the box