python - 使用 python matplotlib 获得正值和负值的堆叠条形图

标签 python matplotlib charts negative-number stacked-chart

我正在尝试使用 python Matplotlib 绘制堆积条形图,并且我有想要绘制的正值和负值。我看过其他帖子,讨论如何绘制具有正值和负值的堆叠条形图,但没有人使用 Matplotlib 完成,所以我找不到我的解决方案。 Stacked bar chart with negative JSON data d3.js stacked bar chart with positive and negative values Highcharts vertical stacked bar chart with negative values, is it possible?

我已经使用这段代码在 python 中使用 matplotlib 绘制堆积条形图:

import numpy as np
import matplotlib.pyplot as plt
ind = np.arange(3)
a = np.array([4,-6,9])
b = np.array([2,7,1])
c = np.array([3,3,1])
d = np.array([4,0,-3])
p1 = plt.bar(ind, a, 1, color='g')
p2 = plt.bar(ind, b, 1, color='y',bottom=sum([a])) 
p3 = plt.bar(ind, c, 1, color='b', bottom=sum([a, b]))
p4 = plt.bar(ind, d, 1, color='c', bottom=sum([a, b, c]))
plt.show()

上面的代码给出了下图:

enter image description here

这没有给我正确的结果。有人能告诉我如何编写代码吗,是使用额外的 if else 语句,还是使用任何其他方式在堆叠条形图中同时绘制负值和正值。

我希望得到如下图表所示的结果: expected chart

现在第一列已正确绘制,因为它具有所有正值,但是当 python 在第二列上工作时,由于负值,它会全部混淆。在绘制额外的负值时,我怎样才能让它在查看正值和负值底部时取正底部?

最佳答案

ax.bar 或 plt.bar 中的 bottom 关键字允许精确设置每个条形盘的下限。我们将 0-neg bottom 应用于负值,将 0-pos bottom 应用于正值。

此代码示例创建所需的绘图:

import numpy as np
import matplotlib.pyplot as plt

# Juwairia's data:     
a = [4,-6,9]
b = [2,7,1]
c = [3,3,1]
d = [4,0,-3]
data = np.array([a, b, c, d])

data_shape = np.shape(data)

# Take negative and positive data apart and cumulate
def get_cumulated_array(data, **kwargs):
    cum = data.clip(**kwargs)
    cum = np.cumsum(cum, axis=0)
    d = np.zeros(np.shape(data))
    d[1:] = cum[:-1]
    return d  

cumulated_data = get_cumulated_array(data, min=0)
cumulated_data_neg = get_cumulated_array(data, max=0)

# Re-merge negative and positive data.
row_mask = (data<0)
cumulated_data[row_mask] = cumulated_data_neg[row_mask]
data_stack = cumulated_data

cols = ["g", "y", "b", "c"]

fig = plt.figure()
ax = plt.subplot(111)

for i in np.arange(0, data_shape[0]):
    ax.bar(np.arange(data_shape[1]), data[i], bottom=data_stack[i], color=cols[i],)

plt.show()

这是结果图:

Stacked barchart plot with pos/neg values in Matplotlib

关于python - 使用 python matplotlib 获得正值和负值的堆叠条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35979852/

相关文章:

Python 按值将列表元素分组为元组

python - 通过 Matplotlib 绘制正态密度的判别函数

mysql - 如何收集图表数据

javascript - AM 图表未正确显示日期轴

python - Python 数学中 prod() 的时间复杂度是多少

Python 使用递归反转字符串

python - 在python中叠加两个单独的直方图

python - 如何将 Matplotlib 的 stock_img() 与 Cartopy 的 NearsidePerspective 投影相匹配

python - 根据 NetworkX 中出现的次数计算边的权重

javascript - 为什么 Google Visualization 会导致 HTML1504 Unexpected end tag 错误?