【问题标题】:R ggplot histogram with 2 variables具有2个变量的R ggplot直方图
【发布时间】:2020-10-06 04:28:54
【问题描述】:

我在 ggplot 中有一个直方图。这是 kaggle 中泰坦尼克号数据集的基本数据集。我试图按年龄组查看直方图中的年龄计数,并且要显示的直方图也包含 0 或 1 的幸存类。 不幸的是显示了所有数据集,而不是每个数据集都被 Survived(0 或 1)分割

所需的输出示例如下图所示。我认为这是一个非常简单的问题,只是我是 ggplot 的新手。 数据集:https://www.kaggle.com/c/titanic

ggplot(titanic, aes(x=Age, fill= Survived))+
  geom_histogram(color="darkblue", fill="lightblue",)

【问题讨论】:

  • fill = "lightblue" 覆盖 fill = Survived。删除fill = "lightblue",如果您想要自定义颜色,请使用scale_fill_manual()。 (例如,.... + scale_fill_manual(values = c("lightblue", "firebrick2"))。)

标签: r ggplot2


【解决方案1】:

也许你正在寻找这个。 @GregorThomas 的建议很棒。请注意将Survived 变量设置为因子:

library(ggplot2)
#Plot
ggplot(titanic, aes(x=Age, fill= factor(Survived)),group=factor(Survived))+
  geom_histogram(color='black',binwidth = 5)+
  stat_bin(binwidth=5, geom="text", aes(label=..count..),
           position = position_stack(0.5),size=3,fontface='bold')

输出:

【讨论】:

    【解决方案2】:

    titanic 包中提供了完全相同的数据,因此如果人们不想从第三方站点下载数据,以下是完整的代表:

    library(ggplot2)
    
    ggplot(titanic::titanic_train, aes(x = Age, fill = factor(Survived))) +
      geom_histogram(color = "darkblue") + 
      scale_fill_manual(values = c("#ed1c23", "lightblue"), name = "Survived")
    

    reprex package (v0.3.0) 于 2020 年 10 月 5 日创建

    【讨论】:

      猜你喜欢
      • 2021-11-30
      • 2013-07-05
      • 2018-05-07
      • 2013-10-16
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      相关资源
      最近更新 更多