Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

r - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...