R - Line Graphs
R - Modern Line Graphs with ggplot2
Section titled “R - Modern Line Graphs with ggplot2”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.
Creating a Simple Line Graph
Section titled “Creating a Simple Line Graph”To create a plot with ggplot2, you need three key components:
ggplot(): The main function where you specify the data set.aes(): The aesthetic mappings, which define how variables in your data map to visual properties (like the x-axis, y-axis, color, etc.).- A
geomlayer: 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 mmmonthly_data <- data.frame( month = 1:12, rainfall_mm = c(7, 12, 28, 45, 80, 55, 30, 25, 15, 10, 8, 5))
# Create the plotggplot(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 themeThis 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.
Plotting Multiple Lines
Section titled “Plotting Multiple Lines”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" formatwide_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" formatlong_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 aestheticggplot(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.
Saving your Plot
Section titled “Saving your Plot”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)