2015-04-23 111 views
5

我需要绘制三个值,以便为X轴的每个值绘制三个值。我的数据是: My dataframe DF如何在R中为相同的X轴值绘制多列

在X轴必须是标记为“m”的列,并且对于每个“m”值,我需要绘制对应的“x”,“y”和“z”值。

我想用GGPLOT2,我需要这样的:

Goal

+0

你能提供一些可再现的数据来证明你想要完成什么? – cdeterman

+0

请在样本输入数据中包含[可重现的示例](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example),并显示您编写的任何代码远。 – MrFlick

+0

对不起,它一开始没有上传,我得到了一些问题与图片 –

回答

6

我创建了自己的数据集来演示如何做到这一点:

数据:

x <- runif(12,1,1.5) 
y <- runif(12,1,1.5) 
z <- runif(12,1,1.5) 
m <- letters[1:12] 
df <- data.frame(x,y,z,m) 

解决方案:

#first of all you need to melt your data.frame 
library(reshape2) 
#when you melt essentially you create only one column with the value 
#and one column with the variable i.e. your x,y,z 
df <- melt(df, id.vars='m') 

#ggplot it. x axis will be m, y will be the value and fill will be 
#essentially your x,y,z 
library(ggplot2) 
ggplot(df, aes(x=m, y=value, fill=variable)) + geom_bar(stat='identity') 

输出:

enter image description here

如果你想吧一个挨着你需要geom_bar指定dodge位置,即对方:

ggplot(df, aes(x=m, y=value, fill=variable)) + 
     geom_bar(stat='identity', position='dodge') 

enter image description here

+0

非常感谢你,你的解决方案拯救了我。 您是否知道如何避免X轴值按字母顺序排列? –

+0

不客气:)很高兴我可以帮忙。有关于更改订单的非常好的答案[这里](http://stackoverflow.com/questions/3253641/how-to-change-the-order-of-a-discrete-x-scale-in-ggplot) (第二个答案,而不是接受的答案)。你需要在'limits'参数中使用'scale_x_discrete'。 – LyzandeR

相关问题