Search code examples
rboxplotshading

How would you put a shadow on a boxplot in R?


I am creating a boxplot in R and want to add a shadow to the box(similar to the box-shadow property in CSS). I was wondering if this was possible and if so how would you do this? Thank You


Solution

  • This is certainly an unpopular choice in terms of graph aesthetics, but if for some reason you do need to do it, one simple way to achieve the effect would be to just plot some grey rectangles underneath the boxes. Here's a quick and dirty example using the mtcars dataset.

    #Plot and save the dimensions of the boxes   
    b <- boxplot(mpg~cyl,data=mtcars)
    

    This will return a list with an object stats that contains the y-coordinates of the boxes in the second and fourth rows. The default settings are to plot the first box at x=1 with a width of 0.8, so from x=0.6 to x=1.4 and so on.

    #Pick some arbitrary offsets
    xoffset <- 0.03
    yoffset <- 0.3
    
    #Add a dark gray rectangle slightly offset to each box
    rect(0.6+xoffset, b$stats[2,1]-yoffset, 1.4+xoffset, b$stats[4,1]-yoffset, col="darkgray", border=NA)
    
    rect(1.6+xoffset, b$stats[2,2]-yoffset, 2.4+xoffset, b$stats[4,2]-yoffset, col="darkgray", border=NA)
    
    rect(2.6+xoffset, b$stats[2,3]-yoffset, 3.4+xoffset, b$stats[4,3]-yoffset, col="darkgray", border=NA)
    
    #Replot the same boxplot on top of the rectangles using the `add=TRUE` argument. 
    boxplot(mpg~cyl,data=mtcars, xlab="Number of Cylinders", ylab="Miles Per Gallon",
            add=TRUE) 
    

    You might want to make some adjustments so that the shadows are proportional to the size of the boxes. Art isn't my thing so I'm honestly not sure how that is supposed to work with light source and perspective etc. Again, you probably don't want to do this, but you can try it out yourself and see how it compares to the other better plotting options that R offers.

    boxplot with shadows