ggplot:如何用facet_wrap显示密度而不是在分组的条形图中计数?
数据帧由两个因素变量组成: Cls
,具有3个级别, subset
带有2个级别。我想比较 subset
的两组中的每个类别( cls
)。我想显示Y轴的百分比。它们应在某些子集
组中计算,而不是整个数据集。
library(tidyverse)
data = data.frame(
x = rnorm(1000),
cls = factor(c(rep("A", 200), rep("B", 300), rep("C", 500))),
subset = factor(c(rep("train", 900), rep("test", 100)))
)
这是我试图显示百分比的尝试,但是由于它们是在整个数据集中计算而不是 subset
group:
ggplot(data, aes(x = cls, fill = cls)) + geom_bar(aes(y = ..count.. / sum(..count..))) + facet_wrap(~subset)
subset group:subset group:subset 组: subset
组: =“ nofollow noreferrer”>
如何修复它?
编辑与接受的答案有关:
plot_train_vs_test = function(data, var, subset_colname){
plot_data = data %>%
count(var, eval(subset_colname)) %>%
group_by(eval(subset_colname)) %>%
mutate(perc = n/sum(n))
ggplot(plot_data, aes(x = var, y = perc, fill = var)) +
geom_col() +
scale_y_continuous(labels = scales::label_percent()) +
facet_wrap(~eval(subset_colname))
}
plot_train_vs_test(data, "cls", "subset")
导致错误。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一个选择和简单的修复方法是计算GGPLOT之外的百分比并绘制汇总的数据:
强>将代码放入函数的一种方法可能是如此:
有关详细信息的更多信息,尤其是
{{
操作员请参阅,带有ggplot2 和使用GGPLOT2进行编程的最佳实践One option and easy fix would be to compute the percentages outside of ggplot and plot the summarized data:
EDIT One approach to put the code in a function may look like so:
For more on the details and especially the
{{
operator see Programming with dplyr, Programming with ggplot2 and Best practices for programming with ggplot2