1

I have some data from a survey I want to visualize in R (ggplot2). The survey was collected data on a five point scale (1-5) but many questions did not get replies from all levels. I've created an example here:

set.seed(50)
data <- data.frame("person" = c(rep("A", 3), rep("B", 3), rep("C", 3)), 
                   "question" = rep(c("speed", "accuracy", "cost"), 3), 
                   "score" = round(runif(n = 9, min = 3, max = 5 )))

data$score <- factor(data$score, levels = 1:5)

ggplot(data, aes(x = score)) + 
  geom_histogram(stat="count", aes(fill = score)) +
  facet_wrap(~question)

geom_hist

Is there a way to preserve the levels when they're not included in the responses? No responses from the 1 or 2 scale so they were dropped, can I force the x-axis to still span 1-5?

Thank you very much!!

Ian Campbell
  • 23,484
  • 14
  • 36
  • 57
ftw
  • 11
  • 1

1 Answers1

0

All you need is scale_x_discrete(drop = FALSE)

ggplot(data, aes(x = score)) + 
    geom_histogram(stat="count", aes(fill = score)) +
    facet_wrap(~question) + scale_x_discrete(drop = FALSE)

enter image description here

Ian Campbell
  • 23,484
  • 14
  • 36
  • 57