Adjust spacing between text in horizontal legend

前端 未结 4 1288
甜味超标
甜味超标 2020-12-24 08:46

I have a plot with a horizontal legend:

 legend(\"bottomleft\", inset = c(0, -0.3), bty = \"n\",
        x.intersp=0, xjust=0,yjust=0,
        legend=c(\"AAP         


        
4条回答
  •  情深已故
    2020-12-24 09:09

    text.width can give you control over the width of each column in your legend, but it's not straightforward. Basically, text.width is a vector that will be multiplied by another vector that is as long as your vector of legend strings. The elements of that second vector are integers from 0 to length(legend)-1. See the code to legend() for the gory details. The important thing is that you can think of this product of text.width and the second vector as, approximately, the x coordinates for your legend elements. Then if you know which x coordinates you want, you can calculate what needs to be passed in the text.width argument.

    legtext <- c("AAPL", "Information Technology", 
                 "Technology Hardware and Equipment", "S&P 500")
    xcoords <- c(0, 10, 30, 60)
    secondvector <- (1:length(legtext))-1
    textwidths <- xcoords/secondvector # this works for all but the first element
    textwidths[1] <- 0 # so replace element 1 with a finite number (any will do)
    

    And then your final code could look something like this (except that we don't know your original plotting data or parameters):

    plot(x=as.Date(c("1/1/13","3/1/13","5/1/13"), "%m/%d/%y"), y=1:3, ylim=c(0,3))
    
    legend(x="bottomleft", bty = "n", x.intersp=0, xjust=0, yjust=0,
       legend=legtext, 
       col=c("black", "red", "blue3", "olivedrab3"), 
       lwd=2, cex = 0.5, xpd = TRUE, ncol = 4,
       text.width=textwidths)
    

    As Andre Silva mentioned, the values you'll want in xcoords and textwidths will depend on the current size of your plot, the range of values specified for your x axis, etc.

    Also, secondvector above would look different if you had more than one element per column. For example, for two columns with two legend elements apiece, secondvector == c(0,0,1,1).

提交回复
热议问题