子集和汇总数据集以准备堆积面积图的可视化
Subset and summarize dataset to prepare visualization for stacked area graph
我有一个包含 80 万行的数据集,每行都有一个时间戳。数据涵盖一年的时间范围。
在准备要生成的堆积面积图时,我想创建 26 个子组(例如,两周间隔)。在这些子组中,我想找到 5 类.
以内值的频率
举个例子:在前两周,> x && <= y 的值百分比是多少,> y && <= z 等的百分比是多少等等
所有这些都应该导致由 ggplot2 库及其 geom_area() 函数创建的堆积面积图。
这是数据集的头部:
date transaction_volume transaction_costs
47 2015-01-01 3.985826 0.03157
59 2015-01-01 3.955749 0.03157
71 2015-01-01 0.315700 0.03157
72 2015-01-01 0.315700 0.03157
73 2015-01-01 0.315700 0.03157
74 2015-01-01 0.315700 0.03157
这是一个包含一些虚拟数据的示例:
library(dplyr)
library(ggplot2)
n <- 1000
d <- data.frame(date=as.Date('2010/01/01') + sort(sample(0:364, n, replace=TRUE)))
d$x <- runif(n)
# These are the breaks defining your bins of data
breaks <- c(0, 0.2, 0.4, 0.6, 0.8, 1)
d %>%
# create fortnight indicator from Julian day number
mutate(Fortnight=ceiling(as.numeric(format(date, '%j'))/14)) %>%
# bin data
mutate(Class=factor(findInterval(x, breaks))) %>%
group_by(Fortnight, Class) %>%
# count per group
summarise(n=n()) %>%
# expressed as proportions
mutate(Proportion=n/sum(n)) %>%
ggplot(aes(x=Fortnight, y=Proportion, fill=Class)) +
geom_area()
如果您想稍微清理一下,请过滤掉两周 27。例如。在 ggplot
调用之前插入 filter(Fortnight < 27) %>%
。
我有一个包含 80 万行的数据集,每行都有一个时间戳。数据涵盖一年的时间范围。
在准备要生成的堆积面积图时,我想创建 26 个子组(例如,两周间隔)。在这些子组中,我想找到 5 类.
以内值的频率举个例子:在前两周,> x && <= y 的值百分比是多少,> y && <= z 等的百分比是多少等等
所有这些都应该导致由 ggplot2 库及其 geom_area() 函数创建的堆积面积图。
这是数据集的头部:
date transaction_volume transaction_costs
47 2015-01-01 3.985826 0.03157
59 2015-01-01 3.955749 0.03157
71 2015-01-01 0.315700 0.03157
72 2015-01-01 0.315700 0.03157
73 2015-01-01 0.315700 0.03157
74 2015-01-01 0.315700 0.03157
这是一个包含一些虚拟数据的示例:
library(dplyr)
library(ggplot2)
n <- 1000
d <- data.frame(date=as.Date('2010/01/01') + sort(sample(0:364, n, replace=TRUE)))
d$x <- runif(n)
# These are the breaks defining your bins of data
breaks <- c(0, 0.2, 0.4, 0.6, 0.8, 1)
d %>%
# create fortnight indicator from Julian day number
mutate(Fortnight=ceiling(as.numeric(format(date, '%j'))/14)) %>%
# bin data
mutate(Class=factor(findInterval(x, breaks))) %>%
group_by(Fortnight, Class) %>%
# count per group
summarise(n=n()) %>%
# expressed as proportions
mutate(Proportion=n/sum(n)) %>%
ggplot(aes(x=Fortnight, y=Proportion, fill=Class)) +
geom_area()
如果您想稍微清理一下,请过滤掉两周 27。例如。在 ggplot
调用之前插入 filter(Fortnight < 27) %>%
。