Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plot legends without border and with white background

Tags:

plot

r

legend

I have a legend in a plot with a line (from an abline-statement) going through it. How can I achieve that the abline gets invisible in proximity of the legend? This should be achievable by setting the legend background white, without borders, but how can I achieve this? Assume the graph should look like this:

windows.options(width=30, height=12) plot(1:10) abline(v=seq(1,10,1), col='grey', lty='dotted') legend(4.8, 3, "This legend text should not be disturbed by the dotted grey lines") 

And to get it a bit more complicated: If the legend interferes with the dots of the dot-plot: How can I achieve that the ablines gets invisible in proximity of the legend (as above), but that the dots are still visible?

windows.options(width=30, height=12) plot(1:10) abline(v=seq(1,10,1), col='grey', lty='dotted') legend(1, 5, "This legend text should not be disturbed by the dotted grey lines, but the plotted dots should still be visible") 

And finally: Is there a way to introduce line-breaks in legend statements?

like image 923
biotom Avatar asked Apr 11 '12 14:04

biotom


People also ask

How do I remove the legend border in R?

Therefore, we can use bty="n" with the legend function and it will remove the border of the legend.

How do I change the background color in legend?

On the Display tab, expand Background. For Symbol, click the down arrow to open the color palette. Choose a color to change the legend background.

How do I remove the legend from a border in Matlab?

set(hLeg,'Visible','off'); set(hObj,'Visible','on');


2 Answers

Use option bty = "n" in legend to remove the box around the legend. For example:

legend(1, 5,        "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",        bty = "n") 
like image 157
mayank Avatar answered Sep 23 '22 10:09

mayank


As documented in ?legend you do this like so:

plot(1:10,type = "n") abline(v=seq(1,10,1), col='grey', lty='dotted') legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white") points(1:10,1:10) 

enter image description here

Line breaks are achieved with the new line character \n. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.

Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).

like image 23
joran Avatar answered Sep 24 '22 10:09

joran