Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Legend with color filling and shading lines in Base R

Tags:

plot

r

base

legend

In my plot I have two intersecting polygons, one colored and one with shading lines. In the legend I would like the two polygons and the intersection array represented correctly. Here is what I have:

plot(1:4, 1:4, type="n", xaxt="n", xlab="", yaxt="n", ylab="")
polygon(c(2,4,2), c(1,3,3), col="gray")
polygon(c(3,3,1), c(1,3,2), col="red", density=10)
legend("topleft", legend=c("A", "B", "AB"), fill=c("gray", "red", "gray"),
           density=c(NA, 10, NA), bty="n") 

Intersecting polygons, legend problem

Is it possible to change the border color in the legend for B to red and add red shading lines to the symbol for AB?

like image 953
Sophia Avatar asked Mar 25 '13 14:03

Sophia


People also ask

How do you fill a color legend in R?

To create the legend for a plot in base R, we can use legend function and if the background color of the legends needs to be changed from white to any other then bg argument in legend function will be used. For example, to change the background color to red then we can use bg="red".

What is inset in legend in R?

The optional inset argument specifies how far the legend is inset from the plot margins. If a single value is given, it is used for both margins; if two values are given, the first is used for x - distance, the second for y -distance.

What is Cex in legend in R?

legend: Text of the legend. fill: Colors to use for filling the boxes with legend text. col: Colors of lines. bg: It defines background color for the legend box. cex: Used for scaling.

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.


1 Answers

You should add argument border= to legend() to change the border color of small boxes and then add another call to legend() to overlay shading to AB box with your color. In the second legend() line I set density= for the AB to 10 and changed also fill= to red for the same box.

plot(1:4, 1:4, type="n", xaxt="n", xlab="", yaxt="n", ylab="")
polygon(c(2,4,2), c(1,3,3), col="gray")
polygon(c(3,3,1), c(1,3,2), col="red", density=10)
legend("topleft", legend=c("A", "B", "AB"), fill=c("gray", "red", "gray"),
       density=c(NA, 10, NA), bty="n",border=c("black", "red", "black")) 
legend("topleft", legend=c("A", "B", "AB"), fill=c("gray", "red", "red"),
       density=c(NA, 10, 10), bty="n",border=c("black", "red", "black")) 

enter image description here

like image 91
Didzis Elferts Avatar answered Oct 01 '22 12:10

Didzis Elferts