Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 bar chart with 2 Y variables

I am trying to create a simple bar chart with ggplot2 (in R). I would like to have 2 bars for each category.

 X   Y1     Y2
 A  0.53    0.01
 B  0.23    0.01
 C  0.15    0.05
 D  0.09    0.26
 E  0.01    0.67

So for A, I would like to have 2 bars equivalent to 0,53 (Y1) and 0,01 (Y2). For B, it would be 2 bars equivalent to 0,23(Y1) and 0,01(Y2) and so on.

This is what I tried so far:

   ggplot(df, aes(x=x, y=y1)) + geom_bar(stat="identity")

Thanks

like image 474
Samer Nachabé Avatar asked Dec 07 '25 02:12

Samer Nachabé


1 Answers

library(reshape)    
dataframe <- melt(dataframe )
    dataframe  <- dataframe [complete.cases(dataframe ),]

    ggplot(data = dataframe , aes(x=X, y = value, fill = variable) ) + geom_bar(stat="identity", position="dodge")

enter image description here

If you want, you can also stack them by removing the position dodge statement. You can change labels and axis title by using the normal ggplot command.

like image 126
MichaelVE Avatar answered Dec 08 '25 15:12

MichaelVE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!