9

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

LyzandeR
  • 37,047
  • 12
  • 77
  • 87
Captain Nemo
  • 262
  • 1
  • 7
  • 22
  • Can you provide some reproducible data to demonstrate what you want to accomplish? – cdeterman Apr 23 '15 at 17:14
  • Please include a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input data and show any code you've written so far. – MrFlick Apr 23 '15 at 17:14
  • Sorry, it was not uploaded at first, I got some problems with the pics – Captain Nemo Apr 23 '15 at 17:16
  • It's not helpful to post pictures of data. Better to share data with a dput(). See the link I provided for better suggestions for including data I your question. – MrFlick Apr 23 '15 at 18:08

1 Answers1

9

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

LyzandeR
  • 37,047
  • 12
  • 77
  • 87
  • Thank you really really much, your solution has saved me. Do you know how to avoid the X-Axis values to appear alphabetically sorted? – Captain Nemo Apr 23 '15 at 19:21
  • You are welcome :) Glad I could be of help. There is a very good answer [here](http://stackoverflow.com/questions/3253641/how-to-change-the-order-of-a-discrete-x-scale-in-ggplot) about changing the order (the second answer, not the accepted one). You need to use `scale_x_discrete` with the `limits` argument. – LyzandeR Apr 23 '15 at 19:27