繁体   English   中英

Matplotlib - 将线添加到链接堆叠条 plot 类别

[英]Matplotlib - Add line to link stacked bar plot categories

我能够生成堆叠条 plot。

但是如何生成这样的东西呢?

我每个国家有两组数据。 这两组(功率和二氧化碳)的单位不同,今天在两个不同的图表上表示。 将它们呈现在同一个上会更具可读性。

我不知道条形图的哪些属性可以帮助我做到这一点。

回复有点,但希望这个回复可以帮助那些可能遇到相同或类似问题的人。

复制 OP 提供的示例图以及沿 x 轴的每个订单的配对数据,我想出了以下解决方案:

import matplotlib.pyplot as plt
import numpy as np

order = ["First", "Second", "Third", "Fourth"]
order_axis = np.arange(len(order))

a_main = np.array([15, 20, 16, 18])
b_main = np.array([10, 12, 5, 9])

a_other = np.array([14, 10, 8, 16])
b_other = np.array([17, 19, 4, 11])

w = 0.2
sep = 0.1

for axis in order_axis:
    plt.plot([order_axis[axis] - sep, order_axis[axis] + sep], [a_main[axis], a_other[axis]], color='C7', ls='--', zorder=1)
    plt.plot([order_axis[axis] - sep, order_axis[axis] + sep], [a_main[axis] + b_main[axis], a_other[axis] + b_other[axis]], color='C7', ls='--', zorder=1)

plt.bar(order_axis - sep, a_main, -w, color='C0', zorder=2, align="edge")
plt.bar(order_axis - sep, b_main, -w, color='C1', bottom=a_main, zorder=2, align="edge")

plt.bar(order_axis + sep, a_other, w, color='C0', zorder=2, align="edge")
plt.bar(order_axis + sep, b_other, w, color='C1', bottom=a_other, zorder=2, align="edge")

plt.xticks(order_axis, order)
plt.show()

这是上面代码生成的图

为了更好地衡量,我还有一个解决方案,它通常适用于沿 x 轴具有任意数量订单的任意数量的堆叠条。

order = ["First", "Second", "Third", "Fourth", "Fifth"]

a = np.array([17, 15, 16, 18, 10])
b = np.array([8, 12, 5, 9, 15])
c = np.array([6, 3, 6, 4, 3])

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

ax.bar(order, a, color='C0', zorder=2)
ax.bar(order, b, color='C1', bottom=a, zorder=2)
ax.bar(order, c, color='C2', bottom=a+b, zorder=2)

width = ax.patches[0].get_width()
stacks = len(ax.patches) // len(order)

for i in range(stacks):
    for j in range(0, len(order) - 1):
        h0 = np.sum([ax.patches[j + len(order) * k].get_height() for k in range(0, i + 1)])
        h1 = np.sum([ax.patches[j + 1 + len(order) * k].get_height() for k in range(0, i + 1)])

        ax.plot([j + width / 2, j + 1 - width / 2], [h0, h1], color='C7', ls='--', zorder=1)

plt.show()

第二个代码片段生成的图表

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM