本文介绍了如何在ggplot2中创建Marimekko / Mosaic图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 当x和y都是分类变量时,Marimekko / Mosaic图是一个很好的默认图。使用ggplot创建这些文件的最佳方法是什么? 博客文章,但这似乎有点过时。现在是否有更好或更容易实现的实现? GGally包有一个函数 ggally_ratio ,但是这产生了一些完全不同的结果: 解决方案使用 geom_bar ,我把它变成了一个通用函数,因此它可以用于任何两个因子。 ggMMplot require(ggplot2) levVar1 levVar2 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( ) geom_text(aes(label = as.character(var1),x = var1Center,y = 1.05))} ggMMplot(钻石$ cut,钻石$清晰度) The Marimekko/Mosaic plot is a nice default plot when both x and y are categorical variables. What is the best way to create these using ggplot?The only reference I could find was this 4yo blog post but this seems a bit outdated. Are there any better or easier implementations avaialable by now? The GGally package has a function ggally_ratio but this produces something quite different: 解决方案 I did it myself a time ago, using just geom_bar, I turned it into a general function so it should work on any two 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) 这篇关于如何在ggplot2中创建Marimekko / Mosaic图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-29 09:00