如何从ggplot2中的两个不同的二进制值列绘制百分比堆积条形图?
Posted
技术标签:
【中文标题】如何从ggplot2中的两个不同的二进制值列绘制百分比堆积条形图?【英文标题】:how to draw a percent stacked bar plot from two distinct binary-valued columns in ggplot2? 【发布时间】:2022-01-05 02:47:27 【问题描述】:我在食品数据框中有两个二进制值列,如下所示:
foods$veryHealthy:
"False" "False" "True" "True" "False" "False" "False" "True" "False" "False" "True" "False"
"True" "False" "False" "True" "False" "True" "False" "False" "True" "False" "False" "False" ...
foods$dairyFree:
"True" "True" "True" "True" "True" "True" "True" "True" "False" "True" "True" "False"
"True" "False" "False" "True" "True" "True" "True" "False" "True" "False" "True" "True" ...
I want to get some plot like:
对于 x 轴而不是四个类别我想使用二进制值。
注意条的粗细如何根据每个类中的实例数而变化。
我尝试了以下代码,但没有得到结果:
ggplot(foods, aes(x=veryHealthy, y=dairyFree, fill=dairyFree)) +
geom_col(position = "fill")
编辑:我必须使用 ggplot2 而不是任何内置或其他库。
【问题讨论】:
【参考方案1】:我猜你正在寻找包ggmosaic
这里你可以找到vingette 的一些例子:
# dummy data
df <- data.frame(veryHealthy = c("False","False","True","True","False","False","False","True","False","False","True","False","True","False","False","True","False","True","False","False","True","False","False","False"),
dairyFree = c("True","True","True","True","True","True","True","True","False","True","True","False","True","False","False","True","True","True","True","False","True","False","True","True"))
library(ggplot2)
library(ggmosaic)
# simple implementation with your dummy data
ggplot2::ggplot(data = df) +
ggmosaic::geom_mosaic(aes(x = product(veryHealthy, dairyFree), fill = veryHealthy ))
编辑:
也许这对你有用(使用与以前相同的虚拟数据):
plot(table(df))
而here 你可以找到一些“手动”的方法
【讨论】:
感谢您的回答,但我必须使用 ggplot2 本身。很抱歉我没有明确强调。 @Hamed 看看更改后的答案......这可能会按照您的需要完成工作以上是关于如何从ggplot2中的两个不同的二进制值列绘制百分比堆积条形图?的主要内容,如果未能解决你的问题,请参考以下文章
在ggplot2中绘制两个具有相同y变量但不同x变量的箱线图