Home > Software engineering >  How to combine multiple dataframes and create bar graph?
How to combine multiple dataframes and create bar graph?

Time:08-17

I'm researching google search trends for five games, and five terms that usually go along with the game titles.

I've created five dataframes, which were used to create another set of five dfs that sums of the number of hits from the first set.

For example, looking into gameplay of the games look like this:

#This is for "gameplay"
trends_gameplay <- gtrends(keyword=c("Cult of the Lamb gameplay", "Elden Ring gameplay", "Divinity Original Sin 2 gameplay", " Minecraft gameplay", "League of Legends gameplay"))

trends_gameplay_over_time <- trends_gameplay$interest_over_time %>%
  as_tibble() %>%
  mutate(hits = stringr::str_replace(hits, "<1", "0"),
         hits = readr::parse_number(hits))

And then I sum up the numbers


gameplay_sum <- trends_gameplay_over_time %>%
  group_by(keyword) %>%
  summarise(total_hits = sum(hits))

This process is done for four other terms; "update", "review", "best", and "theme".

Now I want to create a grouped bar plot. I am aiming to group by the titles of the game.

Would something like this work?

ggplot(mapping=aes(x="title")) 
  geom_bar(data=gameplay_sum, aes(x=dat-0.1), fill="red", binwidth=0.1) 
  geom_bar(data=update_sum, fill="blue", binwidth=0.1)

CodePudding user response:

Edit 1: I think I know now what you are aiming for! Is this it?

Edit 2: Following functional programming paradigm, here is a better version:

library(tidyverse)
library(gtrendsR)

# Function to get data
f_search_trend <- function(v_term) {
  k <- gtrends(keyword = c(paste("Cult of the Lamb", v_term), 
                         paste("Elden Ring", v_term), 
                         paste("Divinity Original Sin 2", v_term), 
                         paste("Minecraft", v_term), 
                         paste("League of Legends", v_term)))

  k <- k$interest_over_time %>%
    as_tibble() %>%
    mutate(hits = stringr::str_replace(hits, "<1", "0"),
           hits = readr::parse_number(hits)) %>% 
    mutate(Term = v_term)
  
  return(k)
}

d1 <- f_search_trend("gameplay")
d2 <- f_search_trend("update")
d3 <- f_search_trend("review")
d4 <- f_search_trend("best")
d5 <- f_search_trend("theme")

# add them together
d <- rbind(d1, d2, d3, d4, d5) %>% 
     group_by(keyword, Term) %>%
     summarise(total_hits = sum(hits)) %>% 
     mutate(keyword = word(keyword , 1  , -2))

# plot
ggplot()  
  geom_col(data = d, 
           aes(x = Term,
               y = total_hits,
               fill = keyword),
           color = "black",
           binwidth = 0.1,
           position = "dodge", 
           stat = "identity")  
  scale_y_continuous(expand = c(0, 0),
                     limits = c(0, max(d$total_hits) * 1.1))  
  labs(x = element_blank(),
       y = "Total Hits")  
  theme_bw()

enter image description here

  • Related