本文介绍了用ggplot2将多个y值绘制为单独的行的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我经常遇到一个问题,我有一个数据框架,它有一个单独的x变量,一个或多个方面变量以及多个不同的其他变量。有时我想同时将不同的y变量绘制为单独的行。但它始终只是我想要的一个子集。我已经尝试使用融合来获取变量作为列并使用它,并且如果我想要原始数据集中的每一列都可以使用它。通常我不会。 现在我一直在做的事情真的很迂回感觉。假设有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 它: 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值绘制为单独的行的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-20 22:21