Home > OS >  Plotting two variables as lines using ggplot2 on the one graph
Plotting two variables as lines using ggplot2 on the one graph

Time:01-22

Year  Export Import
  <chr> <chr>  <chr> 
1 2000  79     32    
2 2001  86     34    
3 2002  87     32    
4 2003  87     32    
5 2004  98     34    
6 2005  107    37   

How can I plot both export import on the same graph, with year on the x-axis, using ggplot2?

I'm sure this is very simple, but I can't find any examples out there.

CodePudding user response:

df <- data.frame(
        Year = c(2000L, 2001L, 2002L, 2003L, 2004L, 2005L),
      Export = c(79L, 86L, 87L, 87L, 98L, 107L),
      Import = c(32L, 34L, 32L, 32L, 34L, 37L)
                     )

library(tidyverse)

df_l <- pivot_longer(df, cols = -Year)

ggplot(df_l, aes(Year, value, color = name))  
  geom_line()

Created on 2022-01-21 by the reprex package (v2.0.1)

CodePudding user response:

The easiest solution is to reshape your dataset to longer, and then group by Import and Export:

df %>% 
  reshape2::melt(id.vars = "Year") %>% 
  ggplot(aes(x = Year, y = value, group = variable))  
  geom_line()

But you can also use two geom_line objects:

df %>% 
  ggplot(aes(x = Year))  
  geom_line(aes(y = Import))  
  geom_line(aes(y = Export))

Data

df <- data.frame(
        Year = c(2000L, 2001L, 2002L, 2003L, 2004L, 2005L),
      Export = c(79L, 86L, 87L, 87L, 98L, 107L),
      Import = c(32L, 34L, 32L, 32L, 34L, 37L)
                     )
  •  Tags:  
  • Related