Learn

Before we teach you how to add aesthetics specific to a geom layer, let’s create our first geom! As mentioned before, geometries or geoms are the shapes that represent our data.

In ggplot, there are many types of geoms for representing different relationships in data. You can read all about each one in the layers section of the ggplot2 documentation. Once you learn the basic grammar of graphics, all you’ll have to do is read the documentation of a particular geom and you’ll be prepared to make a plot with it following the general pattern. For simplicity’s sake, let’s start with the scatterplot geom, or geom_point(), which simply represents each datum as a point on the grid. Scatterplots are great for graphing paired numerical data or to detect a correlation between two variables.

The following code adds a scatterplot layer to the visualization:

viz <- ggplot(data=df, aes(x=col1,y=col2)) + geom_point()

In the code above:

  • Notice the layer is being added by using a + sign which comes after the ggplot object is created, and it comes on the same line.
  • The geom_point() function call is what adds the points layer to the plot. This call can take arguments but we are keeping it simple for now.

The code above would render the following plot: Scatterplot one layer

Another popular layer that allows you to eye patterns in the data by completing a line of best fit is the geom_smooth() layer. This layer, by nature, comes with a gray error band. You could add a smooth layer to the plot by typing the following:

viz <- ggplot(data=df, aes(x=col1,y=col2)) + geom_point() + geom_smooth()
  • Notice that you can add layers one on top of the other. We added the smooth line after adding the geom_point() layer. We could have just included the point layer, or just the line-of-best-fit layer. But the combination of the two enhances our visual understanding of the data, so they make a great pairing.
  • It is nice to put each layer on its own line although it is not necessary, since it improves readability in the long run if you’re collaborating with other people.

The code above would render the following plot: Plot two layers with smooth line

Instructions

1.

Add a scatter plot of the data to the viz ggplot object by using the geom_point() layer.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?