Home > Mobile >  How to get ggplot to create a bargraph of table frequency data
How to get ggplot to create a bargraph of table frequency data

Time:09-28

Hello I am trying to create a bar graph for my data. Whenever I run the barplot code it works, but every way I've attempted to run a ggplot bar graph I get errors. Ex: Error in as.data.frame.default(x[[i]], optional = TRUE) : cannot coerce class ‘c("LayerInstance", "Layer", "ggproto", "gg")’ to a data.frame The barplot code also only displays some of the bar labels, I'm guessing it's a space issue, which is why I'm trying to get it to work with ggplot which I understand better.

UnnestGroupQ3 <- data.frame(Q3 = c ("mail", "email", "mail", "mail", "Demonstration", "Videos (Ex: Youtube)", "Podcast", "Podcast", "mail"))
UnnestGroupQ3 <- 
      group_by(UnnestQ3, Q3) %>% 
      summarise(Q3 = Q3) %>%
      table() %>%
      view()
    
Q3Graph <- barplot(names.arg=UnnestGroupQ3$Q3, UnnestGroupQ3$Freq, xlab = "Communication Method", ylab = "Frequency")
    
GGplotData <- data.frame(UnnestGroupQ3$Q3, UnnestGroupQ3$Freq)
    
Q3GraphGG <- ggplot(GGplotData, aes(x = UnnestGroupQ3$Q3, y = UnnestGroupQ3$Freq))   
      geom_bar()
    view(Q3GraphGG)

CodePudding user response:

You're making this more complex than it needs to be. Your original data frame in the question is:

UnnestGroupQ3 <- data.frame(Q3 = c ("mail", "email", "mail", "mail", 
                                    "Demonstration", "Videos (Ex: Youtube)",
                                    "Podcast", "Podcast", "mail"))

So you can just do

library(ggplot2)

ggplot(UnnestGroupQ3, aes(x = Q3))   
  geom_bar(width = 0.5, fill = "deepskyblue4")  
  theme_minimal(base_size = 20)

enter image description here

  • Related