Learn R Programming

lessR (version 3.5.5)

BoxPlot: Boxplot

Description

Abbreviation: bx Uses the standard R boxplot function, boxplot to display a boxplot in color. Also display the relevant statistics such as the hinges, median and IQR. If the provided object to analyze is a set of multiple variables, including an entire data frame, then each non-numeric variable in the data frame is analyzed and the results written to a pdf file in the current working directory. The name of each output pdf file that contains a bar chart and its path are specified in the output. When output is assigned into an object, such as b in b <- bx(Y), the pieces of output can be accessed for later analysis. A primary such analysis is knitr for dynamic report generation from an R Markdown file in which R output is embedded in documents, facilitated by the Rmd option. See value below.

Usage

BoxPlot(x=NULL, data=mydata, n.cat=getOption("n.cat"),
        Rmd=NULL,

fill=getOption("fill.bar"), stroke=getOption("stroke.bar"), bg=getOption("bg"), grid=getOption("grid"), box=getOption("box"),

cex.axis=0.75, axes="gray30", xlab=NULL, main=NULL, sub=NULL, digits.d=NULL,

rotate.values=0, offset=0.5,

horiz=TRUE, add.points=FALSE,

quiet=getOption("quiet"), width=4.5, height=4.5, pdf=FALSE, fun.call=NULL, …)

bx(…)

Arguments

x
Variable(s) to analyze. Can be a single numerical variable, either within a data frame or as a vector in the user's workspace, or multiple variables in a data frame such as designated with the c function, or an entire data frame. If not specified, then defaults to all numerical variables in the specified data frame, mydata by default.
data
Optional data frame that contains the variable(s) of interest, default is mydata.
n.cat
For the analysis of multiple variables, such as a data frame, specifies the largest number of unique values of variable of a numeric data type for which the variable will be analyzed as a categorical.
Rmd
File name for the file of R markdown instructions to be written, if specified.
fill
Interior color of the box. Turn off with fill="off".
stroke
Color of any points that designate outliers. By default this is the same color as the box.
bg
Color of the plot background. Turn off with bg="off".
grid
Color of the grid lines. Turn off with grid="off".
box
Color of border around the plot background, the box, that encloses the plot. Turn off with box="off".
cex.axis
Scale magnification factor, which by defaults displays the axis values to be smaller than the axis labels. Provides the functionality of, and can be replaced by, the standard R cex.axis.
axes
Color of the font used to label the axis values.
xlab
Label for the value axis, which defaults to the variable's name.
main
Title of graph.
sub
Sub-title of graph, below xlab.
digits.d
Number of decimal digits displayed in the listing of the summary statistics.
rotate.values
Degrees that the axis values are rotated, usually to accommodate longer values, typically used in conjunction with offset.
offset
The amount of spacing between the axis values and the axis. Default is 0.5. Larger values such as 1.0 are used to create space for the label when longer axis value names are rotated.
horiz
Orientation of the boxplot. Set FALSE for vertical.
add.points
If TRUE, then place a dot plot (i.e., stripchart) over the box plot.
quiet
If set to TRUE, no text output. Can change system default with theme function.
width
Width of the plot window in inches, defaults to 4.5.
height
Height of the plot window in inches, defaults to 4.5.
pdf
If TRUE, graphics to be redirected to a pdf file.
fun.call
Function call. Used with knitr to pass the function call when obtained from the abbreviated function call bx.
Other parameter values for graphics as defined processed by boxplot and bxp such as whiskcol for the whisker color, etc. and par, including ylim to set the limits of the value axis, lwd for the line width, cex.lab for the size of the label, color.main for the title, color.lab, sub, color.sub, srt to rotate the axis value labels, and color.ticks to specify the color of the tick marks.

Value

The output can optionally be saved into an R object, otherwise it simply appears in the console. Redesigned in lessR version 3.3 to provide two different types of components: the pieces of readable output, and a variety of statistics. The readable output are character strings such as tables amenable for reading. The statistics are numerical values amenable for further analysis. The motivation of these types of output is to facilitate R markdown documents, as the name of each piece, preceded by the name of the saved object and a $, can be inserted into the Rmd document (see examples). READABLE OUTPUT codeout_stats: Summary statistics for a box plot codeout_outliers: Outlier analysis codeout_file: Name and location of optional R markdown file STATISTICS coden: Number of data values analyzed coden.miss: Number of missing data values codemin: Minimum codelower_whisker: Lower whisker codelower_hinge: Lower hinge codemedian: Median codeupper_hinge: Upper hinge codeupper_whisker: Upper whisker codemax: Maximum codeIQR: Inter-quartile range Although not typically needed, if the output is assigned to an object named, for example, h, then the contents of the object can be viewed directly with the unclass function, here as unclass(h).

