yildizabdullah
yildizabdullah

Reputation: 1971

Using ggplot2 to create dodged chart

My data has the following representation:

test_number;instance_1;instance_2 #field names
test_1;2;3
test_2;5;6
test_3;3;9
...

I want to represent my results in a way that the results for instance_1 and instance_2 can be represented side by side for each test instance.

Upvotes: 0

Views: 37

Answers (1)

keegan
keegan

Reputation: 2992

First thing you'll want to do is rearrange your data for ggplot - it needs to be long and not wide. To do this, we'll us the tidyr package.

library(tidyr)
library(dplyr)
library(ggplot2)

So here's your data now,

df_untidy=data.frame(test_number=1:3,instance_1=c(2,3,5),instance_2=c(3,6,9))

test_number instance_1 instance_2
1           1          2          3
2           2          3          6
3           3          5          9

We combine the instance columns into a single column,

df_tidy <- df_untidy %>% gather(instance,value,-test_number)

test_number   instance value
1           1 instance_1     2
2           2 instance_1     3
3           3 instance_1     5
4           1 instance_2     3
5           2 instance_2     6
6           3 instance_2     9

Then it's simple to plot this with ggplot

ggplot(data=df_tidy,aes(x=factor(test_number),y=value,fill=factor(instance) )) +geom_bar(stat='identity',position='dodge')

enter image description here

Upvotes: 2

Related Questions