How to make mosaic plot in ggplot2

307 Views Asked by At

I want to make mosaic plot in ggplot2,by geom_mosaic

I want to make mosaic plot, in ggplot2. that will be as same as this.

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

I have data frame eyegrade, but I don't know, how to set aes.

library(ggplot2)
library(ggmosaic)
ggplot(data = eyegrade) +
  geom_mosaic(aes(x = product(left,right)))

thank you

1

There are 1 best solutions below

0
On

The original mosaicplot looks like this:

library(faraway)

ct <- xtabs(y ~ right + left, eyegrade)

mosaicplot(ct, color = c("lightblue"), xlab = "Right eye", ylab = "Left eye")

The equivalent in ggmosaic would be something like this:

library(ggplot2)
library(ggmosaic)

ggplot(data = within(eyegrade, left <- forcats::fct_rev(left))) +
  geom_mosaic(aes(x = product(left, right), weight = y),
              fill = "lightblue", color = "black") +
  scale_x_productlist(position = "top", expand = c(0, 0)) +
  scale_y_productlist(expand = c(0, 0)) +
  theme_minimal(base_size = 16) +
  theme(panel.grid = element_blank())

Created on 2022-11-26 with reprex v2.0.2