【问题标题】:Stacked Histograms Using R Base Graphics使用 R 基础图形的堆叠直方图
【发布时间】:2016-05-21 16:22:41
【问题描述】:

使用ggplot2很容易创建堆叠直方图:

library(ggplot2)

ggplot(data = iris, aes(x = Sepal.Length, fill = Species)) + 
  geom_histogram(colour = 'white') 

ggplot(data = iris, aes(x = Sepal.Length, fill = Species)) + 
  geom_histogram(colour = 'white', position = 'fill')

我想知道如何仅使用 R 基础图形来创建两个直方图。

【问题讨论】:

    标签: r ggplot2 histogram


    【解决方案1】:

    您可以根据SpeciesSepal.Length 的频率表使用barplot() 生成这两个图。

    # Create frequency table
    tab <- table(iris$Species, iris$Sepal.Length)
    
    # Stacked barplot
    barplot(tab)
    

    # Stacked percent barplot
    barplot(prop.table(tab, 2)) # Need to convert to marginal table first
    

    【讨论】:

    • 问题是关于直方​​图,而不是条形图。
    • 为什么这些不是直方图?
    • 直方图的 x 轴是连续的,并且值是分箱的。条形图会为每个类别绘制计数,因此如果有不同的值,它们会得到自己的条形图——它们不会被分箱。在这个特定示例中,这只会导致一些失真,因为缺少一些值(7.3-7.9 仅跨越 5 个条而不是 7 个),并且您不能执行不同的 bin 宽度或计数。在具有更多连续和/或稀疏数据的环境中,差异更加明显,有人可能会说是灾难性的。尝试例如set.seed(1); x &lt;- rnorm(30); barplot(table(x)); hist(x)