繁体   English   中英

geom_histogram比例百分比(按bin)

[英]geom_histogram scale percentages by bin

因此,我有这段代码可以为每个机票价格生成一个带有许多垃圾箱的图表,其中y轴是观察次数,而填充则显示了幸存和未幸存的乘客数量。

ggplot(train, aes(x = Avg.Fare.y, fill = Survived)) +
  geom_histogram(binwidth = 1)

但是我真正想要的是一个缩放每个垃圾箱的图形,这样我可以看到填充的百分比,而不是计数。 所以像这样:

虽然@JakeKaupp答案有效,但无需执行ggplot之外的汇总计算就可以实现结果。 这是使用geom_bar (默认情况下使用stat = 'count' )和position = 'fill'的替代方法:

library(dplyr) 
library(ggplot2)

plot_data <- titanic::titanic_train %>% 
  mutate(fare_bin = cut(Fare, quantile(Fare), labels = FALSE, include.lowest = TRUE)) 

ggplot(plot_data) +
  geom_bar(aes(x = fare_bin, fill = factor(Survived) ), position = 'fill')

下次建议:提供您的数据样本,以帮助我们为您提供帮助。

我肯定会在绘图之外汇总数据,然后使用geom_col(position = "stack")实现所需的功能。

library(dplyr) 
library(ggplot2)

plot_data <- titanic::titanic_train %>% 
  mutate(fare_bin = cut(Fare, quantile(Fare), labels = FALSE, include.lowest = TRUE)) %>% 
  count(Survived, fare_bin) %>% 
  group_by(fare_bin) %>% 
  mutate(percent = n/sum(n)) 

ggplot(plot_data, aes(x = fare_bin, y = percent, fill = factor(Survived))) +
  geom_col(position = "stack")

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM