R中直方图的颜色区间

时间:2018-04-23 15:24:02

标签: r ggplot2 histogram geom-bar

我想绘制如图所示的条形图。我希望每个bin都根据其他列中值的总和进行着色。 enter image description here。我在这里做了一个可重复的例子。

library(reshape)
library(ggplot2)

values= replicate(4, diff(c(0, sort(runif(92)), 1)))
 colnames(values) = c("A","B","C","D")
 counts = sample(10:100, 93, replace=T)
 df = data.frame(cbind(values,"count"=counts))
 mdf = melt(df,id="count")

 mdf = mdf %>%
  mutate(binCounts = cut(count, breaks = seq(0, 100, by = 5)))



  plot = ggplot(mdf) +
  geom_bar(aes(x=binCounts, fill=variable)) +
  theme(axis.text.x=element_text(angle = 90, hjust=1))

print(plot)

我想在y轴上计数。对于每个条形,我想绘制A B C和D列中数据的比例。但是,使用上面的代码,它倾向于绘制变量的计数而不是总和。

1 个答案:

答案 0 :(得分:0)

mdf %>%
  ungroup() %>% 
  mutate(binCounts = cut(count, breaks = seq(0, 100, by = 5))) %>% 
  group_by(binCounts,variable) %>% 
  summarise(count = sum(count)) %>% 
  ggplot(aes(x=binCounts,y = count, fill=variable)) +
  geom_col() +
  theme(axis.text.x=element_text(angle = 90, hjust=1))