Graphics Reference
In-Depth Information
A2 B2
11
A3 B1
12
A3 B2
6
This represents the same information, but with a different structure. There are advantages and
disadvantages to the long format, but on the whole, I find that it makes things simpler when deal-
ing with complicated data sets. See Recipes and for information about converting between wide
and long data formats.
To make the first grouped bar graph (
Figure A-4
), we first have to load the ggplot2 library. Then
we tell it to map
Aval
to the xposition with
x=Aval
, and
Bval
to the fill color with
fill=Bval
.
This will make the As run along the x-axis and the Bs determine the grouping. We also tell it to
map
value
to the yposition, or height, of the bars, with
y=value
. Finally, we tell it to draw bars
with
geom_bar()
(don't worry about the other details yet; we'll get to those later):
library(ggplot2)
ggplot(simpledat_long, aes(x
=
Aval, y
=
value, fill
=
Bval))
+
geom_bar(stat
=
"identity"
, position
=
"dodge"
)
Figure A-4. A bar graph made with ggplot() and geom_bar()
To switch things so that the Bs go along the x-axis and the As determine the grouping (
Fig-