使用ggplot2创建躲闪图表

时间:2014-11-25 16:00:36

标签: r ggplot2

我的数据有以下表示:

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

我希望以一种方式表示我的结果,即每个测试实例可以并排显示instance_1和instance_2的结果。

1 个答案:

答案 0 :(得分:2)

您要做的第一件事就是重新安排ggplot的数据 - 它需要很长而不是宽。为此,我们提供了tidyr包。

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

现在这里是你的数据,

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

我们将instance列合并为一列

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

然后用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