ggplot2 barplot无法正确添加

时间:2016-02-12 19:03:51

标签: r ggplot2

我已经和R一起工作了大约两年了,我不知道这里有什么问题。我有这样的数据框。

     incomeGroup    diabetic    percent
      (fctr)      (fctr)      (dbl)
1        <10,000 NonDiabetic 0.87689665
2        >75,000 NonDiabetic 0.93173965
3  10,000-15,000 NonDiabetic 0.80568579
4  15,000-20,000 NonDiabetic 0.84773930
5  20,000-25,000 NonDiabetic 0.83956823
6  25,000-35,000 NonDiabetic 0.86481373
7  35,000-50,000 NonDiabetic 0.86237913
8  50,000-75,000 NonDiabetic 0.91666293
9        <10,000    Diabetic 0.12310335
10       >75,000    Diabetic 0.06826035
11 10,000-15,000    Diabetic 0.19431421
12 15,000-20,000    Diabetic 0.15226070
13 20,000-25,000    Diabetic 0.16043177
14 25,000-35,000    Diabetic 0.13518627
15 35,000-50,000    Diabetic 0.13762087
16 50,000-75,000    Diabetic 0.08333707

然后我使用ggplot2使用以下代码制作图表:

ggplot(income3, aes(x = incomeGroup, y = percent, fill = diabetic)) + 
  geom_bar(data=subset(income3, diabetic == "NonDiabetic"), stat = "identity") + 
  geom_bar(data=subset(income3, diabetic == "Diabetic"), stat = "identity")

由于某种原因,输出已关闭。我得到一个如下图:

![enter image description here

这没有任何意义,因为我将所有数字加起来并且它们都等于1.我不知道这是ggplot的问题还是我做错了。下面是将重新创建我正在使用的数据的代码。

incomeGroup <- c("<10,000", ">75,000", "10,000-15,000", "15,000-20,000", "20,000-25,000", "25,000-35,000", "35,000-50,000", "50,000-75,000", "<10,000", ">75,000", "10,000-15,000", "15,000-20,000", "20,000-25,000", "25,000-35,000", "35,000-50,000", "50,000-75,000")

incomeGroup <- factor(incomeGroup, levels = c("<10,000", "10,000-15,000", "15,000-20,000", "20,000-25,000", "25,000-35,000", "35,000-50,000", "50,000-75,000", ">75,000"))

diabetic <- c("NonDiabetic", "NonDiabetic", "NonDiabetic", "NonDiabetic", "NonDiabetic", "NonDiabetic", "NonDiabetic", "NonDiabetic", "Diabetic", "Diabetic", "Diabetic", "Diabetic", "Diabetic", "Diabetic", "Diabetic", "Diabetic")

diabetic <- factor(diabetic)

percent <- c(0.87689664503343, 0.931739649923405, 0.805685791204679, 0.847739295548242, 0.839568230766604, 0.864813732451467, 0.862379127705366, 0.916662929943874, 0.12310335496657, 0.0682603500765948, 0.194314208795321, 0.152260704451758, 0.160431769233396, 0.135186267548533, 0.137620872294634, 0.0833370700561264)

df <- cbind.data.frame(incomeGroup, diabetic, percent)

1 个答案:

答案 0 :(得分:7)

这个问题是由两次geom_bar次调用引起的,这导致两个条形图相互叠加而不是堆叠。 您不需要这些和子集,请尝试指定group参数:

ggplot(df, aes(x = incomeGroup, y = percent, group = diabetic, fill = diabetic)) + 
  geom_bar(stat = "identity")