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 new ggplot
object,
define the input data, and define aesthetic mappings
You 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))
Error: No layers in plot
Typically, you specify aesthetic mappings with the aes
function:
aes(x, y, ...)
The x
argument specifies the x
value, the y
argument specifies the y
value, and other arguments specify aesthetics to map as name/value pairs.
See the documentation for ggplot2
for
alternate ways to map aesthetics including aes_string
and aes_auto
. As an example, to finish specifying a
plot, you need to add layers. You can create a new layer with the layer
function:
layer(...)
You specify the geometric objects using short names like "point"
. Using our earlier example, we could
define our plot object with:
> plt <- ggplot(data=d, mapping=aes(x=a, y=b)) + layer("point")
The layer function allows you to specify geometric objects as name
value pairs. You do not need to specify the full function name, but simply
need to part after geom_
.
For reference, here is a description of the available geometric functions:
Geometric Function | Description |
---|---|
geom_abline | A line, specified by a slope and intercept |
geom_area | Area plot (a continuous analog to a bar plot) |
geom_bar | Bar plot |
geom_bin2d | Heatmap of two-dimensional bins |
geom_blank | Blank geometric object; doesn’t draw anything |
geom_boxplot | Box plot |
geom_contour | Contour plot |
geom_crossbar | Crossbar plot (like a box plot, but without the whiskers and extreme values) |
geom_density | Density plot |
geom_density2d | Two-dimensional density plot |
geom_errorbar | Error bars (typically added to other plots like bar plots, point plots, and line plots) |
geom_errorbarh | Horizontal error bars |
geom_freqpoly | Frequency polygon (similar to a histogram) |
geom_hex | Hexagonal objects (typically used with hexagonal binning) |
geom_histogram | Histogram |
geom_hline | A horizontal line |
geom_jitter | Points, automatically jittered |
geom_line | A line |
geom_linerange | An interval represented by a vertical line |
geom_path | A geometric path, connecting a set of points in order |
geom_point | Points |
geom_pointrange | A vertical line with a point in the middle (related to crossbars, boxplots, and line-ranges) |
geom_polygon | A polygon |
geom_quantile | A set of quantile lines from a quantile regression |
geom_rect | Two-dimensional rectangles |
geom_ribbon | A ribbon (a y range with continuous x values, like Tufte’s famous Napoleon’s march plot) |
geom_rug | A rug |
geom_segment | Line segments |
geom_smooth | A smoothed condition mean |
geom_step | A stepped plot connecting points |
geom_text | Text |
geom_tile | Tiles |
geom_vline | Vertical line |
ggplot2
includes some convenience
functions for applying a statistical transformation and adding a layer to
a plot. Some of these functions are listed below.
Statistic Function | Description |
---|---|
stat_abline | Adds a line with a slope and intercept. |
stat_bin | Splits data into bins then plots as a histogram. |
stat_bin2d | Shows density across two dimensions using rectangles. |
stat_binhex | Shows density across two dimensions using hexagons. |
stat_boxplot | Creates a box-and-whiskers plot. |
stat_contour | Shows contours of three-dimensional data. |
stat_density | Plots density. |
stat_density2d | Plots density in two dimensions. |
stat_function | Superimposes a function. |
stat_hline | Adds a horizontal line. |
stat_identity | Plots data without a statistical transformation. |
stat_qq | Calculations for a quantile-quantile plot. |
stat_quantile | Continuous quantiles. |
stat_smooth | Adds a smoother. |
stat_spoke | Plots directional data at points (specifying location with x and y, and angle separately). |
stat_sum | Plots sums of unique values (typically on a scatter plot). |
stat_summary | Plots summarized data. |
stat_unique | Plots only unique values (removes duplicates). |
stat_vline | Plots a vertical line. |
You can manually specify different scales with ggplot2
; mapping data to different scales lets
you control how ggplot2
shows different
densities, quantities, or other values. Scales can specify ranges of
colors, objects, or labels. The following table shows some of these scale
functions :
Scale function | Description |
---|---|
scale_alpha | Alpha channel values (grayscale). |
scale_brewer | Colors derived from scales shown on colorbrewer.org. |
scale_continuous | Continuous scales. |
scale_date | Dates. |
scale_datetime | Dates and times. |
scale_discrete | Discrete values. |
scale_gradient | Smooth gradients between two colors. |
scale_gradient2 | Smooth gradients among three colors. |
scale_gradientn | Smooth gradients among n colors. |
scale_grey | Grayscale colors. |
scale_hue | Evenly spaced hues. |
scale_identity | Uses values without scaling. |
scale_linetype | Shows differences as line patterns. |
scale_manual | Manually created discrete scales. |
scale_shape | Different shapes (“glyphs”) for different values. |
scale_size | Shows different values as different size objects. |
With ggplot2
, you can plot data
using several different coordinate systems:
Coordinate function | Description |
---|---|
coord_cartesian | Cartesian coordinates |
coord_equal | Equal scale coordinates |
coord_flip | Flipped Cartesian coordinates |
coord_map | Map projections |
coord_polar | Polar projections |
coord_trans | Transformed Cartesian coordinates |
There are two options for faceting data bundled with the ggplot2
package:
Faceting function | Description |
---|---|
facet_grid | Lay out panels in a grid |
facet_wrap | Wraps a one-dimensional list of facets into two dimensions |
When you are plotting multiple geometric objects (such as multiple bars), you can specify where different objects should be plotted.