Boxplot with pattern filled

Plotting box-plot is easy in R, however if you wish to fill the boxes with pattern, there is no easy way.
Here, it is demonstrated with a data set created as follow. 

x    <- c(5,2,3,5,1, 3,5,6,7,3, 5,2,3,5,1, 3,5,6,7,3)
site <- c("a","b","c", "d", "e", "a", "b", "c", "d", "e", "a","b","c",             "d", "e", "a", "b", "c", "d", "e")
plot <- c("y", "n","y", "n","y", "n","y", "n","y", "n","y", "n","y",               "n","y", "n","y", "n","y", "n" )
x2   <- c(x, x*1.5, x+1.3, x^1.3)
head(x2)
site2 <- c(site, site, site, site) # repeat to increase the data lenght
plot2 <- c(plot, plot, plot, plot)

a  <- cbind(site2, plot2)
df <- cbind(x2, a )
data.frame(df)-> df1
attach(df1)

head(df1)

      x2 site2 plot2
## 1  5     a     y
## 2  2     b     n
## 3  3     c     y
## 4  5     d     n
## 5  1     e     y
## 6  3     a     n


boxplot(x2~ plot2+site2,  col = c("white", 'gray'))


library(reshape2)  # to draw pattern in boxplot
(bx=boxplot(x2~ plot2+site2, at=c(1,2,3,4,5,6,7,8,9,10), col = c("white", 'gray')))             # "at"  defines where the bar will be, N=number of boxes  

Draw the rectangles for Los Angeles, specifying the left, bottom, right, and top positions of the box plots, the density of the lines, and the angles of the lines

rect(c(2-0.4, 4-0.4, 6-0.4, 8-0.4, 10-0.4), # left margin of box, position at x-axis 
     bx$stats[2,                   # lower limit of box, may not need to change
              c(2,4,6,8,10)],      # position of box at x-axis, subject to change
     c(2+0.4, 4+0.4, 6+0.4, 8+0.4, 10+0.4),  # right margin of box, position at x-axis 
     bx$stats[4,  # upper limit of box, may not need to change
              c(2,4,6,8,10)],      # position of box at x-axis
     density=12, angle=45)
            

No comments:

Post a Comment