Reorder stacked barplot x based on fill values wit

2019-06-23 16:43发布

A survey with 5 questions is administered. The questions share the same set of possible answers. Here are the data, reshaped for plotting with 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)

I want to sort the ordering of the questions based on number of a given response. So instead of this...

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

...I want the order of the questions along the x axis to be based on the count of answer = D, for example.

1条回答
趁早两清
2楼-- · 2019-06-23 17:27

Got it. Ordered by the number of responses = A, in the example below.

  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

查看更多
登录 后发表回答