嗨,我有一个堆叠条形图的问题。
我们的目标是打印一个条形图,显示销售的产品堆叠在一起的总和,我已经这样做了,但产品没有分组在一起,所以每个产品都有大块,它们都被拆分了。我需要一些方法来聚合计数,这样它就会求和,然后我就可以按某种顺序添加图表
library(ggplot2)
library(plyr) #Is this automatically loaded with ggplot2?
library(dplyr)
salesMixData <- read.csv("SalesMix.csv", stringsAsFactors = FALSE, header = TRUE)
productMix <- salesMixData[,c(1,6,7)]
ggplot(productMix, aes(x=JoinMonthYear, y=Count,fill=Prod)) +
geom_bar(stat='identity') +
theme(axis.text.x = element_text(angle=60, hjust = 1),legend.position="bottom")输出如下所示:

发布于 2015-12-04 09:47:51
您可能希望首先对数据进行summarise,计算JoinMonthYear和Prod的每个组合的合计和。
下面是一个带有虚拟数据集的示例:
library(ggplot2)
library(dplyr)
d <- data.frame(x=sample(20, 1000, replace=T),
count=rpois(1000, 10),
grp=sample(LETTERS[1:10], 1000, replace=TRUE))这等同于你所看到的:
ggplot(d, aes(x=x, y=count, fill=grp)) +
geom_bar(stat='identity')

将观察结果分组(在您的情况下是由JoinMonthYear和Prod),然后汇总到组的总和,应该会得到您想要的结果:
d %>%
group_by(x, grp) %>%
summarise(sum_count=sum(count, na.rm=TRUE)) %>%
ggplot(aes(x=x, y=sum_count, fill=grp)) +
geom_bar(stat='identity')

https://stackoverflow.com/questions/34079445
复制相似问题