Manish
Manish

Reputation: 3521

How to put border around a legend in R?

I m using R to plot legend but i need to draw black border arnd it.

plot.new()
legend(x=0,y=.15, c(" legend1"), cex=1,pt.cex =1.4,col=c("green"),bty="n",fill="green", pch=c(15, 15, 15, 17),border="black")
legend(x=.75,y=.15, " legend", cex=1, pt.cex =1.4,bty="n",col=c("black"), pch=c(17), border="black")

But in the above code, no black border printed as expected in image shown below. How can i

enter image description here

put border(here black border covering greeen box) and legend as shown below.

Upvotes: 0

Views: 5935

Answers (3)

IRTFM
IRTFM

Reputation: 263311

plot.new()
 legend(x=0,y=.15, c(" legend1"), cex=1,pt.cex =1.4,col=c("green"),
         bty="o",fill="green", pch=c(15, 15, 15, 17) )
 legend(x=.75,y=.15, " legend", cex=1, pt.cex =1.4,
         bty="o",col=c("black"), pch=c(17), box.col="red")

Upvotes: 0

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

Of course there is no border! You have used bty = "n"

From ?par (search for "bty" on that page):

bty: A character string which determined the type of box which is drawn about plots. If bty is one of "o" (the default), "l", "7", "c", "u", or "]" the resulting box resembles the corresponding upper case letter. A value of "n" suppresses the box.

Either remove the bty argument or specify on of the alternatives that match the shape of the border you want.


Update based on question edits.

Since you want to control the fill color and border of your pch symbols, try this:

plot.new()
legend(x=0, y=.15, "legend1 ", cex=1, pt.cex=1.4, 
       bty="n", pch=22, col="black",
       pt.bg="green")
legend(x=.75,y=.15, "legend 2", cex=1, pt.cex =1.4, 
       bty="n", pch=24, col="red", pt.bg="white")

The key is to use one of the pch values that can be colored and filled with different colors, which are those in the range of 21 to 35.

From ?pch, the options we have are:

  • pch = 21: filled circle
  • pch = 22: filled square
  • pch = 23: filled diamond
  • pch = 24: filled triangle point-up
  • pch = 25: filled triangle point down

Upvotes: 9

fdetsch
fdetsch

Reputation: 5308

How about using open plot symbols. I think this should be what you are looking for:

plot.new()
legend(x=0, y=.15, "legend1", 
       cex=1, pt.cex =1.4, bty="n", pch=22, pt.bg = "green")
legend(x=.75, y=.15, "legend2", 
       cex=1, pt.cex =1.4, bty="n", pch=24, pt.bg = "black")

Check out this short help page for further pch examples.

Upvotes: 0

Related Questions