Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorder stacked barplot x based on fill values with ggplot2

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.

like image 896
D L Dahly Avatar asked Jan 30 '15 11:01

D L Dahly


1 Answers

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

like image 109
D L Dahly Avatar answered Nov 15 '22 04:11

D L Dahly