如何在ggmosaic中用sumx值代表单元格?求高效替代方案
高效实现ggmosaic按sumx值绘制单元格的方案
你可以直接利用geom_mosaic原生支持的weight美学参数,无需通过重复数据行的方式,就能让单元格大小对应sumx的值,彻底解决大数值场景下的效率问题。
优化代码
library(tidyverse) library(ggmosaic) # 汇总sumx数据,同时清理分组状态避免警告 df <- diamonds %>% group_by(cut, color) %>% summarise(sumx = sum(x), .groups = "drop") # 直接用weight参数指定权重为sumx ggplot(data = df) + geom_mosaic(aes(x = product(cut), fill = color, weight = sumx))
核心原理
geom_mosaic默认用数据行数作为单元格大小的计算依据,而weight参数可以替换这个依据——指定weight = sumx后,每个单元格的占比会直接根据sumx的数值来计算,完全不需要重复行来模拟权重,内存占用和运行速度都会大幅提升。
替代可视化方案
如果不需要严格的马赛克图布局,也可以用geom_tile实现类似的占比可视化:
df <- diamonds %>% group_by(cut, color) %>% summarise(sumx = sum(x), .groups = "drop") %>% # 计算每个color在对应cut中的占比 group_by(cut) %>% mutate(prop = sumx / sum(sumx)) ggplot(df, aes(x = cut, y = color, fill = color, height = prop)) + geom_tile(color = "white") + coord_flip() + labs(y = "占比")
内容的提问来源于stack exchange,提问作者anderwyang
相关产品推荐
相关产品推荐

