R:按量计算的直方图堆积

时间:2016-10-20 10:27:51

标签: r ggplot2 histogram

我有一个带有binwidth = 1的直方图的ggplot图形。 它由以下代码构成:

p <- ggplot(data, aes(x = Rating)) + coord_fixed() +
  theme_bw() +
  theme(
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.border = element_blank(),
    panel.background = element_blank()
  ) +
geom_histogram(aes(fill=partei), binwidth = 1) +
scale_fill_manual(values=c("#a1a1a1","#D0B100","#FF8B07","#5675D6","#A3DD57","#CE2929","#428953"))

ggplot

我希望按金额订购商品。例如,蓝色方块应位于橙色列下方的底部,因为只有一个蓝色方块和许多橙色方块。此外,如果浅绿色方块位于红色区域上方,那将是很好的。知道如何根据金额订购堆叠

这是数据:

    p_id    Rating partei
 1:  172 -5.628094     SP
 2:  305 -5.489508     SP
 3:  321  9.775742    SVP
 4:  341 -9.540089     SP
 5:  466 -3.875883     SP
 6:  477 -2.474366     SP
 7:  525 -3.789094     SP
 8:  540  1.362994    CVP
 9:  801  1.255944    FDP
10:  823 -2.626939     SP
11:  825  7.280470    SVP
12: 1106  1.882722    CVP
13: 1141  3.733562    FDP
14: 1148 -5.943324     SP
15: 1150 -6.212764     SP
16: 1153  3.077083    FDP
17: 1162  5.936169    SVP
18: 1267 -3.543711     SP
19: 3831  1.932549    CVP
20: 3871  1.315812    CVP
21: 3879  1.608675    FDP
22: 3891 -1.629615     SP
23: 3914 -2.938615    GPS
24: 3915  2.416889    CVP
25: 3916 -5.675579     SP
26: 3918  1.217664    BDP
27: 3920  1.223370    CVP
28: 3921  1.871879    CVP
29: 4055  1.961057    CVP
30: 4062  3.496568    FDP
31: 4064  3.886054    FDP
32: 4068  6.057008    SVP
33: 4075  4.040331    FDP
34: 4078  4.152061    FDP
35: 4088  1.954443    CVP
36: 4112  5.090271      -
37: 4139  4.025476    FDP
38: 4145  7.085134    SVP
39: 4151  3.307654    FDP
40: 4152  3.911100    FDP
41: 4153  1.805892    CVP
42: 4204  2.402280    CVP
43: 4205  1.267867    CVP
44: 4206  1.160906    CVP
45: 4207  2.871954    FDP

1 个答案:

答案 0 :(得分:1)

在这种特定情况下,可以通过修改级别顺序轻松完成 我需要具体说明每种水平和颜色的组合,以保存相同的颜色。

如果您想要更灵活,最简单的方法可能是创建一个包含更多列的新data.frame 您还可以通过修改scale_fill中的实际图例来保留旧图例 enter image description here

data$partei <- factor(data$partei, levels=c("-", "FDP", "BDP", "CVP", "SP", "SVP", "GPS"))

ggplot(data, aes(x = Rating)) + coord_fixed() +
  theme_bw() +
  theme(
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.border = element_blank(),
    panel.background = element_blank()
  ) +
geom_histogram(aes(fill=partei), binwidth = 1) +
scale_fill_manual(values=c( "-" = "#a1a1a1","BDP" = "#D0B100", "CVP" = "#FF8B07", "FDP" = "#5675D6", "GPS" = "#A3DD57", "SP" = "#CE2929", "SVP" = "#428953"))