Skip to Content
R Graphics Cookbook, 2nd Edition
book

R Graphics Cookbook, 2nd Edition

by Winston Chang
November 2018
Beginner to intermediate content levelBeginner to intermediate
441 pages
9h 25m
English
O'Reilly Media, Inc.
Content preview from R Graphics Cookbook, 2nd Edition

Chapter 4. Line Graphs

Line graphs are typically used for visualizing how one continuous variable, on the y-axis, changes in relation to another continuous variable, on the x-axis. Often the x variable represents time, but it may also represent some other continuous quantity; for example, the amount of a drug administered to experimental subjects.

As with bar graphs, there are exceptions. Line graphs can also be used with a discrete variable on the x-axis. This is appropriate when the variable is ordered (e.g., “small,” “medium,” “large”), but not when the variable is unordered (e.g., “cow,” “goose,” “pig”). Most of the examples in this chapter use a continuous x variable, but we’ll see one example where the variable is converted to a factor and thus treated as a discrete variable.

4.1 Making a Basic Line Graph

Problem

You want to make a basic line graph.

Solution

Use ggplot() with geom_line(), and specify which variables you mapped to x and y (Figure 4-1):

ggplot(BOD, aes(x = Time, y = demand)) +
  geom_line()
Basic line graph
Figure 4-1. Basic line graph

Discussion

In this sample data set, the x variable, Time, is in one column and the y variable, demand, is in another:

BOD
#>   Time demand
#> 1    1    8.3
#> 2    2   10.3
#> 3    3   19.0
#> 4    4   16.0
#> 5    5   15.6
#> 6    7   19.8

Line graphs can be made with discrete (categorical) or continuous (numeric) variables on the x-axis. In the example here, the variable ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

R Graphics Cookbook

R Graphics Cookbook

Winston Chang
R Cookbook, 2nd Edition

R Cookbook, 2nd Edition

JD Long, Paul Teetor
R Statistics Cookbook

R Statistics Cookbook

Francisco Juretig

Publisher Resources

ISBN: 9781491978597Errata Page