如何在R中为同一个X轴值绘制多个列

Cap*_*emo 6 plot r ggplot2

我需要绘制三个值,为X轴的每个值制作三个条形.我的数据是: 我的数据帧DF

在X轴中必须是标记为"m"的列,对于每个"m"值,我需要绘制相应的"x","y"和"z"值.

我想使用ggplot2,我需要这样的东西:

目标

Lyz*_*deR 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)
Run Code Online (Sandbox Code Playgroud)

解:

#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')
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述

如果你想要一个在另一个旁边的柱子你需要dodgegeom_barie 指定位置:

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

在此输入图像描述