The R Project SVN R

Rev

Rev 88767 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
42333 ripley 1
% File src/library/graphics/man/barplot.Rd
68948 ripley 2
% Part of the R package, https://www.R-project.org
89497 ligges 3
% Copyright 1995-2026 R Core Team
42333 ripley 4
% Distributed under GPL 2 or later
5
 
27442 ripley 6
\name{barplot}
56186 murdoch 7
\alias{barplot}
27442 ripley 8
\alias{barplot.default}
76259 maechler 9
\alias{barplot.formula}
27442 ripley 10
\title{Bar Plots}
28517 hornik 11
\description{
88767 maechler 12
  Creates a bar plot with vertical or horizontal bars, stacked or side
13
  by side.
28517 hornik 14
}
27442 ripley 15
\usage{
36139 ripley 16
barplot(height, \dots)
17
 
27442 ripley 18
\method{barplot}{default}(height, width = 1, space = NULL,
19
        names.arg = NULL, legend.text = NULL, beside = FALSE,
20
        horiz = FALSE, density = NULL, angle = 45,
29534 ripley 21
        col = NULL, border = par("fg"),
27442 ripley 22
        main = NULL, sub = NULL, xlab = NULL, ylab = NULL,
34030 maechler 23
        xlim = NULL, ylim = NULL, xpd = TRUE, log = "",
27442 ripley 24
        axes = TRUE, axisnames = TRUE,
25
        cex.axis = par("cex.axis"), cex.names = par("cex.axis"),
34030 maechler 26
        inside = TRUE, plot = TRUE, axis.lty = 0, offset = 0,
88767 maechler 27
        add = FALSE, ann = !add && par("ann"), args.legend = NULL,
28
        orderH = c("none", "incr", "decr"),
89497 ligges 29
        panel.first = NULL, panel.last = NULL,
88767 maechler 30
        \dots)
76259 maechler 31
 
32
\method{barplot}{formula}(formula, data, subset, na.action,
33
        horiz = FALSE, xlab = NULL, ylab = NULL, \dots)
27442 ripley 34
}
35
\arguments{
36
  \item{height}{either a vector or matrix of values describing the
37
    bars which make up the plot.  If \code{height} is a vector, the
38
    plot consists of a sequence of rectangular bars with heights
39
    given by the values in the vector.  If \code{height} is a matrix
40
    and \code{beside} is \code{FALSE} then each bar of the plot
41
    corresponds to a column of \code{height}, with the values in the
42961 ripley 42
    column giving the heights of stacked sub-bars making up the
27442 ripley 43
    bar.  If \code{height} is a matrix and \code{beside} is
44
    \code{TRUE}, then the values in each column are juxtaposed
45
    rather than stacked.}
46
  \item{width}{optional vector of bar widths. Re-cycled to length the
61433 ripley 47
    number of bars drawn.  Specifying a single value will have no
42373 murdoch 48
    visible effect unless \code{xlim} is specified.}
27442 ripley 49
  \item{space}{the amount of space (as a fraction of the average bar
50
    width) left before each bar.  May be given as a single number or
51
    one number per bar.  If \code{height} is a matrix and
52
    \code{beside} is \code{TRUE}, \code{space} may be specified by
53
    two numbers, where the first is the space between bars in the
54
    same group, and the second the space between the groups.  If not
55
    given explicitly, it defaults to \code{c(0,1)} if \code{height}
56
    is a matrix and \code{beside} is \code{TRUE}, and to 0.2
57
    otherwise.}
58
  \item{names.arg}{a vector of names to be plotted below each bar or
59
    group of bars.  If this argument is omitted, then the names are
60
    taken from the \code{names} attribute of \code{height} if this
61
    is a vector, or the column names if it is a matrix.}
62
  \item{legend.text}{a vector of text used to construct a legend for
63
    the plot, or a logical indicating whether a legend should be
64
    included.  This is only useful when \code{height} is a matrix.
65
    In that case given legend labels should correspond to the rows of
66
    \code{height}; if \code{legend.text} is true, the row names of
67
    \code{height} will be used as labels if they are non-null.}
68
  \item{beside}{a logical value.  If \code{FALSE}, the columns of
69
    \code{height} are portrayed as stacked bars, and if \code{TRUE}
70
    the columns are portrayed as juxtaposed bars.}
71
  \item{horiz}{a logical value.  If \code{FALSE}, the bars are drawn
72
    vertically with the first bar to the left.  If \code{TRUE}, the
73
    bars are drawn horizontally with the first at the bottom.}
27625 ripley 74
  \item{density}{a vector giving the density of shading lines, in
27442 ripley 75
    lines per inch, for the bars or bar components.
76
    The default value of \code{NULL} means that no shading lines
77
    are drawn. Non-positive values of \code{density} also inhibit the
78
    drawing of shading lines.}
79
  \item{angle}{the slope of shading lines, given as an angle in
80
    degrees (counter-clockwise), for the bars or bar components.}
29534 ripley 81
  \item{col}{a vector of colors for the bars or bar components.
81393 smeyer 82
    By default, \code{"grey"} is used if \code{height} is a vector, and a
83
    gamma-corrected grey palette if \code{height} is a matrix;
84
    see \code{\link{grey.colors}}.}
39762 murrell 85
  \item{border}{the color to be used for the border of the bars.
86
    Use \code{border = NA} to omit borders.  If there are shading
87
    lines, \code{border = TRUE} means use the same colour for
88
    the border as for the shading lines.}
81315 smeyer 89
  \item{main,sub}{main title and subtitle for the plot.}
27442 ripley 90
  \item{xlab}{a label for the x axis.}
91
  \item{ylab}{a label for the y axis.}
92
  \item{xlim}{limits for the x axis.}
93
  \item{ylim}{limits for the y axis.}
94
  \item{xpd}{logical. Should bars be allowed to go outside region?}
34030 maechler 95
  \item{log}{string specifying if axis scales should be logarithmic; see
96
    \code{\link{plot.default}}.}
27442 ripley 97
  \item{axes}{logical.  If \code{TRUE}, a vertical (or horizontal, if
98
    \code{horiz} is true) axis is drawn.}
99
  \item{axisnames}{logical.  If \code{TRUE}, and if there are
100
    \code{names.arg} (see above), the
61153 ripley 101
    other axis is drawn (with \code{lty = 0}) and labeled.}
77420 kalibera 102
  \item{cex.axis}{expansion factor for numeric axis labels (see
103
    \code{\link{par}('cex')}).}
27442 ripley 104
  \item{cex.names}{expansion factor for axis names (bar labels).}
105
  \item{inside}{logical.  If \code{TRUE}, the lines which divide
106
    adjacent (non-stacked!) bars will be drawn.  Only applies when
107
    \code{space = 0} (which it partly is when \code{beside = TRUE}).}
40281 ripley 108
%MM: we still have "NotYetUsed" -- the above describes S-plus 6.1 (not
27442 ripley 109
% precisely documented!) behavior!
110
  \item{plot}{logical.  If \code{FALSE}, nothing is plotted.}
77420 kalibera 111
  \item{axis.lty}{the graphics parameter \code{lty} (see
112
    \code{\link{par}('lty')}) applied to the axis
27625 ripley 113
    and tick marks of the categorical (default horizontal) axis.  Note
27442 ripley 114
    that by default the axis is suppressed.}
28517 hornik 115
  \item{offset}{a vector indicating how much the bars should be shifted
116
    relative to the x axis.}
34030 maechler 117
  \item{add}{logical specifying if bars should be added to an already
118
    existing plot; defaults to \code{FALSE}.}
76259 maechler 119
  \item{ann}{logical specifying if the default annotation (\code{main},
120
    \code{sub}, \code{xlab}, \code{ylab}) should appear on the plot, see
121
    \code{\link{title}}.}
46980 ripley 122
  \item{args.legend}{list of additional arguments to pass to
46986 ripley 123
    \code{\link{legend}()}; names of the list are used as argument
46980 ripley 124
    names.  Only used if \code{legend.text} is supplied.}
88767 maechler 125
  \item{orderH}{a string, one of \code{"none", "incr", "decr"} (possibly abbreviated).
126
    When (as per default) \code{beside} is false, and stacked bars are
127
    drawn and \code{orderH} is not \code{"none"}, it indicates how the stacks
128
    should be ordered, each via \code{\link{order}(height[..], decreasing = <L>)},
129
    where \code{<L>} is \code{TRUE} or \code{FALSE} when \code{orderH} is
130
    \code{"decr"} or \code{"incr"}, respectively.}
76259 maechler 131
  \item{formula}{a formula where the \code{y} variables are numeric data
132
    to plot against the categorical \code{x} variables.  The formula
77213 hornik 133
    can have one of three forms:
134
    \preformatted{
76259 maechler 135
      y ~ x
136
      y ~ x1 + x2
77213 hornik 137
      cbind(y1, y2) ~ x
138
    }
139
    (see the examples).}
76259 maechler 140
  \item{data}{a data frame (or list) from which the variables in formula
141
    should be taken.}
142
  \item{subset}{an optional vector specifying a subset of observations
143
    to be used.}
144
  \item{na.action}{a function which indicates what should happen when
145
    the data contain \code{\link{NA}} values.  The default is to ignore missing
146
    values in the given variables.}
89497 ligges 147
 
148
  \item{panel.first}{an \sQuote{expression} to be evaluated after the
149
    plot axes are set up but before any plotting takes place.  This can
150
    be useful for drawing background grids. Note that this works by 
151
    lazy evaluation: passing this argument from other functions may 
152
    well not work since it may be evaluated too early.}
153
  \item{panel.last}{an expression to be evaluated after plotting has
154
    taken place but before the axes and title are added.  See the
155
    comments about \code{panel.first}.}
156
 
36139 ripley 157
  \item{\dots}{arguments to be passed to/from other methods.  For the
37119 ripley 158
    default method these can include further arguments (such as
56113 ripley 159
    \code{axes}, \code{asp} and \code{main}) and
160
    \link{graphical parameters} (see \code{\link{par}}) which are passed to
37119 ripley 161
    \code{\link{plot.window}()}, \code{\link{title}()} and
27442 ripley 162
    \code{\link{axis}}.}
163
}
164
\value{
165
  A numeric vector (or matrix, when \code{beside = TRUE}), say
166
  \code{mp}, giving the coordinates of \emph{all} the bar midpoints
167
  drawn, useful for adding to the graph.
168
 
169
  If \code{beside} is true, use \code{colMeans(mp)} for the
170
  midpoints of each \emph{group} of bars, see example.
171
}
88767 maechler 172
\author{R Core, with a contribution by Arni Magnusson, and \code{orderH} by
173
  \enc{François}{Francois} Rebaudo, see also Fig.~3 in
174
  \doi{10.1111/eea.12693}.}
