Changing box styling

So far, we have used the default styling for our box plots. In this recipe, we will learn how to change the colors, widths, and styles of various elements of a box plot.

Getting ready

We will continue using the base graphics library functions, so we need not load any additional library or package. We just need to run the recipe code at the R prompt. We can also save the code as a script to use it later. Here, we will use the metals.csv example dataset again:

metals<-read.csv("metals.csv")

How to do it...

We can build a box plot with custom colors, widths, and styles in the following way:

boxplot(metals[,-1],
border = "white",col = "black",boxwex = 0.3,
medlwd=1, whiskcol="black",staplecol="black",
outcol="red",cex=0.3,outpch=19,
main="Summary of metal concentrations by Site")

grid(nx=NA,ny=NULL,col="gray",lty="dashed")
How to do it...

How it works...

We have used a few different arguments in the example to change the styling of the box plot. The first two are col and border, which set the box color and border color respectively. Note that the border argument also sets the color for the median line, unless it is specified using the medcol argument.

In the example, in addition to using boxwex for adjusting box widths, we used medlwd to set the width of the median line. We set the color of the whiskers and staple using whiskcol and staplecol respectively. The color and symbol type of the outlier points were set using outcol and outpch respectively. The size of the points was set using the cex argument.

There's more...

We can set the color, size, and styling for each of the components. If you type ?bxp at the R prompt, you can see the help section for the bxp() function which is called by boxplot() to do the actual drawing. The following is a summary:

Argument to boxplot()

Corresponding setting

boxlty, boxlwd , boxcol , boxfill

Box outline type, width, color, and fill color

medlty, medlwd , medpch, medcex , medcol , medbg

Median line type, line width, point character, point size expansion, color, and background color

whisklty, whisklwd, whiskcol

Whisker line type, width, and color

staplelty , staplelwd , staplewex , staplecol

Staple line type, width, line width expansion, and color

outlty, outlwd , outwex , outpch , outcex , outcol , outbg

Outlier line type, line width, line width expansion, point character, point size expansion, color, and background color

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset