ggplot2 Line Graph in R: Complete Guide with Examples
This practical ggplot2 line graph tutorial shows how to create clear line charts in R, from simple time-series plots to multiple-series comparisons, step lines, fitted regression trends, polynomial curves, smoothers and uncertainty bands. Follow the examples, inspect the charts and download practice datasets.
This lesson is part of the ggplot2 tutorial. Examples use ggplot2 and four downloadable fictional datasets. A line graph is most appropriate when observations have a meaningful order, such as time, distance, age or an ordered experimental condition.
1. What is a line graph and when should you use one?
A line graph (also called a line chart or line plot) displays values as points connected by straight segments. It is particularly useful for showing how a numeric outcome changes across time or another ordered variable. A line graph can reveal trends, seasonal patterns, fluctuations, turning points and differences between groups.
- Time-series line graph: values measured by date, month, quarter or year.
- Multiple-line graph: two or more series compared on the same axes.
- Trend line: a fitted line that summarises an association or direction.
- Polynomial curve: a curved regression fit used when a straight-line relationship is inadequate.
- Step line: useful when values remain constant between change points.
- Line with ribbon: displays a range, such as a confidence interval or forecast interval.

2. Create a basic line graph with geom_line()
The geom_line() function connects observations in x-axis order. The following example uses the built-in economics dataset, which is included with ggplot2.
library(ggplot2)
ggplot(economics, aes(x = date, y = unemploy)) +
geom_line(colour = "steelblue", linewidth = 1) +
labs(
title = "Unemployment over time",
x = "Date",
y = "Number unemployed"
) +
theme_minimal()
For a simple numeric example, the pressure dataset is also available in base R:
ggplot(pressure, aes(x = temperature, y = pressure)) +
geom_line(colour = "#E76F51", linewidth = 1.1) +
labs(x = "Temperature", y = "Pressure") +
theme_minimal()
Use geom_point() as well when you want to show the individual observations explicitly.
ggplot(economics, aes(date, unemploy)) +
geom_line(colour = "#2878B5") +
geom_point(colour = "#E07A32", size = 1) +
theme_minimal()
3. Difference between geom_line() and geom_path()
Both functions connect points, but they determine connection order differently:
geom_line()orders observations by the x variable before connecting them.geom_path()connects observations in the order in which they appear in the data.
For time-series data, geom_line() is usually the natural choice. Use geom_path() when the row order itself represents a meaningful route, sequence or trajectory.
# Connect observations in x-axis order
ggplot(df, aes(x = time, y = value)) +
geom_line()
# Connect observations in the order stored in the data
ggplot(df, aes(x = x, y = y)) +
geom_path()
For reproducible plots, sort time-series data by date and check for duplicate or missing time points before plotting.
4. Create a time-series line graph in R
For dates stored as text, convert the date column using as.Date(). Then map the date to x and the measured variable to y.
sales <- read.csv("monthly_sales.csv")
sales$month <- as.Date(paste0(sales$month, "-01"))
ggplot(sales, aes(x = month, y = sales)) +
geom_line(colour = "#2878B5", linewidth = 1.2) +
geom_point(colour = "#E07A32", size = 2) +
scale_x_date(date_labels = "%b %Y",
date_breaks = "3 months") +
labs(
title = "Monthly sales trend",
x = "Month",
y = "Sales"
) +
theme_minimal()

For daily, weekly, monthly and annual data, select date breaks that keep the axis readable. Avoid printing every date label when the time series is long.
5. Draw multiple lines on the same graph
Map a categorical variable to colour or group. ggplot2 then draws a separate line for each category. The example compares several product or business series over time.
series_data <- read.csv("multiple_series.csv")
series_data$month <- as.Date(paste0(series_data$month, "-01"))
ggplot(series_data,
aes(x = month, y = value,
colour = series, group = series)) +
geom_line(linewidth = 1.1) +
geom_point(size = 2) +
labs(
title = "Compare multiple time series",
x = "Month",
y = "Value",
colour = "Series"
) +
theme_minimal()

If you omit the grouping variable, ggplot2 may connect observations from different categories into one unintended line. Explicitly mapping group = series is a useful safeguard.
6. Customize line colour, width and linetype
Use colour, linewidth and linetype to control the appearance of a line. Fixed styling values belong outside aes(). Map a variable inside aes() when the appearance should vary by group.
# Fixed styling
ggplot(economics, aes(date, unemploy)) +
geom_line(
colour = "#6A4C93",
linewidth = 1.2,
linetype = "solid"
)
# Different styles for different series
ggplot(series_data,
aes(month, value, colour = series,
linetype = series, group = series)) +
geom_line(linewidth = 1.1)
Common linetypes include "solid", "dashed", "dotted", "dotdash" and "longdash". Use colour and line type together when a chart may be printed in grayscale or viewed by readers with colour-vision deficiencies.
7. Add points, labels and annotations
A line communicates continuity; points show where observations were recorded. Add geom_point() when the measurement occasions matter or the dataset contains relatively few observations.
ggplot(series_data,
aes(month, value, colour = series, group = series)) +
geom_line(linewidth = 1) +
geom_point(size = 2.5) +
theme_minimal()
For direct labels, add a text layer. The example below labels the last observation in each series; check_overlap = TRUE can reduce collisions.
library(dplyr)
last_points <- series_data |>
group_by(series) |>
slice_max(month, n = 1, with_ties = FALSE)
ggplot(series_data,
aes(month, value, colour = series, group = series)) +
geom_line(linewidth = 1) +
geom_point(data = last_points, size = 2) +
geom_text(
data = last_points,
aes(label = series),
hjust = -0.1,
show.legend = FALSE,
check_overlap = TRUE
) +
scale_x_date(expand = expansion(mult = c(.02, .18))) +
theme_minimal()
Use annotate() for a specific event or threshold, such as a policy change or target value. Keep annotations concise and explain their meaning in the caption.
8. Step lines and area charts
Step line graph
A step line is appropriate when a value remains constant over an interval and changes at specific points, such as a tariff, policy rate, inventory level or machine setting. Use geom_step().
ggplot(economics, aes(date, unemploy)) +
geom_step(colour = "#8064A2", linewidth = 1) +
theme_minimal()

Area chart
An area chart fills the space below a time-series line. Use geom_area() when the magnitude or cumulative volume is important and the baseline is meaningful.
ggplot(series_data,
aes(month, value, fill = series, group = series)) +
geom_area(alpha = 0.45, position = "identity") +
theme_minimal()
For several categories that form a total, consider a stacked area chart with position = "stack". Avoid stacking unrelated series when comparing their individual trends is the main objective.
9. Add a linear regression trend line
A trend line summarizes the relationship between two numeric variables. It is not the same as connecting observations in time order. Use geom_smooth(method = "lm") to add a linear regression fit.
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point(alpha = 0.65, colour = "#2878B5") +
geom_smooth(
method = "lm",
formula = y ~ x,
se = TRUE,
colour = "#D1495B"
) +
labs(
title = "Linear regression trend",
x = "Engine displacement",
y = "Highway miles per gallon"
) +
theme_minimal()

The shaded region is the model's confidence band for the fitted mean by default. It is not a prediction interval for individual future observations. Check model assumptions and residuals before interpreting the line as an adequate model.
10. Fit polynomial regression curves in ggplot2
When the relationship bends, a polynomial regression may represent it better than a straight line. A quadratic model includes a squared term; a cubic model includes a cubic term. Use the lowest degree that captures a defensible pattern rather than selecting a high degree simply to follow every fluctuation.
Quadratic polynomial (degree 2)
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point(alpha = 0.6) +
geom_smooth(
method = "lm",
formula = y ~ poly(x, 2),
se = TRUE,
colour = "#E76F51",
linewidth = 1.2
) +
labs(title = "Quadratic polynomial regression") +
theme_minimal()
Cubic polynomial (degree 3)
ggplot(mpg, aes(x = displ, y = hwy)) +
geom_point(alpha = 0.6) +
geom_smooth(
method = "lm",
formula = y ~ poly(x, 3),
se = TRUE,
colour = "#6A4C93"
) +
theme_minimal()

