我需要绘制三个值,以便为X轴的每个值绘制三个值。我的数据是: 如何在R中为相同的X轴值绘制多列
在X轴必须是标记为“m”的列,并且对于每个“m”值,我需要绘制对应的“x”,“y”和“z”值。
我想用GGPLOT2,我需要这样的:
我需要绘制三个值,以便为X轴的每个值绘制三个值。我的数据是: 如何在R中为相同的X轴值绘制多列
在X轴必须是标记为“m”的列,并且对于每个“m”值,我需要绘制对应的“x”,“y”和“z”值。
我想用GGPLOT2,我需要这样的:
我创建了自己的数据集来演示如何做到这一点:
数据:
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')
输出:
如果你想吧一个挨着你需要geom_bar
指定dodge
位置,即对方:
ggplot(df, aes(x=m, y=value, fill=variable)) +
geom_bar(stat='identity', position='dodge')
非常感谢你,你的解决方案拯救了我。 您是否知道如何避免X轴值按字母顺序排列? –
不客气:)很高兴我可以帮忙。有关于更改订单的非常好的答案[这里](http://stackoverflow.com/questions/3253641/how-to-change-the-order-of-a-discrete-x-scale-in-ggplot) (第二个答案,而不是接受的答案)。你需要在'limits'参数中使用'scale_x_discrete'。 – LyzandeR
你能提供一些可再现的数据来证明你想要完成什么? – cdeterman
请在样本输入数据中包含[可重现的示例](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example),并显示您编写的任何代码远。 – MrFlick
对不起,它一开始没有上传,我得到了一些问题与图片 –