Creating Graphics with ggplot2
Above, we used the qplot
function to build ggplot2
objects in
one function call. Sometimes, you may need more flexibility than qplot
provides. Alternately, you may want to
write a more verbose description of your plot to make your code easier to
read. To do this, you create your plot in several parts:
You call the
ggplot
function to create a newggplot
object, define the input data, and define aesthetic mappingsYou add layers to the
ggplot
object
Note that you add layers (and options) to a ggplot
object by using the +
operator.
As an example, we could create a plot identical to the one we started with using these statements:
> plt <- ggplot(data=d, mapping=aes(x=a, y=b)) + geom_point() > summary(plt) data: a, b, c [10x3] mapping: x = a, y = b faceting: facet_null() ----------------------------------- geom_point: na.rm = FALSE stat_identity: position_identity: (width = NULL, height = NULL)
To create ggplot
objects without
qplot
, you begin by using the ggplot
function.
ggplot(data, mapping = aes(), ..., environment = globalenv())
Here is a description of the arguments to ggplot2
:
Argument | Description | Default |
---|---|---|
data | The default data frame for the plot | |
mapping | Default list of aesthetic mappings for the plot | aes() |
environment | Environment in which the aesthetics should occur | globalenv() |
... |
The ggplot
function returns a new
ggplot
object with no layers. You can’t
actually print a chart from this object because no layers are
defined:
> ggplot(data=d, mapping=aes(x=a, y=b))
Get R in a Nutshell, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.