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"))
...I want the order of the questions along the x axis to be based on the count of answer = D, for example.
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With