Reputation: 503
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
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)
a point : legend(1, 1, legend = c("h","w"), col=c("red","green"), pch=19)
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"))
Upvotes: 4
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:
Upvotes: 3