用ggplot2将多个y值绘制为单独的行的正确方法 [英] The right way to plot multiple y values as separate lines with ggplot2
问题描述
现在我一直在做的事情真的很迂回感觉。假设有mtcars我想绘制disp,hp和wt对mpg:
ggplot(mtcars,aes(x = mpg) )+
geom_line(aes(y = disp,color =disp))+
geom_line(aes(y = hp,color =hp))+
geom_line y = wt,color =wt))
这种感觉非常多余。如果我先融化mtcars,那么所有的变量都会融化,然后我会结束绘制其他我不想要的变量。
有没有人有这样做的好方法?
ggplot总是喜欢 long 格式的数据框,所以 melt
它:
< (mtcars,id =mpg,measure = c(disp,hp,wt))
ggplot(mtcars.long,aes(mtcars.long,aes mpg,value,color = variable))+ geom_line()
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 always prefers long format dataframe, so melt
it:
mtcars.long <- melt(mtcars, id = "mpg", measure = c("disp", "hp", "wt"))
ggplot(mtcars.long, aes(mpg, value, colour = variable)) + geom_line()
这篇关于用ggplot2将多个y值绘制为单独的行的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!