geom_mosaic_text无输出,如何为马赛克图添加标签?
解决马赛克图标签不显示的问题
你的代码存在两个关键问题,导致geom_mosaic_text没有输出:
- 未使用
+将geom_mosaic_text与前面的ggplot对象连接,这会让标签层无法被添加到图中 geom_mosaic_text的映射参数不全,缺少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)) + geom_mosaic_text( aes(x = product(cut), weight = sumx, label = sumx), vjust = 0.5, hjust = 0.5 )
关键调整说明
- 用
+把geom_mosaic_text接入ggplot的图层链,确保标签被加载到图上 - 在
geom_mosaic_text的映射中添加weight = sumx,让标签与马赛克块的权重分组对应 - 设置
vjust和hjust为0.5,让标签居中显示在每个马赛克块内部
如果需要给每个color分组的子块都添加标签,可以调整x轴映射为product(cut, color),示例如下:
ggplot(data = df) + geom_mosaic(aes(x = product(cut, color), fill = color, weight = sumx)) + geom_mosaic_text( aes(x = product(cut, color), weight = sumx, label = sumx), vjust = 0.5, hjust = 0.5, size = 3 )
内容的提问来源于stack exchange,提问作者anderwyang
相关产品推荐
相关产品推荐

