如何按季分组生成《老友记》角色同场相关性可视化图表?
解决老友记脚本按季计算主卡司同场相关性并可视化的问题
核心问题原因
pairwise_cor(corrr包)默认对整个数据集计算相关性,group_by无法触发分组计算逻辑,因此会丢失season字段信息。需要手动按季拆分数据后分别计算,再整合结果。
具体实现步骤
1. 加载依赖包
library(tidyverse) library(corrr) library(ggplot2)
2. 数据预处理与按季拆分
假设你的数据集名为friends_script,包含season(季数)、episode(剧集)、character(角色)字段。先按季拆分数据集:
# 按季拆分,保留season字段 season_datasets <- friends_script %>% group_split(season, .keep = TRUE)
3. 批量计算各季角色同场相关性
遍历每个季的子数据集,先将数据转换为「每集-角色」的宽格式(标记角色是否在该集出现),再计算两两相关性并添加季数标记:
# 批量计算并整合结果 season_cor_results <- map_dfr(season_datasets, function(sub_df) { # 转换为宽格式:行=剧集,列=角色,值=是否出现(1=出现,0=未出现) episode_character_matrix <- sub_df %>% distinct(season, episode, character) %>% mutate(present = 1) %>% pivot_wider( names_from = character, values_from = present, values_fill = 0 ) %>% select(-season, -episode) # 移除非角色字段 # 计算两两相关性,添加当前季标记 episode_character_matrix %>% pairwise_cor(method = "pearson") %>% # 可替换为"spearman" mutate(season = unique(sub_df$season)) })
4. 可视化方案
方案1:分面展示所有季的相关性
season_cor_results %>% filter(item1 != item2) %>% # 移除角色自身的相关性 ggplot(aes(x = item1, y = item2, fill = correlation)) + geom_tile(color = "white") + scale_fill_gradient2( low = "#1a53ff", mid = "white", high = "#ff4d4d", midpoint = 0, limits = c(-1, 1) ) + labs(title = "老友记主卡司同场相关性(按季)", x = "", y = "") + theme_minimal() + theme( axis.text.x = element_text(angle = 45, hjust = 1), plot.title = element_text(hjust = 0.5) ) + facet_wrap(~season, ncol = 2) # 按季分面,可调整列数
方案2:单独生成并保存每一季的可视化图
# 遍历每个季,生成独立图表并保存 walk(unique(season_cor_results$season), function(season_num) { season_plot <- season_cor_results %>% filter(season == season_num, item1 != item2) %>% ggplot(aes(x = item1, y = item2, fill = correlation)) + geom_tile(color = "white") + scale_fill_gradient2( low = "#1a53ff", mid = "white", high = "#ff4d4d", midpoint = 0, limits = c(-1, 1) ) + labs( title = str_glue("老友记第{season_num}季主卡司同场相关性"), x = "", y = "" ) + theme_minimal() + theme( axis.text.x = element_text(angle = 45, hjust = 1), plot.title = element_text(hjust = 0.5) ) # 保存图片到工作目录 ggsave( filename = str_glue("friends_cor_season_{season_num}.png"), plot = season_plot, width = 8, height = 6, dpi = 300 ) })
内容的提问来源于stack exchange,提问作者ECII
相关产品推荐
相关产品推荐

