Search code examples
rggplot2mappingaes

Plotting two variables as lines using ggplot2 on the one graph


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.


Solution

  • 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)