Graphics Reference
In-Depth Information
Building a Simple Graph
Ggplot2 has a simple requirement for data structures: they must be stored in data frames, and
each type of variable that is mapped to an aesthetic must be stored in its own column. In the
simpledat examples we looked at earlier, we first mapped one variable to the x aesthetic and
another to the fill aesthetic; then we changed the mapping specification to change which vari-
able was mapped to which aesthetic.
We'll walk through a simple example here. First, we'll make a data frame of some sample data:
dat <- data.frame(xval = 1 : 4 , yval = c( 3 , 5 , 6 , 9 ), group = c( "A" , "B" , "A" , "B" ))
dat
xval yval group
1
3
A
2
5
B
3
6
A
4
9
B
A basic ggplot() specification looks like this:
ggplot(dat, aes(x = xval, y = yval))
This creates a ggplot object using the data frame dat . It also specifies default aestheticmap-
pingswithin aes() :
x=xval maps the column xval to the xposition.
y=yval maps the column yval to the yposition.
After we've given ggplot() the data frame and the aesthetic mappings, there's one more critical
component: we need to tell it what geometricobjectsto put there. At this point, ggplot2 doesn't
know if we want bars, lines, points, or something else to be drawn on the graph. We'll add
geom_point() to draw points, resulting in a scatter plot:
ggplot(dat, aes(x = xval, y = yval)) + geom_point()
Search WWH ::




Custom Search