How to Plot Two Lines in ggplot2

How to Plot Two Lines in ggplot2, Are you struggling to create a dual-axis plot in ggplot2? Look no further!

This comprehensive guide will walk you through the basic syntax and provide examples of how to plot two lines in one graph using ggplot2.

The Basic Syntax

To plot two lines in one graph using ggplot2, you can use the following basic syntax:

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

Example 1: Basic Plot with Two Lines

Suppose you have a data frame in R that contains sales and customer data for a 10-day period:

Machine Learning Archives » Data Science Tutorials

# 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)

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

In this example, the x-axis displays the day and the y-axis displays the values for the sales and customers each day.

Example 2: Custom Plot with Two Lines

You can customize your plot by adding a title, labels, colors, line thickness, and theme. Here’s an example:

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()

In this example, we’ve added a custom title and labels to the x-axis and y-axis. We’ve also changed the colors of the lines to red and steel blue.

Additionally, we’ve increased the line thickness using the lwd argument.

Conclusion

Plotting two lines in ggplot2 is a straightforward process that requires only a few lines of code.

By using the geom_line function and customizing your plot with titles, labels, colors, and themes, you can create a wide range of visualizations that help you communicate complex data insights effectively.

Statistical Analysis» Statistics Methods » Quick Guide » finnstats

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

five − four =