How to plot multiple columns in R for the same X-A

2019-04-29 18:19发布

This question already has an answer here:

I need to plot three values, to make three bars for each value of the X-Axis. My data is: My dataframe DF

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:

Goal

标签: r plot ggplot2
1条回答
放我归山
2楼-- · 2019-04-29 18:44

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:

enter image description here

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')

enter image description here

查看更多
登录 后发表回答