Line Chart Overview
A line chart displays a set of points connected by line segments.
Line charts are commonly used to display changes over time.
Code: line chart in R (ggplot)
Below, is some simple code to create a line chart in R using the ggplot2 package. To do this, you’ll need to have R and ggplot2 installed. If you don’t have R set up and installed, enter your name and email in the sidebar on the right side of the page and we’ll send you a pdf to help you get set up.
Here’s the code to create a simple line chart in R.
# Load ggplot2 graphics package library(ggplot2) # Create dummy dataset df.dummy_data <- data.frame( dummy_metric <- cumsum(1:20), date = seq.Date(as.Date("1980-01-01"), by="1 year", length.out=20) ) # Plot the data using ggplot2 package ggplot(data=df.dummy_data, aes(x=date,y=dummy_metric)) + geom_line()
In the above code, we’re creating a data frame with a sequence of dates (the “date” variable) and random, increasing data (“dummy metric”). (Don’t worry too much about how the dataset is created here. We’ll focus on plotting.)
Let’s look at the plotting code, line-by-line:
Here, we’re calling the ggplot function. With the first argument,
The next piece,
Next we add line geoms (i.e., the type of geometric objects were plotting):
This piece of code is the part that actually does the plotting. And in this case, we’re specifying that we want to plot lines. When we use the line geom, ggplot creates line segments connecting our plotted data points (although, notice that it doesn’t plot the points themselves.)
If we wanted, we could plot other geoms instead of lines. And actually, we can plot them both at the same time. To illustrate this, we’ll make a quick modification to the code by adding another line of code:
That would give us the following plotting code:
ggplot(data=df.dummy_data, aes(x=date,y=dummy_metric)) + geom_line() + geom_point()
Which produces the following plot:
Notice that this chart is almost exactly the same as the first line chart above, except we have added points. (To learn more about
Okay, take one more look at the code:
geom_line() + geom_point()
In these two lines of code, we first plot line segments with
More technically, one would say that we added two layers. The line segments are one layer and the points are another layer.
Ggplot allows you to add multiple layers. If you want to have just lines, you plot lines with
Keep in mind that we aren’t restricted to just two layers. We can add more layers to generate more sophisticated plots.
This is another property that makes the ggplot2 library extremely powerful, and we’ll cover layering strategies in other blog posts.
Do you have a question about this? Leave a comment below.