How to Remove Duplicate Data in R
How to Change Plot Options in R
How to Use Data Tables in R

How to Use Layers in ggplot2 in R

The basic concept of a ggplot2 graphic in R is that you combine different elements into layers. Each layer of a ggplot2 graphic contains information about the following:

  • The data that you want to plot: For ggplot(), this must be a data frame.

  • A mapping from the data to your plot: This usually is as simple as telling ggplot() what goes on the x-axis and what goes on the y-axis.

  • A geometric object, or geom in ggplot terminology: The geom defines the overall look of the layer (for example, whether the plot is made up of bars, points, or lines).

  • A statistical summary, called a stat in ggplot: This describes how you want the data to be summarized (for example, binning for histograms, or smoothing to draw regression lines).

That was a mouthful. In practice, you describe all this in a short line of code. For example, here is the ggplot2 code to plot the faithful data using two layers.The first layer is a geom that draws the points of a scatterplot; the second layer is a stat that draws a smooth line through the points.

image0.jpg
> ggplot(faithful, aes(x=eruptions, y=waiting)) + geom_point() + stat_smooth()
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
How to Create Subgroups of Data in R
How to Define the Data Display Mode in R
How to Install and Load CRAN Packages in R
How to Install, Load, and Unload Packages in R
How to Get Your Data Out of R
Advertisement

Inside Dummies.com