[英]What is this type of graph, and how do you draw it in R?
使用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()
對頻率表進行預格式化:
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.