Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I swap labels and symbols in a legend in R?

Tags:

r

The legend that R creates when you call legend() has the symbols (or line types etc) on the left and the labels on the right. I'd like it the other way round, i.e. labels on the left (right-aligned) and the symbols on the right.

I know that I can use adj to adjust the position of the labels, but with this they are not aligned properly anymore. If I set adj=2 for example, the labels are to the left of the symbols, but the end of the text is not aligned with the symbols.

Any pointers on how to do this using either the standard legend() function or a package would be appreciated.

like image 772
Lars Kotthoff Avatar asked Feb 20 '12 18:02

Lars Kotthoff


People also ask

How do I change the text of labels in a legend?

You want to change the text of labels in a legend. Set the labels in the scale (Figure 10.13, left): Note that the labels on the x-axis did not change. To do that, you would have to set the labels of scale_x_discrete () (Recipe 8.10 ), or change the data to have different factor level names (Recipe 15.10 ).

How do you put a legend on a line in R?

R legend position, lines and fill When adding a legend to a plot, there are two main ways to modify the legend position with the R legend function. On the one hand, you can set the argument x to "top", "topleft", "topright", "bottom", "bottomleft", "bottomright", "left", "right" or "center". In this scenario you don’t have to set the argument y.

How do you add a legend to a bar plot?

Note that if you need to add a legend to a bar plot, pie chart or box plot you can use the fill argument instead of setting lines. If your plot have shading lines you can also add them to the legend with the density argument and modify the angle on the lines with the angle argument of the function.

How are the labels matched to the items in the legend?

If you are also changing the order of items in the legend, the labels are matched to the items by position. In this example we’ll change the item order, and make sure to set the labels in the same order (Figure 10.14 ):


1 Answers

If you set trace = TRUE and then save the output, you can draw the legend and then add the labels with a call to text() using the coordinates given by trace, setting pos = 2 for right alignment. Here's an example:

    set.seed(1)
    plot(1:10,runif(min=0,max=10,10),type='l',ylim=c(0,10),xlim=c(0,10),col=1)
    lines(1:10,runif(min=0,max=10,10),col=2,lty=2)
    lines(1:10,runif(min=0,max=10,10),col=3,lty=2)
    a <- legend(1,10,lty=1:3,col=1:3,legend=c("","",""),bty="n",trace=TRUE)
    text(a$text$x-1,a$text$y,c("line 1","line 2","line 3"),pos=2)

enter image description here

like image 67
tim riffe Avatar answered Sep 20 '22 12:09

tim riffe