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.
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 ).
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.
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.
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 ):
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)
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