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

如何用ggplot2的geom_mosaic绘制与mosaicplot一致的马赛克图

用ggplot2结合ggmosaic复刻faraway包的马赛克图

问题背景

用户原本使用faraway包绘制eyegrade数据集的马赛克图,代码如下:

library(faraway)
(ct <- xtabs(y ~ right + left, eyegrade))
mosaicplot(ct, color = c("lightblue"),xlab="Right eye",ylab="Left eye")

现需用ggplot2结合ggmosaic包的geom_mosaic实现完全一致的效果,但此前的尝试未正确设置参数。

正确实现代码

以下是对应mosaicplot效果的geom_mosaic代码:

library(ggplot2)
library(ggmosaic)

ggplot(data = eyegrade) +
  geom_mosaic(
    aes(
      x = product(right, left),  # 匹配原xtabs的维度顺序,控制坐标轴分组逻辑
      weight = y                # 指定频数权重,对应xtabs中的计数列y
    ),
    fill = "lightblue"          # 设置填充色,与原mosaicplot效果一致
  ) +
  labs(
    x = "Right eye",
    y = "Left eye"
  ) +
  theme_minimal()  # 可选,让视觉风格更贴近基础绘图系统的mosaicplot

参数说明

  • product(right, left):ggmosaic的product()函数用于定义马赛克图的分组维度,顺序需与原xtabs(y ~ right + left)一致,才能保证x轴对应右眼、y轴对应左眼的结构与原图匹配。
  • weight = y:必须指定该参数,因为eyegrade数据集中的y是各组的频数,geom_mosaic需要通过它计算每个矩形的占比大小。
  • fill = "lightblue":geom_mosaic用fill控制填充色,对应原mosaicplot的color参数效果。

内容的提问来源于stack exchange,提问作者user20606451

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 22:35:18