如何合并多个DataFrame并绘制按游戏名称分组的条形图?
问题背景
我正在研究五款游戏及与游戏名称相关的五个术语的Google搜索趋势,已经创建了五个DataFrame,还基于它们生成了另外五个用于汇总点击量的DataFrame。
针对「gameplay」术语的处理代码示例:
#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))
点击量求和代码:
gameplay_sum <- trends_gameplay_over_time %>% group_by(keyword) %>% summarise(total_hits = sum(hits))
这套流程同样适用于另外四个术语:「update」「review」「best」和「theme」。现在我需要创建按游戏名称分组的条形图,请问下面这段代码是否可行?
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)
代码问题分析与修正
你提供的这段ggplot代码不可行,存在几个关键问题:
- 语法与变量错误:
mapping=aes(x="title")里的"title"是字符串常量,不是数据框里的列名,ggplot没法识别对应数据;aes(x=dat-0.1)中的dat完全没定义,你的数据框里根本没有这个列。 - 逻辑错误:没有指定y轴为
total_hits,默认会按行计数而非使用实际的点击量总和;而且多个geom_bar直接叠加会导致x轴对齐混乱,同时你也没处理keyword列里的术语后缀,没法实现按游戏名称分组的需求。
正确实现步骤
步骤1:统一处理数据,提取纯游戏名称
首先得从每个汇总数据框的keyword列里剥离术语,提取出纯游戏名称,比如把"Cult of the Lamb gameplay"转换成"Cult of the Lamb":
# 定义提取游戏名称的函数 extract_game_name <- function(df, term) { df %>% mutate( game_name = stringr::str_remove(keyword, paste0(" ", term)), term = term ) } # 处理所有五个汇总数据框 gameplay_clean <- extract_game_name(gameplay_sum, "gameplay") update_clean <- extract_game_name(update_sum, "update") review_clean <- extract_game_name(review_sum, "review") best_clean <- extract_game_name(best_sum, "best") theme_clean <- extract_game_name(theme_sum, "theme") # 合并所有数据到一个数据框(ggplot处理长格式数据更方便) all_data <- bind_rows(gameplay_clean, update_clean, review_clean, best_clean, theme_clean)
步骤2:绘制分组条形图
用合并后的长格式数据绘图,能自动处理分组和颜色区分:
ggplot(all_data, aes(x = game_name, y = total_hits, fill = term)) + geom_bar(stat = "identity", position = position_dodge(width = 0.8), width = 0.7) + labs( x = "游戏名称", y = "总搜索点击量", fill = "搜索术语", title = "各游戏不同搜索术语的总点击量" ) + theme(axis.text.x = element_text(angle = 45, hjust = 1)) # 旋转x轴标签避免重叠
(可选)如果坚持分开用多个geom_bar叠加
要是一定要用多个geom_bar实现,得先确保每个数据框都有统一的game_name列,手动设置x轴位置对齐:
# 先给每个数据框添加game_name列 gameplay_sum <- gameplay_sum %>% mutate(game_name = str_remove(keyword, " gameplay")) update_sum <- update_sum %>% mutate(game_name = str_remove(keyword, " update")) # 获取统一的游戏名称顺序,避免x轴错位 game_levels <- unique(gameplay_sum$game_name) ggplot() + geom_bar(data = gameplay_sum, aes(x = factor(game_name, levels = game_levels), y = total_hits), fill = "red", stat = "identity", width = 0.4, position = position_nudge(x = -0.2)) + geom_bar(data = update_sum, aes(x = factor(game_name, levels = game_levels), y = total_hits), fill = "blue", stat = "identity", width = 0.4, position = position_nudge(x = 0.2)) + labs(x = "游戏名称", y = "总搜索点击量") + theme(axis.text.x = element_text(angle = 45, hjust = 1))
内容的提问来源于stack exchange,提问作者sgy0003
相关产品推荐
相关产品推荐

