当期待躲闪图表时,ggplot会产生叠加的条形图

时间:2016-07-17 06:56:10

标签: r ggplot2 geom-bar

我有一个数据集,在一个表中显示产品,会计期间和交易。

app$FISCAL_PERIOD <-(201604,201604,201604,201605,201605,201605,201606,201606,201606,201607,201607,201607,201608,201608,201608,201609,201609,201610,201610,201611,201611)

app$Product <- c("Product 1","Product 3","Other","Product 1","Product 3","Other","Product 1","Product 3","Other","Product 1","Product 3","Other","Product 1","Product 3","Other","Product 2","Product 3","Product 2","Product 3","Product 2","Product 3")

app$sum_trans<-c(78,23410,1946,84,29532,417,16,30364,129,305,32386,584,424,20873,274,20,20929,470,19261,10,6131)

当我运行这个时,我得到了我希望的图表,一个&#34;躲过了#34;条形图:

ggplot(data=app, aes(x=FISCAL_PERIOD, y=sum_trans, fill=Product)) + geom_bar(stat="identity", position=position_dodge(), colour="black")

但是当我运行这个时,我会得到一个不是我需要的堆积条形图:

ggplot(data=app, aes(x=Product, y=sum_trans, fill=FISCAL_PERIOD)) + geom_bar(stat="identity", position=position_dodge(), colour="black")

1 个答案:

答案 0 :(得分:0)

可能是这种情况,因为ggplot不理解FISCAL_PERIOD变量作为因子变量。这应该做的修复:

ggplot(data=app, aes(x=Product, y=sum_trans, fill=as.factor(FISCAL_PERIOD))) +
geom_bar(stat="identity", position="dodge", colour="black")