从聚合数据中创建密度图

时间:2017-01-10 22:29:39

标签: r

我有一个包含3列聚合数据的数据框:CreditScore,Count,Month。

所以550,3,3的一行意味着3人中有3人获得了550分的信用评分。

我正在尝试创建叠加的密度图,以比较两个月之间信用分布的差异。

我觉得这应该很简单但在谷歌上找不到任何东西。

尝试在R中执行此操作。

任何建议都表示赞赏。

数据示例:

structure(list(CrScore = c(0L, 2L, 3L, 530L, 535L, 544L, 549L, 
551L, 554L, 558L, 560L, 561L, 563L, 565L, 567L, 568L, 569L, 577L, 
579L, 580L), Count.of.MFSAccount = c(2L, 9L, 2L, 1L, 1L, 1L, 
1L, 1L, 1L, 2L, 1L, 1L, 3L, 1L, 1L, 2L, 1L, 2L, 1L, 1L), EnterDate.Month = structure(c(17136, 
17136, 17136, 17136, 17136, 17136, 17136, 17136, 17136, 17136, 
17136, 17136, 17136, 17136, 17136, 17136, 17136, 17136, 17136, 
17136), class = "Date")), .Names = c("CrScore", "Count.of.MFSAccount", 
"EnterDate.Month"), row.names = c(10L, 28L, 42L, 80L, 113L, 174L, 
212L, 231L, 259L, 299L, 320L, 331L, 359L, 382L, 409L, 421L, 432L, 
540L, 573L, 593L), class = "data.frame")

1 个答案:

答案 0 :(得分:1)

ggplot2使用Count.of.MFSAccount的标准化版本作为权重:

library(ggplot2)
library(dplyr)

# Create weights that are normalized within each date
df <- df %>%
        group_by(EnterDate.Month) %>%
        mutate(w = Count.of.MFSAccount / sum(Count.of.MFSAccount))

# Plot with constructed weights
ggplot(df, aes(CrScore, weight=w, color=factor(EnterDate.Month))) + geom_density()
相关问题