plot legends without border and with white background

RPlotLegend

R Problem Overview


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?

R Solutions


Solution 1 - R

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")

Solution 2 - R

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbiotomView Question on Stackoverflow
Solution 1 - RmayankView Answer on Stackoverflow
Solution 2 - RjoranView Answer on Stackoverflow