python-3.x - 如何在 Python 中创建具有每个变量值之间差距的堆积条形图

标签 python-3.x graph

我在用 Python 创建堆积条形图时遇到了问题。 我有如下 3 个变量的数据:

A=[3,5,7]

B=[4,5,7]

C=[2,3,4,5,6,7]

我想创建一个条形图,其中包含每个变量值的差距,如下所示

带有每个变量值之间差距的条形图:

enter image description here

谁能帮我画这张图?非常感谢。

最佳答案

其实你想画一个颜色表或者类似甘特图的东西。我不知道在 Python 中执行此操作的真正便捷方法。

一种解决方案是使用matplotlib.pyplot.grid (doc) .此讨论提供了一个 solution .

另一种解决方案是研究plotly包。它为表格和甘特图提供了非常漂亮的输出 (doc) .

在这里,我将使用 ma​​tplotlib 中的 hbar 向您展示类似的输出。主要思想是重建细胞网格。每行代表一个类(例如 ABC)。每行由相同数量的单元格组成。每个单元格具有相同的宽度。单元格的颜色由数据的二进制转换定义。

要调整 x 轴 标签,只需手动移动它们即可。

# Import module
import seaborn
import matplotlib.pyplot as plt
import numpy as np

##########################
#       Your input       #
##########################

A = [3, 5, 7]
B = [4, 5, 7]
C = [2, 3, 4, 5, 6, 7]


##########################
# Prepra the data        #
##########################
my_list = [A, B, C]
segments = 8
cell_width = 1000
nb_x_range = [i * cell_width for i in range(2, segments)]
classes = ["A", "B", "C"]
colors_def = {'A': {0: "w", 1: "b"},
              'B': {0: "w", 1: "g"},
              'C': {0: "w", 1: "y"},
              }

def create_data(my_list):
    data = np.zeros((segments + 1, len(classes)))
    for i, sub_list in enumerate(my_list):
        for elt in sub_list:
            data[elt, i] = 1
    return data

data = create_data(my_list)
print(data)
# [[0. 0. 0.]
#  [0. 0. 0.]
#  [0. 0. 1.]
#  [1. 0. 1.]
#  [0. 1. 1.]
#  [1. 1. 1.]
#  [0. 0. 1.]
#  [1. 1. 1.]
#  [0. 0. 0.]]

y_pos = np.arange(len(classes))
# left alignment of data starts at zero
left = np.zeros(len(my_list)) - cell_width/2


##########################
#       Create plot      #
##########################
# Set sea born for prettier graph
seaborn.set()
# create figure
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111)
# Set X axis (shifted)
ax.set_xlim((min(nb_x_range)-cell_width/2, max(nb_x_range)+cell_width/2))

# For each cell
for d in data:
    # Define color for each row
    colors = [colors_def[classes[i]][bi] for i, bi in enumerate(d)]
    # e.g. colors = [colors_def["A"][d[0]], colors_def["B"][d[1]], colors_def["C"][d[2]]]

    # Draw cell
    ax.barh(y_pos, cell_width,
            height=1,           # Heights of horizontal bars
            color=colors,       # Colors
            left=left)          # Left padd from y-axis
    # Update margin
    left += cell_width

# Axis graduation
ax.set_yticks(y_pos)
ax.set_xticks(nb_x_range)
ax.set_yticklabels(classes)
ax.set_xlabel('Stacked bar')

plt.show()

输出如下所示: enter image description here

关于python-3.x - 如何在 Python 中创建具有每个变量值之间差距的堆积条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56378621/

相关文章:

algorithm - 给定节点数和边数,找到强连接的最大节点数

python-3.x - 当纸张本身打印有角点/线条时,如何找到纸张的角点?

python - 如何在 json 格式的字符串中使用 str.format?

python - 如何按时间间隔调整 Bokeh x 轴标记

r - 查找两个顶点(节点)之间的所有路径

linux - Linux 上的 FORTRAN 图形库

python - 使用 matplotlib 绘图 : hours shown as float

python - 无法根据第一列值将列拆分为多列

python - 类型错误 : 'FirefoxWebElement' object is not iterable

algorithm - 使用什么算法来确定使系统进入 "Zero"状态所需的最少操作数?