Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

increasing the size of the coloured squares on histogram legends in R

Tags:

r

I am trying to increase the size of the coloured squares in the legend on a histogram in R - when I output the PDFs they are too small so it is hard to distinguish the colours. I've searched Google, the R-help Nabble forum and this place, all to no avail. I've also tried several of the commands in the legend documentation.

What do I need to use in the legend() function to increase them? and is it possible to remove the black border around each coloured square to ease viewing?

Here my example:

a<-c(1,1,2,3,3,3,3,4,54,56,2,23,1,3,23)
hist(a) 
graphics::legend(x=-1,y=10,c(">0%",">20%",">40%",">60%",">80%"),
       x.intersp=1,y.intersp=2,cex=1, bty="n",
       fill=c("black","gray50","gray70","gray85","white"))

enter image description here

I wish to change the size of box in the legend?


SOLUTION: from @Ben Bolker

add to the script above the legend function

> source("http://www.math.mcmaster.ca/bolker/R/misc/legendx.R")

then add

> box.cex=c(2,2)

within the legend function

like image 723
rg255 Avatar asked Dec 06 '22 10:12

rg255


2 Answers

I hacked the source of the legend function to allow a box.cex argument that specifies the relative x and y dimensions of the box. This isn't perfect -- if the expansion is big enough then you have to adjust y.intersp to prevent the fill boxes from overlapping.

source("http://www.math.mcmaster.ca/bolker/R/misc/legendx.R")
a<-c(1,1,2,3,3,3,3,4,54,56,2,23,1,3,23)
cex <- 1
hist(a)
legend("topright",c(">0%",">20%",">40%",">60%",">80%"),
       bty="n",
       fill=c("black","gray50","gray70","gray85","white"),
       box.cex=c(3,3),
       y.intersp=2.8)

enter image description here

like image 61
Ben Bolker Avatar answered Jan 18 '23 12:01

Ben Bolker


You can use very thick lines, with rectangular ends.

plot( 1, type = "n", axes = FALSE, xlab = "", ylab = "" ) # Empty plot
par( lend = 1 ) # Rectangular line endings
legend(
  "topleft",
  c( "Red", "Black" ),
  col = c("red", "black"),
  lty = 1, lwd = 10
)

enter image description here

like image 21
Vincent Zoonekynd Avatar answered Jan 18 '23 13:01

Vincent Zoonekynd