For an explicit model, fit it with lm() and add predictions with geom_line():
model2 <- lm(y ~ poly(x, 2, raw = TRUE), data = practice_data)
prediction_data <- data.frame(
x = seq(min(practice_data$x),
max(practice_data$x),
length.out = 200)
)
prediction_data$predicted <- predict(model2, newdata = prediction_data)
ggplot(practice_data, aes(x, y)) +
geom_point(alpha = 0.5) +
geom_line(
data = prediction_data,
aes(x, predicted),
colour = "#C44536",
linewidth = 1.2
)
Polynomial fits can behave erratically near the boundaries and can overfit. Compare models using subject knowledge, residual diagnostics and suitable validation rather than relying only on visual fit or a higher R-squared.
11. Smooth line graphs with LOESS or GAM
A smoother can reveal a broad pattern when the relationship is not well described by a straight line. For smaller datasets, method = "loess" is a common exploratory option.
ggplot(mpg, aes(displ, hwy)) +
geom_point(alpha = 0.55) +
geom_smooth(
method = "loess",
formula = y ~ x,
span = 0.8,
se = TRUE,
colour = "#2A9D8F"
) +
theme_minimal()
For larger datasets, a generalized additive model (GAM) can be useful:
ggplot(mpg, aes(displ, hwy)) +
geom_point(alpha = 0.5) +
geom_smooth(
method = "gam",
formula = y ~ s(x, bs = "cs"),
se = TRUE,
colour = "#8064A2"
) +
theme_minimal()

LOESS and GAM curves are flexible descriptive fits. They should not automatically be interpreted as causal relationships or reliable extrapolations beyond the observed data range.
12. Add confidence bands and shaded ranges
geom_smooth(se = TRUE) draws a confidence band around a fitted smoother. If your dataset already contains lower and upper values, use geom_ribbon() to display the interval explicitly.
ggplot(mpg, aes(displ, hwy)) +
geom_point(alpha = 0.4) +
geom_smooth(
method = "lm",
se = TRUE,
fill = "#90CAF9",
colour = "#1565C0"
) +
theme_minimal()
Example using precomputed bounds:
ggplot(summary_data, aes(x = month, y = mean_value)) +
geom_ribbon(
aes(ymin = lower, ymax = upper),
fill = "#90CAF9",
alpha = 0.4
) +
geom_line(colour = "#1565C0", linewidth = 1) +
theme_minimal()

13. Create faceted line graphs
Facets place groups in separate panels while retaining a common visual structure. This is useful when many lines overlap or when the scales and patterns need to be inspected individually.
ggplot(series_data, aes(month, value, group = series)) +
geom_line(colour = "#2878B5", linewidth = 1) +
geom_point(colour = "#E07A32", size = 1.8) +
facet_wrap(~ series, scales = "free_y") +
labs(x = "Month", y = "Value") +
theme_minimal()

