44

当 x 和 y 都是分类变量时,Marimekko/Mosaic 图是一个很好的默认图。使用 ggplot 创建这些的最佳方法是什么?

例子

我能找到的唯一参考是这篇 4yo博客文章,但这似乎有点过时了。现在有更好或更简单的实现吗?GGally 包有一个功能ggally_ratio,但这会产生一些完全不同的东西:

笨拙地

4

7 回答 7

28

前段时间我自己做了,使用 just geom_bar,我把它变成了一个通用函数,所以它应该适用于任何两个factors在此处输入图像描述

ggMMplot <- function(var1, var2){
  require(ggplot2)
  levVar1 <- length(levels(var1))
  levVar2 <- length(levels(var2))

  jointTable <- prop.table(table(var1, var2))
  plotData <- as.data.frame(jointTable)
  plotData$marginVar1 <- prop.table(table(var1))
  plotData$var2Height <- plotData$Freq / plotData$marginVar1
  plotData$var1Center <- c(0, cumsum(plotData$marginVar1)[1:levVar1 -1]) +
    plotData$marginVar1 / 2

  ggplot(plotData, aes(var1Center, var2Height)) +
    geom_bar(stat = "identity", aes(width = marginVar1, fill = var2), col = "Black") +
    geom_text(aes(label = as.character(var1), x = var1Center, y = 1.05)) 
  }

ggMMplot(diamonds$cut, diamonds$clarity)
于 2013-10-08T20:46:20.820 回答
23

前段时间我在一个项目中遇到了同样的问题。我的解决方案是与选项geom_bar一起使用以适应不同的条宽:scales="free_x", space="free_x"facet_grid

# using diamonds dataset for illustration
df <- diamonds %>%
  group_by(cut, clarity) %>%
  summarise(count = n()) %>%
  mutate(cut.count = sum(count),
         prop = count/sum(count)) %>%
  ungroup()

ggplot(df,
       aes(x = cut, y = prop, width = cut.count, fill = clarity)) +
  geom_bar(stat = "identity", position = "fill", colour = "black") +
  # geom_text(aes(label = scales::percent(prop)), position = position_stack(vjust = 0.5)) + # if labels are desired
  facet_grid(~cut, scales = "free_x", space = "free_x") +
  scale_fill_brewer(palette = "RdYlGn") +
  # theme(panel.spacing.x = unit(0, "npc")) + # if no spacing preferred between bars
  theme_void() 

marimekko情节

于 2017-08-15T07:12:54.040 回答
13

第一次尝试。我不确定如何将因子标签放在轴上。

makeplot_mosaic <- function(data, x, y, ...){
  xvar <- deparse(substitute(x))
  yvar <- deparse(substitute(y))
  mydata <- data[c(xvar, yvar)];
  mytable <- table(mydata);
  widths <- c(0, cumsum(apply(mytable, 1, sum)));
  heights <- apply(mytable, 1, function(x){c(0, cumsum(x/sum(x)))});

  alldata <- data.frame();
  allnames <- data.frame();
  for(i in 1:nrow(mytable)){
    for(j in 1:ncol(mytable)){
      alldata <- rbind(alldata, c(widths[i], widths[i+1], heights[j, i], heights[j+1, i]));
    }
  }
  colnames(alldata) <- c("xmin", "xmax", "ymin", "ymax")

  alldata[[xvar]] <- rep(dimnames(mytable)[[1]],rep(ncol(mytable), nrow(mytable)));
  alldata[[yvar]] <- rep(dimnames(mytable)[[2]],nrow(mytable));

  ggplot(alldata, aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax)) + 
    geom_rect(color="black", aes_string(fill=yvar)) +
    xlab(paste(xvar, "(count)")) + ylab(paste(yvar, "(proportion)"));
}

例子:

makeplot_mosaic(mtcars, vs, gear)

例子

于 2013-10-08T15:47:52.617 回答
9