Details

OVERVIEW Unlike the standard R boxplot function, boxplot, the default here is for a horizontal boxplot. Also, BoxPlot does not currently process in formula mode, so use the standard R boxplot function to process a formula in which a boxplot is displayed for a variable at each level of a second, usually categorical, variable. Other graphic parameters are available to format the display, such as main for the title, and other parameters found in boxplot and par. To minimize white space around the boxplot, re-size the graphics window before or after creating the boxplot. DATA The data may either be a vector from the global environment, the user's workspace, as illustrated in the examples below, or one or more variable's in a data frame, or a complete data frame. The default input data frame is mydata. Can specify the source data frame name with the data option. If multiple variables are specified, only the numerical variables in the list of variables are analyzed. The variables in the data frame are referenced directly by their names, that is, no need to invoke the standard R mechanisms of the mydata$name notation, the with function or the attach function. If the name of the vector in the global environment and of a variable in the input data frame are the same, the vector is analyzed. To obtain a box plot of each numerical variable in the mydata data frame, use BoxPlot(). Or, for a data frame with a different name, insert the name between the parentheses. To analyze a subset of the variables in a data frame, specify the list with either a : or the c function, such as m01:m03 or c(m01,m02,m03). COLORS Individual colors in the plot can be manipulated with options such as fill for the color of the box. A color theme for all the colors can be chosen for a specific plot with the colors option with the lessR function theme. The default color theme is dodgerblue, but a gray scale is available with "gray", and other themes are available as explained in theme, such as "red" and "green". Use the option ghost=TRUE for a black background, no grid lines and partial transparency of plotted colors. For the color options, such as grid, the value of "off" is the same as "transparent". VARIABLE LABELS If variable labels exist, then the corresponding variable label is by default listed as the label for the horizontal axis and on the text output. For more information, see Read. PDF OUTPUT To obtain pdf output, use the pdf.file option, perhaps with the optional width and height options. These files are written to the default working directory, which can be explicitly specified with the R setwd function. ONLY VARIABLES ARE REFERENCED The referenced variable in a lessR function can only be a variable name. This referenced variable must exist in either the referenced data frame, such as the default mydata, or in the user's workspace, more formally called the global environment. That is, expressions cannot be directly evaluated. For example: > BoxPlot(rnorm(50)) # does NOT work Instead, do the following:
    > Y <- rnorm(50)   # create vector Y in user workspace
    > BoxPlot(Y)     # directly reference Y

References

Gerbing, D. W. (2013). R Data Analysis without Programming, Chapter 5, NY: Routledge.

See Also

boxplot, bxp, par, theme.

Examples

Run this code
# simulate data and get at least one outlier
y <- rnorm(100,50,10)
y[1] <- 90


# ------------------------------
# box plot for a single variable
# ------------------------------

# standard horizontal boxplot with all defaults
BoxPlot(y)

# short name
bx(y)

# save the box plot to a pdf file
BoxPlot(y, pdf=TRUE)

# vertical boxplot with plum color
BoxPlot(y, horiz=FALSE, fill="plum")

# box plot with outliers more strongly highlighted
BoxPlot(y, stroke="red", xlab="My Variable")


# ------------------------------------------------
# box plots for data frames and multiple variables
# ------------------------------------------------

# read internal lessR dataset
# mydata contains both numeric and non-numeric data
mydata <- rd("Employee", format="lessR", quiet=TRUE)

# box plot with superimposed dot plot (stripchart)
BoxPlot(Salary, add.points=TRUE)

# box plot with results saved to object b instead of displaying 
b <- BoxPlot(Salary)
# show the results
b
# show just the piece regarding the statistics
b$out_stats
# list the names of all the components
names(b)

# box plot with rotated axis values, offset more from axis
BoxPlot(Salary, rotate.values=45, offset=1)

# BoxPlot generates R markdown file to be "knit"
#  such as in RStudio
bx(Salary, Rmd="myout")

# box plots for all numeric variables in data frame called mydata
BoxPlot()

# box plots for all numeric variables in data frame called mydata
#  with specified options
BoxPlot(fill="palegreen1", stroke="plum")

# Use the subset function to specify a variable list
# box plots for all specified numeric variables
BoxPlot(c(Salary,Years))

Run the code above in your browser using DataLab