首页 > 解决方案 > 使用 ggplot 和 r 显示分类变量的分布

问题描述

根据通用泰坦尼克数据集简化我的问题:

如何获得数据集中所有属性的以下图在此处输入图像描述

如果可能的话,我还想获得每个类别的计数或百分比。

提前谢谢你的帮助。

问候, 特鲁蒂

标签: rggplot2bar-chart

解决方案


使用泰坦尼克号数据集,可以使用

library(tidyverse)
data("Titanic")

Titanic %>% 
  as.data.frame() %>%    # transform from a table to dataframe
  gather(variable, value, -Freq) %>%  # change to long format
  group_by(variable, value) %>% 
  summarise(Freq = sum(Freq)) %>% # get the freq for each level of each variable
  ggplot(aes(variable, Freq, fill = value)) + 
  geom_col(position = position_stack()) +
  geom_text(aes(label = paste0(value, " (", Freq, ")")), vjust = 1, 
            position = position_stack()) +
  theme(legend.position = "none")

在此处输入图像描述


推荐阅读