使用ggplot2根据填充值重新排序堆积的条形图x

时间:2015-01-30 11:24:25

标签: r ggplot2 bar-chart

进行了一项包含5个问题的调查。这些问题共享同一组可能的答案。以下是使用ggplot2重新绘制的数据。

library(tidyr)
library(magrittr)

data <- data.frame(ID = c(1:500),
                   q1  = factor(sample(c(1:4), 500, replace = T),
                                labels = c("A", "B", "C", "D")),
                   q2  = factor(sample(c(1:4), 500, replace = T),
                                labels = c("A", "B", "C", "D")),
                   q3  = factor(sample(c(1:4), 500, replace = T),
                                labels = c("A", "B", "C", "D")),
                   q4  = factor(sample(c(1:4), 500, replace = T),
                                labels = c("A", "B", "C", "D")),
                   q5  = factor(sample(c(1:4), 500, replace = T),
                                labels = c("A", "B", "C", "D"))) %>%
gather(question, value, q1:q5)

我想根据给定响应的数量对问题的排序进行排序。所以不要这样......

library(ggplot2)

ggplot(data, aes(x = question , fill = value)) +
  geom_bar() + 

  theme(panel.background = element_rect(fill = "white")) +
  scale_fill_manual("Value", values = c("#2171B5", "#6BAED6", "#BDD7E7", 
                                   "#EFF3FF"))

enter image description here

...我希望沿x轴的问题顺序基于例如answer = D的计数。

1 个答案:

答案 0 :(得分:6)

知道了。在下面的示例中按响应数量= A排序。

  data$question <- reorder(dataf$question, data$value, function(x) max(table(x)[1]))  

   ggplot(heatDf, aes(x = question, fill = value)) +
      geom_bar() + 
      theme(panel.background = element_rect(fill = "white")) +
      scale_fill_manual("", values = c("#2171B5", "#6BAED6", "#BDD7E7", 
                                       "#EFF3FF", "grey30"))

enter image description here