How to Create a GGPlot with Multiple Lines

Load ggplot2 package

library(ggplot2)
theme_set(theme_minimal())

Data

head(economics)
## # A tibble: 6 x 6
##   date         pce    pop psavert uempmed unemploy
##   <date>     <dbl>  <int>   <dbl>   <dbl>    <int>
## 1 1967-07-01  507. 198712    12.5     4.5     2944
## 2 1967-08-01  510. 198911    12.5     4.7     2945
## 3 1967-09-01  516. 199113    11.7     4.6     2958
## 4 1967-10-01  513. 199311    12.5     4.9     3143
## 5 1967-11-01  518. 199498    12.5     4.7     3066
## 6 1967-12-01  526. 199657    12.1     4.8     3018

Basic line plot

ggplot(data = economics, aes(x = date, y = psavert))+
  geom_line()

Plot with multiple lines

ggplot(economics, aes(x=date)) + 
  geom_line(aes(y = psavert), color = "darkred") + 
  geom_line(aes(y = uempmed), color="steelblue", linetype="twodash") 
# Data preparation
library("tidyverse")
df <- economics %>%
  select(date, psavert, uempmed) %>%
  gather(key = "variable", value = "value", -date)
head(df)
## # A tibble: 6 x 3
##   date       variable value
##   <date>     <chr>    <dbl>
## 1 1967-07-01 psavert   12.5
## 2 1967-08-01 psavert   12.5
## 3 1967-09-01 psavert   11.7
## 4 1967-10-01 psavert   12.5
## 5 1967-11-01 psavert   12.5
## 6 1967-12-01 psavert   12.1
# Visualization
ggplot(df, aes(x = date, y = value)) + 
  geom_line(aes(color = variable, linetype = variable)) + 
  scale_color_manual(values = c("darkred", "steelblue"))

Comments ( 15 )

library("tidyverse")
df <- economics %>%
  select(date, psavert, uempmed) %>%
  mutate(uempmed_2 = 2*uempmed) %>%
  gather(key = "variable", value = "value", -date)

ggplot(df, aes(x = date, y = value)) + 
  geom_line(aes(color = variable, linetype = variable)) + 
  scale_color_manual(values = c("darkred", "steelblue", "green"))
library(ggplot2)
theme_set(theme_minimal())
data(economics)
ggplot(economics, aes(x = date)) +
  geom_line(aes(y = psavert, color = "psavert")) +
  geom_line(aes(y = uempmed, color = "uempmed"), linetype = "twodash") +
  scale_color_manual(values = c("darkred", "steelblue"))


More Python Code Example

Popular Examples

Read more here: Source link