bc
Plots a bar chart, such as for counts, with default colors for one or two variables, including background color and grid lines, from a variety of different types of data. For two variables a legend is provided. Also displays the frequency table for one or two variables, Cramer's V association, and the corresponding chi-square inferential analysis. For two variables, the frequencies include the joint and marginal frequencies. Unlike the standard R function, barplot
, the variable(s) can be entered directly into the function call without first converting to a table.
If the provided object to analyze is a set of multiple variables, including an entire data frame, then a bar chart is calculated for each non-numeric variable in the data frame 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.
BarChart(x=NULL, by=NULL, data=mydata, n.cat=getOption("n.cat"), col.fill=NULL, col.stroke=getOption("col.stroke.bar"),
col.bg=getOption("col.bg"),
col.grid=getOption("col.grid"),
random.col=FALSE,
colors=c("rainbow", "terrain", "heat"),
horiz=FALSE, over.grid=FALSE, addtop=0.05,
gap=NULL, prop=FALSE,
xlab=NULL, ylab=NULL, main=NULL,
cex.axis=0.75, col.axis="gray30",
value.labels=NULL, rotate.values=0, offset=0.5,
beside=FALSE, col.low=NULL, col.hi=NULL, count.labels=NULL,
legend.title=NULL, legend.loc="right.margin", legend.labels=NULL,
legend.horiz=FALSE,
quiet=getOption("quiet"),
pdf.file=NULL, pdf.width=5, pdf.height=5, ...)
bc(...)
c
fumydata
."heat"
, "rainbow"
and "terrain"
.TRUE
, randomizes the order
of the colors within the chosen color palette, when the second variable is
not ordered, otherwise is ignored. Each analysis generally yields different
colors of the TRUE
.TRUE
, plot the grid lines over the histogram.horiz=FALSE
, in the same scale as the vertical axis, puts
more space between the bars and the top of the plot area, usually to
accommodate the legend when plotting two variables. now a multiplicative
factor instead ospace
option from
the standard R barplot
function with a default of 0.2 unless two
variables are plotted and beside=TRUE
,horiz=TRUE
. Defaults
to variable name.NULL
), then the
value.labels are set to the factooffset
.TRUE
for the levels of the
first variable to be plotted as adjacent bars instead of stacked on each other.x
has values that are counts, already tabulated. The
specified variable here contains the names of the levels of x.
by
variable.TRUE
, no text output. Can change system default with
set
function.barplot
, chisq.test
and, for two variables, legend
. Horizontal bar charts, specified by horiz=TRUE
, list the value labels horizontally and automatically extend the left margin to accommodate both the value labels and the variable label. The form of the entered data, the first variable x and optionally a second variable, y, is flexible. The data may be entered as factors, numeric values, characters, or a matrix. The data may be entered and the resulting frequencies computed, or the frequencies can be entered directly. The most natural type of data to enter, when entering the variables, is to enter factors. Plus, the bar colors for a second variable which is an ordered factor are also ordered in a corresponding progression.
DATA
The data may either be a vector from the global environment, the user's workspace, as illustrated in the examples below, or a variable in a data frame. The default input data frame is mydata
. Specify a different data frame name with the data
option. Regardless of its name, 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 vector in the global environment and of a variable in the input data frame are the same, the vector is analyzed. If two variables are specified, both variables should be in the data frame, or one of the variables is in the data frame and the other in the global environment.
To obtain a bar chart of each numerical variable in the mydata
data frame, invoke Bar chart()
. 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 variable list with either a : or the c
function, such as m01:m03 or c(m01,m02,m03).
COLORS
For a one variable plot, the color of the bars is set by the current color theme according to the function set
, which includes the default color theme dodgerblue
. When two variables are plotted, a set of arbitrary colors represent the various levels of the second variable. Transparency effects are only incorporated for a one variable bar plot in a single color.
There are three ways to override the default colors.
1. There are two pre-defined color palettes, each with 7 colors. Three more built-in R color palettes are also available by setting colors
to one of "rainbow"
, "heat"
and "terrain"
. The most vivid of all the palettes is "rainbow"
.
2. The order of the colors within the chosen palette can be randomized with the random.col="TRUE"
option. For example, when this option is activated each of the seven colors in a palette has a 1/7 chance of appearing as the first color, the only color used in the plot of a single variable, and the color used for the first bar in each group for a plot of two variables. When invoked for a color="gray"
, the order from light to dark will generally be lost, which may be desirable if the categories do not represent an ordered factor.
3. The desired colors can be explicitly specified with the col.bars
option, which overrides any other bar color options. When plotting one variable, include one color in this color list, the color used for all of the bars. When plotting two variables, usually the list of colors includes the same number of elements as the number of levels for the second variable. As always with R, if the list includes more than once color, the c
function must be used to generate the list, as in
col.bars=c("coral3","seagreen3")
for a second variable with two levels. When two variables are plotted, if there are fewer specified colors than the levels of the second variable, the remaining colors are selected from the remaining colors in the activated palette.
The default colors in one of the two provided color palettes can be viewed, in the order in which they are displayed, by running the corresponding two lines of R code, for the default colors: clr <- c("slategray3", "bisque3", "darksalmon", "darkolivegreen3", "thistle", "azure3", "moccasin") barplot(rep(1,7), names=clr, col=clr, border=NA, space=.1)
When plotting one ordered factor, or when plotting two variables, and the second variable is an ordered factor, then neither of the two standard color palettes are used. Instead, the resulting bar colors for each level of the ordered factor are also ordered in a progression of colors. The default progression is based on the first color of either the regular or gray color palettes, but this can be changed with the col.low
and col.hi
options, or individually specify the color of each bar with the col.bars
option. A specified palette can, for example, be from light to dark of the same hue, or from a light color of one hue to a dark color of another hue. Each color value can be specified with a color name, or with a specification with the rgb
function. See the examples below.
The showColors
function in this package provides, for each color: name, sample color swatch, and corresponding rgb specification. For a very small number of levels, such as two, it is may be desirable to specify the low and high values to not be closer to each other than the default values.
LEGEND
When two variables are plotted, a legend is produced, with values for each level of the second or by
variable. By default, the location is placed in the right margin of the plot. This position can be changed with the legend.loc
option, which, in addition to the lessR
option of right.margin
, accepts any valid value consistent with the standard R legend
function, used to generate the legend.
If the default right margin is retained, variable labels are also accommodated for the legend title. To conserve horizontal space, the variable label is listed in multiple lines if needed. The legend title is constructed by forming lines of maximum length of 12 characters, with multiple words per line if possible. Any single word in the label of more than 12 characters is abbreviated to 12 characters with the R abbreviate
function. Also, any value labels are abbreviated to a maximum of 6 characters.
If the legend is not in the right margin, sometimes bars from the graph may intrude into the legend. One response is to re-run the analysis with the legend in a new location. Another response is to invoke the addtop
option to place more space between the top bar in the graph and the top of the graph. This option only applies for the default vertical bars. Also, the legend is displayed vertically by default, but can be changed to horizontal with the legend.horiz
option.
ENTER COUNTS DIRECTLY
Instead of calculating the counts from the data, the counts can be entered directly. For two variables, enter the counts as a matrix and include the xlab
option to label the horizontal axis, such as with the name of the variable. Also include the legend.title
option to provide a legend. See the examples below.
Or, include the already tabulated counts as the data which is read into R. If count.labels
is not NULL
, then it is presumed to be a valid variable name. As such, it indicates that the primary variable, x
consists of values already tabulated, that is, counts, and is ready to be plotted directly. The value for count.labels
specifies the label for each level of x
.
STATISTICS In addition to the barchart, descriptive and optional inferential statistics are also presented. First, the frequency table for one variable or the joint frequency table for two variables is displayed. Second, the corresponding Cramer's V and chi-square test are also displayed by default.
VARIABLE LABELS
If variable labels exist, then the corresponding variable label is listed as the label for the horizontal axis unless xlab is specified in the function call. If there are two variables to plot, the title of the resulting plot is based on the two variable labels, unless a specific title is listed with the main
option. The variable label is also listed in the text output, next to the variable name. If the analysis is for two variables, then labels for both variables are included.
PDF OUTPUT
Because of the customized graphic windowing system that maintains a unique graphic window for the Help function, the standard graphic output functions such as pdf
do not work with the lessR
graphics functions. Instead, to obtain pdf output, use the pdf.file
option, perhaps with the optional pdf.width
and pdf.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 (or list of variable names). 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:
> BarChart(cut(rnorm(50), breaks=seq(-5,5))) # does NOT work}
Instead, do the following: > Y <- cut(rnorm(50), breaks=seq(-5,5)) # create vector Y in user workspace > BarChart(Y) # directly reference Y
freq
and prop
. If two categorical variables are analyzed, then nothing is returned.
[object Object],[object Object]
# Pain is an ordered factor, Gender is an unordered factor # Place in data frame mydata to simulate reading with rad Pain <- sample(c("None", "Some", "Much", "Massive"), size=25, replace=TRUE) Pain <- factor(Pain, levels=c("None", "Some", "Much", "Massive"), ordered=TRUE) Gender <- sample(c("Male", "Female"), size=25, replace=TRUE) Gender <- factor(Gender) mydata <- data.frame(Pain, Gender) rm(Pain); rm(Gender)
# -------------------------------------------- # barchart from the data for a single variable # --------------------------------------------
# for each level of Pain, display the frequencies # Pain is an ordered factor, so the bar colors are ordered BarChart(Pain) # short name bc(Pain) # save and then display the frequencies for later analysis myCount <- BarChart(Pain) myCount # rotate and offset the axis labels BarChart(Pain, rotate.values=45, offset=1) # compare to standard R bar plot, which requires mydata$ reference barplot(table(mydata$Pain))
# Gender is unordered, so one color used for all the bars BarChart(Gender)
# column proportions instead of frequencies BarChart(Gender, prop=TRUE)
# specify a unique bar color for each of the two bars BarChart(Gender, col.fill=c("palegreen3","tan"))
# automatically provide horizontal value labels # and adjust left margin as needed BarChart(Pain, horiz=TRUE)
# ---------------------------------------- # barchart from the data for two variables # ----------------------------------------
# at each level of Pain, show the frequencies of the Gender levels BarChart(Pain, by=Gender)
# at each level of Pain, show the row proportions of the Gender levels BarChart(Pain, Gender, prop=TRUE)
# at each level of Gender, show the frequencies of the Pain levels # Pain levels are ordered, so the corresponding colors are also ordered # color theme set to gray theme(colors="gray") BarChart(Gender, by=Pain) theme(colors="sienna")
# specify an ordered blue palette of colors for the ordered levels of Pain # only works when the variable is an ordered factor # colors can be named or customized with rgb function BarChart(Gender, by=Pain, col.low="azure", col.hi=rgb(100,110,200,max=255))
# define custom color gradient within each group of bars # applies to both ordered and unordered factors BarChart(Gender, by=Pain, col.fill=c("thistle1","thistle2","thistle3","thistle4"))
# display bars beside each other instead of stacked, Female and Male # the levels of Pain are included within each respective bar BarChart(Gender, by=Pain, beside=TRUE, legend.horiz=TRUE)
# horizontal bar chart of two variables, put legend on the top BarChart(Gender, by=Pain, horiz=TRUE, legend.loc="top")
# many options, including those from par: col.main, col.axis, col.lab, cex.lab # for more info on these graphic options, enter: help(par) BarChart(Pain, by=Gender, col.fill=c("coral3","seagreen3"), legend.loc="topleft", legend.labels=c("Girls", "Boys"), xlab="Pain Level", main="Gender for Different Pain Levels", col.bg="wheat1", col.grid="wheat3", col.main="wheat4", col.axis="wheat4", col.lab="wheat4", cex.lab=1.2)
# --------------------------------------------- # multiple bar charts across multiple variables # ---------------------------------------------
# bar charts for all non-numeric variables in the data frame called mydata # and all numeric variables with a small number of values, < n.cat BarChart()
# specify a list of variables mydata <- Read("Employee", format="lessR", quiet=TRUE) BarChart(c(Dept, Gender))
# ---------------------------- # can enter many types of data # ----------------------------
# generate and enter integer data X1 <- sample(1:4, size=100, replace=TRUE) X2 <- sample(1:4, size=100, replace=TRUE) BarChart(X1) BarChart(X1,X2)
# generate and enter type double data X1 <- sample(c(1,2,3,4), size=100, replace=TRUE) X2 <- sample(c(1,2,3,4), size=100, replace=TRUE) BarChart(X1) BarChart(X1, by=X2)
# generate and enter character string data # that is, without first converting to a factor Travel <- sample(c("Bike", "Bus", "Car", "Motorcycle"), size=25, replace=TRUE) BarChart(Travel, horiz=TRUE)
# ------------------------------ # bar chart directly from counts # ------------------------------
# barchart of one variable with three levels # enter counts as a vector with the combine function, c # must supply the level names and variable name Dept <- c(5,6,4,6,15) names(Dept) <- c("ACCT", "ADMIN", "FINC", "MKTG", "SALE") BarChart(Dept)
# counts are in the data table to be read directly mydata <- read.csv(text=" Dept, Count ACCT,5 ADMN,6 FINC,4 MKTG,6 SALE,15", header=TRUE) # use count.labels to indicate the label for each corresponding count BarChart(Count, count.labels=Dept)
# barchart of two variables
# two Quality levels, the rows
# three Supplier levels, the columns
# enter counts row by row, then form the table with rbind function
# must supply the level (value) names and the variable names
# chart presented as Row Variable, analyzed at each level of Column Variable
row1 <- c(19, 16, 23)
row2 <- c(6, 6, 8)
mytable <- rbind(row1, row2)
rownames(mytable) <- c("Pass", "Defective")
colnames(mytable) <- c("Acme Inc", "Nuts Inc", "Bolts Inc")
BarChart(mytable, xlab="Supplier", legend.title="Quality")