简体   繁体   English

R中直方图的颜色箱

[英]colour bins of histogram in R

I want to plot a barplot like in figure. 我想绘制一个如图所示的小节。 I want each bin to be coloured based on the sum of the value in the other columns. 我希望根据其他列中值的总和为每个bin着色。 在此处输入图片说明 . I made a reproducible example 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)

I want the count on the y axis. 我想要在y轴上计数。 For each bar I want to plot the proportion of the data from the column ABC and D. However with the above code it tends to plot the count of the variable rather than the sum. 对于每个条形图,我想绘制ABC和D列中数据的比例。但是,使用上述代码,它倾向于绘制变量的数量而不是总和。

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM