如何在matplotlib中绘制具有混合+ ve和-ve值的100%堆积条形图?

问题描述:

我有与每个变量的绝对值的总和= 100% 下面是一些示例数据混合正值和负值的一些数据:如何在matplotlib中绘制具有混合+ ve和-ve值的100%堆积条形图?

Out01 = [79.069,-1.602,5.067,-4.241,-5.433,-4.590] 
Out02 = [50.348,13.944,-15.373,6.554,5.541,8.240] 
Out03 = [-8.053,0.819,-9.741,2.814,22.475,56.098] 
Out04 = [-17.350,33.710,-18.510,-0.842,3.050,26.537] 
Out05 = [-20.169,37.583,-20.785,-2.041,1.728,17.695] 

我画它们作为希望的在Microsoft Excel中通过如下“100%堆积列”图表: I drew them as desired in Microsoft Excel as follows by the "100% stacked columns" chart: 现在我想通过matplotlib库在python中绘制类似的图表。

我该怎么做?

+0

[Here](http://matplotlib.org/examples/pylab_examples/bar_stacked.html)是来自matplotlib gallery的堆叠条形示例。应该给你一个好的起点。 – Primer

+0

这个例子中的问题是它只处理积极的data_。请阅读下面第一个答案中的描述。 –

+0

这似乎是一个重复的问题:http://*.com/questions/35979852/stacked-bar-charts-using-python-matplotlib-for-positive-and-negative-values – elke

最后,得到的答复, 当我跟着the example in matplotlib page,它包括底部关键字指定每个样本数据的比上一个上升。

p2 = plt.bar(ind, womenMeans, width, color='y', bottom=menMeans, yerr=womenStd) 

例如,如果我们想绘制男性和女性的数据作为例子,我们与男子得分20(系列G1)开始,然后画女性,她们开始密谋的25值20. 底部值要展开这一点,如果我们添加了另一个类别,说儿童,得分15,那么它应该与底部 = 20 + 25 = 45。等

负值绘制,我们有一个问题,那就是他们在积极的方向相反的方向发展。所以它应该从bottom = 0开始,然后独立地以正值或负值的总和的最大值开始。 要理解一个例子,如果我们想绘制一系列如下:(20,25,-15,30,10,-5,17,3,-28) 每个值的底部应该是如下所示(0,20,0,45,-15,-25,75,92,-30)为什么?

对于20,我们只是开始绘图,所以,没有底部的要求。 对于25,我们需要增加20。 对于-15,它是第一个负值,所以它必须绘制在轴下方,没有底部值,所以底部= 0 对于30,它应该提高20 + 25 = 45 对于-10,它应该低于之前的负值,即-15 对于下一个-5,它应该低于-10 + -15 = -25 依此类推。 ..

def bottoms_matrix(matrix): 
    positives = [] 
    negatives = [] 
    for i, row_mat in enumerate(matrix): 
     tmp_p = [] 
     tmp_n = [] 
     for j, cell in enumerate(row_mat): 
      if cell >0: 
       tmp_p.append(cell) 
       tmp_n.append(0.) 
      else: 
       tmp_p.append(0.) 
       tmp_n.append(cell) 
     positives.append(tmp_p) 
     negatives.append(tmp_n) 

    # get cumulative sums 
    positives = positives[:-1] 
    negatives = negatives[:-1] 
    positives.insert(0, [0.] * len (matrix[0])) 
    negatives.insert(0, [0.] * len(matrix[0])) 
    tmp = swap_matrix(positives) 
    tmp = [list(np.cumsum(t)) for t in tmp] 
    positives = swap_matrix(tmp) 

    tmp = swap_matrix(negatives) 
    tmp = [list(np.cumsum(t)) for t in tmp] 
    negatives = swap_matrix(tmp) 

    final_matrix =[] 
    for i, row_mat in enumerate(matrix): 
     tmp =[] 
     for j, cell in enumerate(row_mat): 
      tmp.append(positives[i][j] if cell > 0 else negatives[i][j]) 
     final_matrix.append(tmp) 
    return final_matrix 

一个完整的例子有数据和所有辅助功能is uploaded on my Git page

+0

我已经等了3天,但不幸的是,没有人回答。但是,我知道答案,并将其放在这里以利于他人。我表示接受了其他人的信心,认为它确实有效,尽管我没有赢得它的声誉。 –

+0

您的Git页面的链接似乎不起作用。是否有可能在这里添加一个完整的示例+图表? – elke

+0

谢谢@elke您的评论。我纠正了断开的链接。 –