Use a fixed y-axis when direct magnitude comparisons matter. Use scales = "free_y" when each series has a very different range and the shape within each panel is the focus.
14. Format axes, dates and line graph themes
Use date scales for time-series data and continuous scales for numeric x variables. Add readable breaks, units and concise labels.
ggplot(sales, aes(month, sales)) +
geom_line(linewidth = 1, colour = "#2878B5") +
scale_x_date(
date_breaks = "3 months",
date_labels = "%b %Y"
) +
scale_y_continuous(
labels = scales::label_number(big.mark = ",")
) +
labs(
title = "Monthly sales",
x = NULL,
y = "Sales (units)"
) +
theme_minimal(base_size = 12) +
theme(
axis.text.x = element_text(angle = 45, hjust = 1),
plot.title = element_text(face = "bold")
)
Other useful options include scale_x_continuous(), scale_y_continuous(), scale_colour_brewer() and scale_colour_manual(). Use coord_cartesian() for visual zooming without dropping data from the layer calculations.
15. Download ggplot2 line graph practice datasets
These fictional datasets let you practise time-series plotting, multiple lines, polynomial regression and date formatting. They are educational examples, not real business, weather or student records.
- Download monthly sales CSV — 24 monthly observations for a time-series line chart.
- Download daily temperature CSV — daily dates and temperature values for date-scale practice.
- Download multiple series CSV — three groups measured across 24 months.
- Download polynomial trend CSV — numeric predictor and response values for linear and polynomial fits.
For the polynomial dataset:
practice_data <- read.csv("polynomial_trend.csv")
ggplot(practice_data, aes(x, y)) +
geom_point(alpha = 0.6) +
geom_smooth(
method = "lm",
formula = y ~ poly(x, 2),
colour = "#C44536"
) +
theme_minimal()
16. Interactive line graph explorer
Change the line style and trend model to see how a connected series differs from a fitted trend. This browser-based teaching visual is illustrative; use the R code above for statistical analysis.
17. Common line graph mistakes and practice exercises
Common mistakes
- Wrong connection order: sort time-series records by date and use
geom_line()for x-ordered connections. - Lines join different groups: map
group = categoryor colour to the series identifier. - Dates are stored as text: convert them with
as.Date()before using date scales. - Too many lines: use facets, direct labels or a smaller number of meaningful series to reduce clutter.
- Using a trend line as a time-series line: a regression fit summarizes a relationship; it does not connect sequential observations.
- Overfitting polynomial curves: higher degree does not automatically mean a better explanatory model. Check diagnostics and validate the fit.
- Misinterpreting confidence bands: a confidence band for the fitted mean is not the same as an interval for individual predictions.
- Using a line for unordered categories: connecting unrelated categories can imply a continuity that does not exist. Consider a point or bar chart instead.
Practice exercises
- Plot the monthly sales dataset with both
geom_line()andgeom_point(). - Format the x-axis to show quarterly labels using
scale_x_date(). - Compare Alpha, Beta and Gamma using different colours and a legend.
- Use
facet_wrap()to show each series in its own panel. - Fit linear, quadratic and cubic regression models to
polynomial_trend.csv. Compare the curves and residual patterns. - Use
geom_step()to represent a process that changes only at specific dates. - Build a line graph with a shaded interval using
geom_ribbon().
Continue learning ggplot2
Explore the other lessons in the ggplot2 tutorial. Line graphs are often used alongside scatter plots, histograms, density plots and bar charts to understand different aspects of a dataset.
ggplot2 FAQ
How do I make a line graph in ggplot2?
Use ggplot(data, aes(x = x_variable, y = y_variable)) + geom_line(). The x variable should define the order of observations, such as dates or a meaningful numeric sequence.
What is the difference between geom_line() and geom_path()?
geom_line() connects observations in x-axis order. geom_path() connects observations in the order they appear in the data.
How do I add multiple lines to one ggplot2 graph?
Map a grouping variable to colour or group, for example aes(x = month, y = sales, colour = region), and add geom_line().
How do I add a linear trend line in ggplot2?
Add geom_smooth(method = 'lm', formula = y ~ x, se = TRUE) to show a fitted linear regression line and its confidence band.
How do I add a polynomial regression line in ggplot2?
Use geom_smooth(method = 'lm', formula = y ~ poly(x, 2), se = TRUE) for a quadratic fit, or increase the polynomial degree when justified by the data.
How do I make a time-series line graph in ggplot2?
Convert the date column to Date with as.Date(), map it to x, and use geom_line(). Use scale_x_date() to format date labels.
How do I change line colour, width and type?
Set colour, linewidth and linetype inside geom_line(). Map colour to a variable inside aes() when separate series need different colours.
How do I show a shaded confidence interval?
Use geom_smooth(se = TRUE) for model-based uncertainty or geom_ribbon() when you already have lower and upper bounds in your data.