如何在R中为相同的X轴值绘制多列 [英] How to plot multiple columns in R for the same X-Axis Value
本文介绍了如何在R中为相同的X轴值绘制多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要绘制三个值,为X轴的每个值制作三个条形图。我的数据是:
在X轴必须是标记为m的列,并且对于每个m值,我需要绘制相应的x,y和z值。
我想使用ggplot2,我需要如下所示:
解决方案
我创建了自己的数据集来演示如何做到这一点: b
数据:
x < - runif(12,1,1.5 )
y< - runif(12,1,1.5)
z< - runif(12,1,1.5)
m< - 字母[1:12]
df< ; - data.frame(x,y,z,m)
解决方案:
#你首先需要融化你的data.frame
库(reshape2)
#只有一列的值为
#,另一列的变量即你的x,y,z
df < - melt(df,id.vars ='m')
#ggplot它。 x轴将是m,y将是该值并且填充将是
#essentially您的x,y,z
库(ggplot2)
ggplot(df,aes(x = m,y = value,fill = variable))+ geom_bar(stat ='identity')
输出: p>
如果你想要一个挨着另一个,你需要在 geom_bar $ c中指定
dodge
位置$ c> ie:
ggplot(df,aes(x = m,y = value,fill = variable))+
geom_bar(stat ='identity',position ='dodge')
I need to plot three values, to make three bars for each value of the X-Axis. My data is:
In the X-Axis must be the column labeled as "m" and for each "m" value I need to plot the correspondent "x","y" and "z" value.
I want to use ggplot2 and I need something like this:
解决方案
I created my own dataset to demonstrate how to do it:
Data:
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)
Solution:
#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')
Output:
If you want the bars one next to the other you need to specify the dodge
position at geom_bar
i.e.:
ggplot(df, aes(x=m, y=value, fill=variable)) +
geom_bar(stat='identity', position='dodge')
这篇关于如何在R中为相同的X轴值绘制多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文