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

2019-04-29 18:34发布

问题:

This question already has an answer here:

  • Plot multiple columns on the same graph in R [duplicate] 4 answers

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:

回答1:

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 plot ggplot2