rstringdataframebar-chartfrequency-table

How do i turn my frequency table into a dataframe to make a bar chart graph?


I think that the title doesn't really help, but... let's go.
I have data about a candidates tweets. Its a dataframe and one of the columns its named "Tweets" (each row I have a different tweet). I've used the following functions to make a frequency table:

frequencytable <- candidate$Tweets %>%
  na.omit() %>%
  tolower() %>%
  strsplit(split = "[ .,!]") %>% # or strsplit(split = "\\W")
  unlist() %>%
  gsub('[.?:!,"\n"]', '', .) %>%
  table() %>%
  sort(decreasing = TRUE)

after that, I got results like these (a large table, without column names, where the rows are different words with their corresponded frequency below):

hello   bye  good money   red 
  567   321    22    61    98 

In dput format:

frequencytable <-
c(hello = 567L, bye = 321L, good = 22L, money = 61L, red = 98L)

(imagine that the numbers are below the words) and so on (I think that I have about ~500 occurrences)........

And now I want to show these results in a simple bar chart graph, but I'm struggling a lot.
I've tried something like:

ggplot(data = candidate$Tweets) + 
  geom_bar(mapping = aes(x = frequencytable))

It doesn't work... I've done some research and I found some tips like: turn it into a dataframe and after that proceed with the ggplot but I'm really stuck.


Solution

  • Here are three solutions starting with the frequency table.

    Make up a data set.

    set.seed(2020)
    frequencytable <- table(sample(letters[1:4], 100, TRUE))
    

    Base R.

    barplot(frequencytable)
    

    Now, ggplot2 solutions. Load the package first.

    library(ggplot2)
    
    df1 <- as.data.frame(frequencytable)
    ggplot(df1, aes(Var1, Freq)) + geom_col()
    
    df2 <- stack(frequencytable)
    ggplot(df2, aes(ind, values)) + geom_col()