27442 ripley 175
\references{
88581 hornik 176
  \bibshow{R:Becker+Chambers+Wilks:1988}
36222 ripley 177
 
88585 hornik 178
  \bibshow{R:Murrell:2005}
27442 ripley 179
}
180
\seealso{
76259 maechler 181
  \code{\link{plot}(\dots, type = "h")}, \code{\link{dotchart}};
182
  \code{\link{hist}} for bars of a \emph{continuous} variable.
183
  \code{\link{mosaicplot}()}, more sophisticated to visualize
184
  \emph{several} categorical variables.
27442 ripley 185
}
186
\examples{
76259 maechler 187
# Formula method
188
barplot(GNP ~ Year, data = longley)
189
barplot(cbind(Employed, Unemployed) ~ Year, data = longley)
190
 
191
## 3rd form of formula - 2 categories :
192
op <- par(mfrow = 2:1, mgp = c(3,1,0)/2, mar = .1+c(3,3:1))
193
summary(d.Titanic <- as.data.frame(Titanic))
194
barplot(Freq ~ Class + Survived, data = d.Titanic,
195
        subset = Age == "Adult" & Sex == "Male",
80079 hornik 196
        main = "barplot(Freq ~ Class + Survived, *)", ylab = "# {passengers}", legend.text = TRUE)
76259 maechler 197
# Corresponding table :
198
(xt <- xtabs(Freq ~ Survived + Class + Sex, d.Titanic, subset = Age=="Adult"))
199
# Alternatively, a mosaic plot :
200
mosaicplot(xt[,,"Male"], main = "mosaicplot(Freq ~ Class + Survived, *)", color=TRUE)
201
par(op)
202
 
203
 
204
# Default method
41502 ripley 205
require(grDevices) # for colours
61153 ripley 206
tN <- table(Ni <- stats::rpois(100, lambda = 5))
88436 maechler 207
## barplot() returns x-locations:
61153 ripley 208
r <- barplot(tN, col = rainbow(20))
88436 maechler 209
lines(r, tN, type = "h", col = 2, lwd = 7) # type "h" plot *is* 'bar'plot
27442 ripley 210
 
88436 maechler 211
## draw axis separately  using x-locations from barplot():
61153 ripley 212
barplot(tN, space = 1.5, axisnames = FALSE,
88436 maechler 213
        sub = "barplot(..., space= 1.5, axisnames = FALSE)"
214
       ) |> axis(1, at = _, labels = paste("# :", tN), cex.axis = 3/4)
27442 ripley 215
 
216
barplot(VADeaths, plot = FALSE)
217
barplot(VADeaths, plot = FALSE, beside = TRUE)
218
 
219
mp <- barplot(VADeaths) # default
220
tot <- colMeans(VADeaths)
221
text(mp, tot + 3, format(tot), xpd = TRUE, col = "blue")
222
barplot(VADeaths, beside = TRUE,
223
        col = c("lightblue", "mistyrose", "lightcyan",
224
                "lavender", "cornsilk"),
80079 hornik 225
        legend.text = rownames(VADeaths), ylim = c(0, 100))
27442 ripley 226
title(main = "Death Rates in Virginia", font.main = 4)
227
 
228
hh <- t(VADeaths)[, 5:1]
229
mybarcol <- "gray20"
230
mp <- barplot(hh, beside = TRUE,
231
        col = c("lightblue", "mistyrose",
232
                "lightcyan", "lavender"),
80079 hornik 233
        legend.text = colnames(VADeaths), ylim = c(0,100),
27442 ripley 234
        main = "Death Rates in Virginia", font.main = 4,
235
        sub = "Faked upper 2*sigma error bars", col.sub = mybarcol,
236
        cex.names = 1.5)
237
segments(mp, hh, mp, hh + 2*sqrt(1000*hh/100), col = mybarcol, lwd = 1.5)
61168 ripley 238
stopifnot(dim(mp) == dim(hh))  # corresponding matrices
27442 ripley 239
mtext(side = 1, at = colMeans(mp), line = -2,
240
      text = paste("Mean", formatC(colMeans(hh))), col = "red")
241
 
242
# Bar shading example
243
barplot(VADeaths, angle = 15+10*1:5, density = 20, col = "black",
80079 hornik 244
        legend.text = rownames(VADeaths))
27442 ripley 245
title(main = list("Death Rates in Virginia", font = 4))
246
 
76259 maechler 247
# Border color
27442 ripley 248
barplot(VADeaths, border = "dark blue") % lwd = 2 << not passed
61153 ripley 249
%notyet barplot(VADeaths, inside = FALSE, main = "barplot(*, inside = FALSE)")
34030 maechler 250
 
76259 maechler 251
# Log scales (not much sense here)
61153 ripley 252
barplot(tN, col = heat.colors(12), log = "y")
253
barplot(tN, col = gray.colors(20), log = "xy")
46980 ripley 254
 
76259 maechler 255
# Legend location
46980 ripley 256
barplot(height = cbind(x = c(465, 91) / 465 * 100,
257
                       y = c(840, 200) / 840 * 100,
258
                       z = c(37, 17) / 37 * 100),
259
        beside = FALSE,
260
        width = c(465, 840, 37),
261
        col = c(1, 2),
262
        legend.text = c("A", "B"),
263
        args.legend = list(x = "topleft"))
88767 maechler 264
 
265
% better example ?
266
## Using 'orderH' to sort the "stacks" (each separately)
267
set.seed(1234)
268
mydat <- matrix(rlnorm(4*13, sdlog=1/2), ncol = 13,
269
                dimnames = list(NULL, LETTERS[1:13]))
270
myCol <- c("#1B9E77", "#D95F02", "#7570B3", "#E7298A")
271
barplot(mydat, col=myCol)
272
barplot(mydat, col=myCol, orderH = "decr", main= "orderH = 'decr'")
273
barplot(mydat, col=myCol, orderH = "incr", main= "orderH = 'incr'")
27442 ripley 274
}
275
\keyword{hplot}