How can I plot two lines in ggplot2? Can you provide examples?

GGplot2 is a widely used data visualization package in the R programming language. It offers a variety of options for creating high-quality graphs and charts. One common task is plotting two lines on the same graph using ggplot2. This can be achieved by specifying two separate data sets and using the “geom_line” function to plot each line. Additionally, the “aes” function can be used to customize the appearance of the lines. Some examples of how to plot two lines in ggplot2 can be found in the package’s documentation or online tutorials.

Plot Two Lines in ggplot2 (With Examples)


You can use the following basic syntax to plot two lines in one graph using :

ggplot(df, aes(x = x_variable)) + 
  geom_line(aes(y = line1, color = 'line1')) + 
  geom_line(aes(y = line2, color = 'line2'))

The following examples show how to use this syntax in practice.

Example 1: Basic Plot with Two Lines in ggplot2

Suppose we have the following data frame in R:

#create data frame
df <- data.frame(day = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
                 sales = c(8, 8, 7, 6, 7, 8, 9, 12, 14, 18),
                 customers = c(4, 6, 6, 4, 6, 7, 8, 9, 12, 13))

#view first six rows of data frame
head(df)

  day sales customers
1   1     8         4
2   2     8         6
3   3     7         6
4   4     6         4
5   5     7         6
6   6     8         7  

The following code shows how to create a basic plot in ggplot2 with two lines to represent the total sales and customers during this 10-day period:

library(ggplot2)

#create plot with two lines
ggplot(df, aes(x = day)) + 
  geom_line(aes(y = sales, color = 'sales')) + 
  geom_line(aes(y = customers, color = 'customers'))

The x-axis displays the day and the y-axis displays the values for the sales and the customers each day.

Example 2: Custom Plot with Two Lines in ggplot2

The following code shows how to create the same plot as the previous example with a custom title, labels, colors, line thickness, and theme:

library(ggplot2)

ggplot(df, aes(x = day)) + 
  geom_line(aes(y = sales, color = 'sales'), lwd=2) + 
  geom_line(aes(y = customers, color = 'customers'), lwd=2) +
  scale_color_manual('Metric', values=c('red', 'steelblue')) +
  labs(title = 'Sales & Customers by Day', x = 'Day', y = 'Amount') +
  theme_minimal()

Plot of two lines in ggplot2

Note that we chose to use theme_minimal() for this plot, but there are a variety of themes you can use for your plot. Refer to for a complete list of ggplot2 themes.

Additional Resources

The following tutorials explain how to perform other common plotting functions with lines in ggplot2:

x