在
ggmosaic
中,我希望每个单元格代表值 sumx
,但是 geom_mosaic 不能支持它(默认,在 geom_mosaic 中,单元格代表数据行数,如 geom_histogram )。
下面的代码,我根据值重复行数据
sumx
,它运行良好。
有什么方法可以简化这个或有替换代码/geom_xx 吗? 当价值巨大时,目前的方式可能效率低下。谢谢!
library(tidyverse)
library(ggmosaic)
df <- diamonds %>% group_by(cut,color) %>% summarise(sumx = sum(x))
df2 <- df[rep(c(1:nrow(df)),df$sumx),]
ggplot(data = df2) +
geom_mosaic(aes(x = product(cut),fill=color))
由于
geom_mosaic
支持 weight
美学,您可以通过将 sumx
映射到 weight
上,根据聚合数据框实现所需的结果:
library(tidyverse)
library(ggmosaic)
df <- diamonds |>
summarise(sumx = sum(x), .by = c(cut, color))
ggplot(data = df) +
geom_mosaic(aes(x = product(cut), fill = color, weight = sumx))