【问题标题】:colour bins of histogram in RR中直方图的颜色箱
【发布时间】:2018-04-23 15:24:01
【问题描述】:

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

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 列中数据的比例。但是,使用上面的代码,它倾向于绘制变量的计数而不是总和。

【问题讨论】:

  • 是的,geom_bar 绘制观察计数。使用geom_col,向aes 提供一个y 值(我猜你想要y = count),看看是否可行。
  • @camille 'geom_col' 有帮助,但它也准确地总结了 4 次我不想要的计数。
  • 好的,所以我认为你需要在绘图之前做更多的数据准备。比如对每个 bin 和变量中的计数求和

标签: r ggplot2 histogram geom-bar


【解决方案1】:
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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多