带有刻面的堆叠条的反向填充顺序

时间:2013-04-21 18:18:52

标签: r ggplot2

我无法弄清楚如何让填充顺序反转。基本上,我试图让指南和填充符合从正面到负面的单词的内在顺序:

从上到下的指南和填充顺序应为:

  • “远远超出我的预期”,(填充在顶部,在传奇的顶部)
  • “比我预期的要好一点”,
  • “关于我的期望”,
  • “比我预期的要差一点”,
  • “比我想象的要糟糕得多”(填充在传说底部的最底部)

您需要样本数据:

dat <- structure(list(Banner = structure(c(2L, 2L, 2L, 2L, 2L, 1L, 1L, 
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 
2L, 2L, 1L, 1L, 1L, 1L, 1L), .Label = c("Other", "Some Company"
), class = "factor"), Response = structure(c(1L, 2L, 3L, 4L, 
5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 
1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L),
 .Label = c(
"Far better than I expected", 
"A little better than I expected", 
"About what I expected", 
"A little worse than I expected", 
"Far worse than I expected"), class = "factor"), Frequency = c(1L, 
6L, 9L, 0L, 0L, 29L, 71L, 149L, 32L, 6L, 1L, 7L, 16L, 1L, 0L, 
38L, 90L, 211L, 24L, 6L, 0L, 0L, 8L, 1L, 1L, 6L, 13L, 109L, 35L, 
9L), Proportion = c(6, 38, 56, 0, 0, 10, 25, 52, 11, 2, 4, 28, 
64, 4, 0, 10, 24, 57, 7, 2, 0, 0, 80, 10, 10, 3, 8, 63, 20, 5
), Phase = c("Phase 1", "Phase 1", "Phase 1", "Phase 1", "Phase 1", 
"Phase 1", "Phase 1", "Phase 1", "Phase 1", "Phase 1", "Phase 2", 
"Phase 2", "Phase 2", "Phase 2", "Phase 2", "Phase 2", "Phase 2", 
"Phase 2", "Phase 2", "Phase 2", "Phase 3", "Phase 3", "Phase 3", 
"Phase 3", "Phase 3", "Phase 3", "Phase 3", "Phase 3", "Phase 3", 
"Phase 3")), .Names = c("Banner", "Response", "Frequency", "Proportion", 
"Phase"), 
row.names = c(NA, 30L), 
sig = character(0), 
comment = "Overall, my experience was...  by  Company", q1 = "", q2 = "", 
class = c("survcsub", "data.frame"))

位置标签

dat <- ddply(dat, .(Banner, Phase), function(x) {
   x$Pos <- (cumsum(x$Proportion) - 0.5*x$Proportion)
   x
})

剧情

ggplot(dat, aes(Banner, Proportion/100, fill=Response,
  label=ifelse(Proportion > 5, percent(Proportion/100), ""))) + 
  geom_bar(position="fill", stat="identity") + 
  geom_text(aes(Banner, Pos/100)) + 
  facet_grid(~Phase) + 
  scale_y_continuous(labels=percent) +
  labs(x="\nCompany", y="\nProportion")

我尝试了什么:

dat$Response <- factor(dat$Response, levels=rev(dat$Response)) 
# No dice, reverses the colour of the scale but not the position of the fill

1 个答案:

答案 0 :(得分:1)

要更改堆积条形图中值的顺序,您应在order=的{​​{1}}中使用参数aes()并设置排序所需的列名称(在本例中为geom_bar() )。使用函数Response,您可以设置条形的逆序。

使用原始数据框(没有desc()的最后一行)。

factor()

要正确放置标签,请更改位置计算:

ggplot(dat, aes(Banner, Proportion/100, fill=Response,
                label=ifelse(Proportion > 5, percent(Proportion/100), ""))) + 
  geom_bar(position="fill", stat="identity",aes(order=desc(Response))) + 
  geom_text(aes(Banner, Pos/100)) + 
  facet_grid(~Phase) + 
  scale_y_continuous(labels=percent) +
  labs(x="\nCompany", y="\nProportion")

enter image description here