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

后端 未结 2 1460
梦毁少年i
梦毁少年i 2020-12-10 03:39

I often run into an issue where I have a data frame that has a single x variable, one or more facet variables, and multiple different other variables. Sometimes I would lik

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-10 04:24

    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.

提交回复
热议问题