ggplot2中的着色密度图

时间:2013-05-05 15:30:31

标签: r ggplot2 histogram density-plot

当我使用以下代码生成密度图时:

require(ggplot2)
set.seed(seed=10)
n <- 10000
s.data <- data.frame(score = rnorm(n,500,100),
                     gender = sample(c("Male","Female","No Response"),size=n,replace=T,prob=c(.4,.55,.05)),
                     major = sample(c("A","B","C","D"),size=n,replace=T,prob=c(.02,.25,.05,.68))) 
ggplot(s.data, aes(major,..density..,fill=major,group=1)) + 
  geom_histogram() + facet_wrap(~ gender)

enter image description here

我无法用颜色来区分“主要”类别。

我想得到的是密度图,类似于颜色和图例意义上的频率图:

ggplot(s.data, aes(major,fill=major)) + 
    geom_histogram() + facet_wrap(~ gender)

enter image description here

此问题是关注我已回答here的问题(here)。

1 个答案:

答案 0 :(得分:1)

您仍然可以使用构面参数scale="free_y"尝试频率图:

ggplot(s.data, aes(major,..count..,fill=major)) + 
  geom_histogram() + facet_wrap(~ gender, scale="free_y")

enter image description here