You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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
  )

关键调整说明

  1. 用+把geom_mosaic_text接入ggplot的图层链,确保标签被加载到图上
  2. 在geom_mosaic_text的映射中添加weight = sumx,让标签与马赛克块的权重分组对应
  3. 设置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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 17:52:02