您可以使用名为“ggmosaic”(https://github.com/haleyjeppson/ggmosaic)的 ggplot2 扩展包。

https://cran.r-project.org/web/packages/ggmosaic/vignettes/ggmosaic.html提供了带有示例代码和视觉结果的广泛教程。

于 2016-12-27T16:23:10.273 回答
5

Plotluck是一个基于ggplot2的库,旨在根据 1-3 个变量的特征自动选择绘图类型。它包含马赛克图的功能。例子: plotluck(mtcars,vs,gear)

在此处输入图像描述

于 2015-04-17T06:03:54.233 回答
4

按照user2030503的建议,这里有一个使用ggmosaic. (请注意ggplot 3.0 破坏了一些 ggmosaic,因此您需要最新版本。)

library(tidyverse)
library(ggmosaic)

# Data copied from linked blog post
df <- data.frame(
  segment = LETTERS[1:4],
  segpct = c(40, 30, 20, 10),
  Alpha = c(60, 40, 30, 25), 
  Beta = c(25, 30, 30, 25),
  Gamma = c(10, 20, 20, 25), 
  Delta = c(5, 10, 20, 25)
  )

# Convert to "long" for plotting
df_long <- gather(df, key = "greek_letter", value = "pct", 
                  -c("segment", "segpct")) %>% 
  mutate(
    greek_letter = factor(
      greek_letter, 
      levels = c("Alpha", "Beta", "Gamma", "Delta")
      ),
    weight = (segpct * pct) / 10000
    )

# Plot
ggplot(df_long) +
  geom_mosaic(aes(x = product(greek_letter, segment), fill = greek_letter,
                  weight = weight))

在此处输入图像描述

于 2020-01-22T18:54:00.260 回答
2

感谢所有创建此条目的人,这确实帮助了我,因为 ggmosaic 没有做我想要的(并且没有正确标记轴)。Z.Lin 的 nice 函数在https://github.com/tidyverse/ggplot2/issues/3142中给出了一种解释的警告,这似乎是在说,在技术上其内容不真实的警告实际上是在警告我们, ggplotocracy,祝福并感谢他们,觉得 geom_bar 不应该真的有可变宽度。我想我明白了这一点,所以我从 Jake Fisher 那里得到了这个功能,并根据我自己的需要对其进行了调整。如果它对其他人有用,这里是:

makeplot_mosaic2 <- function(data, x, y, statDigits = 1, residDigits = 1, pDigits = 3, ...){
  ### from https://stackoverflow.com/questions/19233365/how-to-create-a-marimekko-mosaic-plot-in-ggplot2,
  ### this from Jake Fisher (I think)
  xvar <- deparse(substitute(x))
  yvar <- deparse(substitute(y))
  mydata <- data[c(xvar, yvar)]
  mytable <- table(mydata)
  
  widths <- c(0, cumsum(apply(mytable, 1, sum)))
  heights <- apply(mytable, 1, function(x){c(0, cumsum(x/sum(x)))})
  
  alldata <- data.frame()
  allnames <- data.frame()
  for(i in 1:nrow(mytable)){
    for(j in 1:ncol(mytable)){
      alldata <- rbind(alldata, c(widths[i], widths[i+1], heights[j, i], heights[j+1, i]))
    }
  }
  colnames(alldata) <- c("xmin", "xmax", "ymin", "ymax")
  
  alldata[[xvar]] <- rep(dimnames(mytable)[[1]],rep(ncol(mytable), nrow(mytable)))
  alldata[[yvar]] <- rep(dimnames(mytable)[[2]],nrow(mytable))
  
  chisq <- chisq.test(mytable)
  df <- chisq$parameter
  pval <- chisq$p.value
  chisqval <- chisq$statistic
  # stdResids <- chisq$stdres
  alldata$xcent <- (alldata$xmin + alldata$xmax)/2
  alldata$ycent <- (alldata$ymin + alldata$ymax)/2
  alldata$stdres <- round(as.vector(t(chisq$stdres)), residDigits)
  # print(chisq$stdres)
  # print(alldata)
  
  titleTxt1 <- paste0("Mosaic plot of ",
                      yvar,
                      " against ",
                      xvar,
                      ", ")
  titleTxt2 <- paste0("chisq(",
                     df,
                     ") = ",
                     round(chisqval, statDigits),
                     ", p = ",
                     format.pval(pval, digits = pDigits))
  titleTxt <- paste0(titleTxt1, titleTxt2)
  subTitleTxt <- "Cell labels are standardised residuals"
  
  ggplot(data  = alldata, 
         aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax)) + 
    geom_rect(color="black", aes_string(fill=yvar)) +
    geom_text(aes(x = xcent, y = ycent, label = stdres)) +
    xlab(paste0("Count of '", 
                xvar,
                "', total = ",
                max(alldata$xmax))) + # tweaked by CE
    ylab(paste0("Proportion of '", 
                yvar,
                "' per level of '",
                xvar,
                "'")) +
    ggtitle(titleTxt,
            subtitle = subTitleTxt) +
    theme_bw() +
    theme(plot.title = element_text(hjust = .5),
          plot.subtitle = element_text(hjust = .5))
}

makeplot_mosaic2(mtcars, vs, gear)
makeplot_mosaic2(diamonds, cut, clarity)
于 2020-09-20T09:10:49.387 回答