Reorder stacked barcode x based on fill values ​​with ggplot2

A survey is conducted with 5 questions. Questions contain the same set of possible answers. Here are the data modified to build 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 order of questions based on the number of answers given. So instead ...

 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 counting the answer = D, for example.

+5
source share
1 answer

Got it. Sorted by number of answers = 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

+6
source

Source: https://habr.com/ru/post/1212265/


All Articles