使用ggplot在堆积条形图中订购条形图

时间:2014-01-29 22:31:16

标签: r ggplot2

以下是我的数据框的简化版本(通用性没有太大损失)

sales<-data.frame(ItemID=c(1,3,7,9,10,12),
                  Salesman=c("Bob","Sue","Jane","Bob","Sue","Jane"),
                  ProfitLoss=c(10.00,9.00,9.50,-7.50,-11.00,-1.00))

产生

  ItemID Salesman ProfitLoss
1      1      Bob       10.0
2      3      Sue        9.0
3      7     Jane        9.5
4      9      Bob       -7.5
5     10      Sue      -11.0
6     12     Jane       -1.0

以下列出每位销售员销售情况的堆积条形图,按每位销售员的整体利润排序。

sales$Salesman<-reorder(sales$Salesman,-sales$ProfitLoss,FUN="sum") #to order the bars
profits<-sales[which(sales$ProfitLoss>0),]
losses<-sales[which(sales$ProfitLoss<0),]
ggplot()+
  geom_bar(data=losses,aes(x=Salesman, y=ProfitLoss),stat="identity", color="white")+
  geom_bar(data=profits,aes(x=Salesman, y=ProfitLoss),stat="identity", color="white")

enter image description here

这完全符合我的要求。当一个销售人员有利润但没有亏损,或亏损但没有利润时,我的问题就出现了。例如,将sales更改为

sales<-data.frame(ItemID=c(1,3,7,9,10),
                  Salesman=c("Bob","Sue","Jane","Bob","Sue"),
                  ProfitLoss=c(10.00,9.00,9.50,-7.50,-11.00))

并重新应用前面的步骤生成

enter image description here

所以,推销员明显不合时宜。对于这个例子,我可以在损失之前欺骗和计划我的利润,如

ggplot()+
      geom_bar(data=profits,aes(x=Salesman, y=ProfitLoss),stat="identity", color="white")+
      geom_bar(data=losses,aes(x=Salesman, y=ProfitLoss),stat="identity", color="white")

但这对我的真实数据集不起作用。

编辑:在我的真实数据集中,每个销售人员都有两个以上的销售人员,并且对于每个销售人员,我都堆积了条形图,以便最小的条形图最接近x轴和最大条形图(即最大的利润,最大的损失)离x轴最远。出于这个原因,我需要在profits数据帧和losses数据帧上调用geom_bar()。 (我最初留下这些信息,试图避免让我的问题过于复杂。)

1 个答案:

答案 0 :(得分:0)

问题是第一次调用geom_bar(损失数据集)只有两个级别的推销员,因此订单被更改 - 这就是为什么首先调用利润仍然有效(因为仍然存在所有级别)。但是如果你改变了情节调用,你的重新排序会起作用

sales<-data.frame(ItemID=c(1,3,7,9,10),
              Salesman=c("Bob","Sue","Jane","Bob","Sue"),
              ProfitLoss=c(10.00,9.00,9.50,-7.50,-11.00))

 #to order the bars
sales$Salesman<-reorder(sales$Salesman,-sales$ProfitLoss,FUN="sum")

# Changed plot call
ggplot(sales, aes(x = factor(Salesman), y = ProfitLoss)) + 
  geom_bar(stat = "identity",position="dodge",color="white")

enter image description here

-------------------------------------------------------------------------------

编辑后;你想要最长的条[即最大的(利润+绝对(损失))离y轴最远,而不是收入下降。您可以通过更改重新排序功能来完成此操作。如果我误解了,请道歉。

我更改了Jane的数据,因此它是最长的整体栏

sales<-data.frame(ItemID=c(1,3,7,9,10),
              Salesmn=c("Bob","Sue","Jane","Bob","Sue"),
              ProfitLoss=c(10.00,9.00,29.50,-7.50,-11.00))

sales$Salesman<-reorder(sales$Salesman,-sales$ProfitLoss,function(z) sum(abs(z)))

    ggplot(sales, aes(x = factor(Salesman), y = ProfitLoss)) + 
  geom_bar(stat = "identity",position="dodge",color="white")

enter image description here