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

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 like to simultaneously plot different y variables as separate lines. But it is always only a subset I want. I've tried using melt to get "variable" as a column and use that, and it works if I want every single column that was in the original dataset. Usually I don't.

Right now I've been doing things really roundabout it feels like. Suppose with mtcars I want to plot disp, hp, and wt against mpg:

ggplot(mtcars, aes(x=mpg)) + 
  geom_line(aes(y=disp, color="disp")) + 
  geom_line(aes(y=hp, color="hp")) + 
  geom_line(aes(y=wt, color="wt"))

This feels really redundant. If I first melt mtcars, then all variables will get melted, and then I will wind up plotting other variables that I don't want to.

Does anyone have a good way of doing this?


ggplot总是喜欢格式的数据帧,所以melt它:

mtcars.long <- melt(mtcars, id = "mpg", measure = c("disp", "hp", "wt"))
ggplot(mtcars.long, aes(mpg, value, colour = variable)) + geom_line()
链接地址: http://www.djcxy.com/p/30940.html

上一篇: R中的线性回归

下一篇: 用ggplot2将多个y值绘制为单独的行的正确方法