Skip to content

R - Line Graphs

A line graph is ideal for visualizing trends in data over time or some other continuous sequence. While base R has the plot() function, the modern, powerful, and recommended approach for creating complex and publication-quality graphics in R is the ggplot2 package.

ggplot2 is based on the Grammar of Graphics, a philosophy that breaks plots down into component parts like data, aesthetic mappings, and geometric layers. This makes it a systematic and flexible tool for visualization.

To create a plot with ggplot2, you need three key components:

  1. ggplot(): The main function where you specify the data set.
  2. aes(): The aesthetic mappings, which define how variables in your data map to visual properties (like the x-axis, y-axis, color, etc.).
  3. A geom layer: The geometric object that defines the type of plot (e.g., geom_line() for a line graph, geom_point() for a scatter plot).
# First, install and load the ggplot2 package (it's part of the tidyverse)
# install.packages("tidyverse")
library(ggplot2)
# Create some sample data: monthly rainfall in mm
monthly_data <- data.frame(
month = 1:12,
rainfall_mm = c(7, 12, 28, 45, 80, 55, 30, 25, 15, 10, 8, 5)
)
# Create the plot
ggplot(data = monthly_data, mapping = aes(x = month, y = rainfall_mm)) +
geom_line()

This code generates a simple line graph. The x-axis represents the month (from 1 to 12) and the y-axis shows the corresponding rainfall. A single line connects the data points in order.

Customizing the Graph: Titles, Labels, and Colors

Section titled “Customizing the Graph: Titles, Labels, and Colors”

You can easily customize your plot by adding more layers. The labs() function is used to add titles and axis labels. To change the appearance of a geom, you set its properties (like color or size) outside of the aes() function.

ggplot(data = monthly_data, mapping = aes(x = month, y = rainfall_mm)) +
geom_line(color = "steelblue", size = 1.5) + # Set static color and size
geom_point(color = "steelblue", size = 3) + # Add points to the line
labs(
title = "Monthly Rainfall in Fictional City",
subtitle = "A seasonal trend is visible",
x = "Month of the Year",
y = "Rainfall (mm)",
caption = "Source: Fictional Weather Service"
) +
theme_minimal() # Apply a clean theme

This code produces a much more polished graph. The line and points are a pleasant ‘steelblue’ blue. The plot has a clear title, subtitle, informative axis labels, and a caption. The theme_minimal() function gives the plot a clean, modern look.

The ggplot2 way to plot multiple lines is not to add them one by one, but to map a categorical variable in your data to the color aesthetic. This requires your data to be in a “long” or “tidy” format, where each observation has its own row.

Let’s compare rainfall for two different cities. First, we’ll create the data and then use tidyr::pivot_longer() to reshape it.

library(tidyr)
# Data for two cities in a "wide" format
wide_data <- data.frame(
month = 1:12,
city_a_rainfall = c(7, 12, 28, 45, 80, 55, 30, 25, 15, 10, 8, 5),
city_b_rainfall = c(90, 85, 60, 40, 25, 15, 10, 12, 20, 35, 65, 80)
)
# Reshape the data to a "long" format
long_data <- wide_data %>%
pivot_longer(
cols = c(city_a_rainfall, city_b_rainfall), # The columns to pivot
names_to = "city", # New column for the old column names
values_to = "rainfall" # New column for the old values
)
# Now, create the plot by mapping the 'city' column to the color aesthetic
ggplot(data = long_data, mapping = aes(x = month, y = rainfall, color = city)) +
geom_line(size = 1) +
labs(
title = "Monthly Rainfall Comparison",
x = "Month",
y = "Rainfall (mm)",
color = "City" # This renames the legend title
) +
theme_light()

This code generates a line chart with two distinct lines, one for each city. ggplot2 automatically assigns different colors to each line and creates a legend to identify which color corresponds to which city. This approach is highly scalable—if you had ten cities, the same code would produce a plot with ten lines.

The best way to save a ggplot is with the ggsave() function. It automatically detects the file type from the extension (e.g., .png, .pdf, .svg) and saves the last plot you displayed.

# This will save the last plot to a file named 'rainfall_comparison.png'
# ggsave("rainfall_comparison.png", width = 8, height = 5)