什么是这种类型的图,如何在 R 中绘制它?

What is this type of graph, and how do you draw it in R?

我以为会是个累积的东西,发现了累积频数图和累积流图。但是,我认为图像中的图形也不是,因为累积图形是从 0 开始的,但我的变量不是。此外,密度图听起来最接近,但它是 1 面积上的分布,但我想显示频率。

基本上,变量是主变量的子部分,我想显示这些子变量何时收敛以创建峰值。本质上,这些变量加起来显示一个累积界限。

使用ggplot2你可以使用geom_area()函数

library(ggplot2)
library(gcookbook) # For the data set

ggplot(uspopage, aes(x=Year, y=Thousands, fill=AgeGroup)) + geom_area()

感谢您分享更多关于您的数据的信息。

让我们以休斯顿警察局公开的犯罪统计数据为例。在本例中,我们使用 2015 年 1 月的数据集。

library(ggplot2)

crime <- gdata::read.xls('http://www.houstontx.gov/police/cs/xls/jan15.xls')

# There's a single case in there where the offense type is called '1',
# that doesn't make sense to us so we'll remove it.
crime <- crime[!crime$Offense.Type == '1', ]
crime$Offense.Type <- droplevels(crime$Offense.Type)

有 10 列,但我们 感兴趣的是这样的:

# Hour Offense.Type
# 8   Auto Theft
# 13  Theft
# 5   Auto Theft
# 13  Theft
# 18  Theft
# 18  Theft

如您所述,问题在于每一行都是一个事件。我们需要一种方法来获取每小时的频率以传递给 geom_area()

第一种方式是让ggplot2处理它,不需要预先格式化数据。

p <- ggplot(crime, aes(x=Hour, fill=Offense.Type)) 
p + geom_area(aes(y = ..count..), stat='density')

另一种方法是使用 R 的 table() 和 reshape2 的 melt():

预先格式化频率 table
library(reshape2)
crime.counts <- table(crime$Hour, crime$Offense.Type)
crime.counts.l <- melt(crime.counts,
                        id.vars = c('Hour'),
                        value.name = "NumberofCrimes")

names(crime.counts.l) <- c("Hour", "Offense.Type", "numberOfCrimes")
p <- ggplot(crime.counts.l, aes(x = Hour,
                                 y = numberOfCrimes,
                                 fill = Offense.Type))
p + geom_area()