如何在 R 中为相同的 X 轴值绘制多列
How to plot multiple columns in R for the same X-Axis Value
我需要绘制三个值,为 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 轴的每个值制作三个条形图。我的数据是:
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')