Rof非数字数据中的堆栈条形图?

时间:2016-02-18 04:21:16

标签: r

我在data.frame中有以下数据

Count   Group A Group B
2   Red One 
1   Blue    One 
1   Green   One 
5   Red Two
1   Blue    Two
2   Red Three
4   Blue    Three
2   Green   Three
1   Yellow  Three

我需要以类似于此的方式绘制此图 enter image description here

我该怎么做?谢谢!

1 个答案:

答案 0 :(得分:1)

阅读您的数据;

df <- read.table(text="Count Group_A Group_B
2 Red One
1 Blue One
1 Green One
5 Red Two
1 Blue Two
2 Red Three
4 Blue Three
2 Green Three
1 Yellow Three", sep=" ", header=TRUE)

指定因子的级别排序;

df$Group_A <- factor(df$Group_A, levels=c("Red", "Blue", "Green", "Yellow"))
df$Group_B <- factor(df$Group_B, levels=c("One", "Two", "Three"))

创建一个条形图;

library(ggplot2)
ggplot(df) + 
  geom_bar(aes(x=Group_B, y=Count, fill=Group_A), position="dodge", stat="identity") + 
  scale_fill_manual(values=c("Red"="red", "Blue"="blue", "Green"="green","Yellow"="yellow"))

enter image description here

或者,如果您不希望不均匀的组具有不同的宽度,我会添加缺少的数据;

df <- read.table(text="Count Group_A Group_B
2 Red One
1 Blue One
1 Green One
5 Red Two
1 Blue Two
2 Red Three
4 Blue Three
2 Green Three
1 Yellow Three
0 Yellow One
0 Green Two
0 Yellow Two", sep=" ", header=TRUE)

enter image description here

更准确地表达您的要求;

ggplot(df) + 
  geom_bar(aes(x=Group_B, y=Count, color=Group_A), fill="white", width=0.3, position=position_dodge(width=0.5), stat="identity", lwd=2)     + 
  scale_color_manual(values=c("Red"="red", "Blue"="blue", "Green"="green", "Yellow"="yellow")) + theme_bw() 

enter image description here