Plotting two variables as lines using ggplot2 on the same 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.

Many, many thanks for your help!

Have you tried it at all? :wink:
Some inspiration: Line chart | the R Graph Gallery

For your dataset it might be done like this:

df = tribble(
 ~Year, ~Export, ~Import,
 2000,  79,     32,    
 2001,  86,     34 ,   
 2002,  87,     32,    
 2003,  87,     32,    
 2004,  98,     34,    
 2005,  107,    37)


ggplot(df, aes(x = Year)) +
  #add one line for Export
  geom_line(aes(y = Export), colour = "blue") + 
  # add another line for Import
  geom_line(aes(y = Import), colour = "lawngreen") +
  theme_classic()

However, usually it is better to have the data in the so-called long format. In this case you don't have to add each line individually, but instead can just say "colour = category")

# convert the dataset to long format
df2 = pivot_longer(df,     # the dataset we want to convert 
                   -Year,  # keep column year as it is
                   names_to = "Cat", 
                   values_to = "value")
df2
# A tibble: 12 x 3
    Year Cat    value
   <dbl> <chr>  <dbl>
 1  2000 Export    79
 2  2000 Import    32
 3  2001 Export    86
 4  2001 Import    34
 5  2002 Export    87
 6  2002 Import    32
 7  2003 Export    87
 8  2003 Import    32
 9  2004 Export    98
10  2004 Import    34
11  2005 Export   107
12  2005 Import    37

ggplot(df2, aes(x = Year,
                y = value,
                colour = Cat)) + 
  geom_line() + 
  #let's add some plots, just because we can
  geom_point(size = 3.5) + 
  theme_classic() +
  scale_colour_manual(values = c("blue", "green3"))

1 Like

I would do:

library("ggplot2")
df <- data.frame(year = c(2000, 2001, 2002, 2003, 2004, 2005), 
                 export = c(79, 86, 87, 87, 98, 107), 
                 import = c(32, 34, 32, 32, 34, 37))

ggplot(data=df, aes(x=year)) + 
  geom_line(aes(y=export), color="darkred") +
  geom_line(aes(y=import), color="steelblue")
1 Like

many, many thanks! but here I got the followin: "Error: mapping must be created by aes()
Run rlang::last_error() to see where the error occurred"? Any suggest? -Would appreciate.

Please show your code that makes the plot and produces the error.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.