Search code examples
rmergeggplot2dummy-data

ggplot plot only the 1 on same graph remove 0 for a MQC


Suppose I have 1 question with 8 choices. A respondent can select minimum 1 choice and maximum 2 choices. I have coded a dummy for each choice.

Now it's easy to use ggplot to plot 8 graph where each graph containing yes and no barplot. However my question is how to use ggplot in order to create a single plot that removes all no and keep only the yes (so in my case the graph should have 8 yes bar)

respondant1 = c("yes","no","no","no","no","no","no","yes")
respondant2 = c("yes","no","no","no","no","no","no","yes")
respondant3 = c("no","no","no","no","yes","no","no","no")
respondant4 = c("no","yes","no","no","no","yes","no","no")
respondant5 = c("no","no","yes","no","no","no","no","no")
respondant6 = c("no","yes","no","no","no","no","no","no")
respondant7 = c("no","no","no","no","no","no","yes","yes")
respondant8 = c("no","no","no","yes","no","no","no","no")

new = rbind(respondant1,respondant2,respondant3,respondant4,
            respondant5,respondant6,respondant7,respondant8)

new = as.data.frame(new)

Solution

  • Conversion to factor (the first line) is not necessary, however, factor is a suitable data structure for responses. The only thing left to do is to aggregate positive scores, and to use geom_bar with stat=identity.

    new[] <- lapply(new, function(x) factor(x, levels = c('yes', 'no')))
    yes_plot <- data.frame(question=colnames(new), 
                           yes=sapply(new, function(x) sum(x == 'yes')))
    ggplot(yes_plot, aes(question, yes)) + geom_bar(stat='identity')
    

    enter image description here