Javier2013
Javier2013

Reputation: 503

Legend on an empty plot gives no colors

I am trying to make a legend on an empty plot in R, but when I specify the colors argument on the legend function I don't get any colors.

plot(1, type="n", axes=FALSE, xlab="", ylab="")
legend(1, 1, legend = c("h","w"), col=c("red","green"))

I only see the labels of legend but not the colors.

Why?

Upvotes: 1

Views: 895

Answers (2)

Cath
Cath

Reputation: 24074

you have to choose something to put into colors. Here, you're telling R the colors but no object. You can choose, for example:

a plain line : legend(1, 1, legend = c("h","w"), col=c("red","green"), lty=1) enter image description here
a point : legend(1, 1, legend = c("h","w"), col=c("red","green"), pch=19)

enter image description here

Or another type of line or symbol but you need to specify in the legend call what you want to put in colors.

To complete @LyzandeR 's suggestion, if you want the border of the boxes to be of same colors as the filling, you need to also use border:

plot(1, type="n", axes=FALSE, xlab="", ylab="")
legend(1, 1, legend = c("h","w"), fill=c("red","green"), border=c("red","green"))

enter image description here

Upvotes: 4

LyzandeR
LyzandeR

Reputation: 37879

If you just want the colours irrespective of a shape you can also use the fill argument instead.

plot(1, type="n", axes=FALSE, xlab="", ylab="")
legend(1, 1, legend = c("h","w"), fill=c("red","green"))

Which produces:

enter image description here

Upvotes: 3

Related Questions