The right way to plot multiple y values as separate lines with ggplot2

ggplot always prefers long format dataframe, so melt it:

library(reshape2)
mtcars.long <- melt(mtcars, id = "mpg", measure = c("disp", "hp", "wt"))
ggplot(mtcars.long, aes(mpg, value, colour = variable)) + geom_line()

There are many other options for doing this transformation. You can see the R-FAQ on converting data from wide to long for an overview.


With reshape2 being deprecated, I updated @kohske answer using pivot_longer from tidyverse package.

Pivoting is explained here and involves specifying the data to reshape, second argument describes which columns need to be reshape (use - to exclude that column). Third is names_to gives the name of the variable that will be created from the data stored in the column names. Finally values_to gives the name of the variable that will be created from the data stored in the cell value, i.e. count. They also have more complex examples like numbers in column names e.g. wk1 wk2 etc.

# new suggestion
library(tidyverse)

# I subset to just the variables wanted so e.g. gear and cab are not included
mtcars.long <- mtcars %>% 
  select("mpg","disp", "hp", "wt") %>% 
  pivot_longer(-mpg, names_to = "variable", values_to = "value")

head(mtcars.long)
# # A tibble: 6 x 3
# mpg variable  value
# <dbl> <chr>     <dbl>
#   1    21 disp     160   
# 2    21 hp       110   
# 3    21 wt         2.62
# 4    21 disp     160   
# 5    21 hp       110   
# 6    21 wt         2.88


ggplot(mtcars.long, aes(mpg, value, colour = variable)) + geom_line()

Chart is:

mtcarstestchart

Tags:

R

Ggplot2