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

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

A=[3,5,7]

B=[4,5,7]

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

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

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

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

最佳答案

其实你想画一个颜色表或者类似甘特图的东西。我不知道在 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()

输出如下所示:

https://stackoverflow.com/questions/56378621/

相关文章:

amazon-web-services - AWS ECR 如何限制除最新标签之外的重新标记

docker - 无法使用 docker login --password-stdin

reactjs - 使用 react-testing-library 时让 react-datepi

c# - 从不同的项目 .Net 访问 protobuf

google-sheets - 具有日期条件的 Google 表格摘要

python - Jupyter 笔记本 : how to run python shell com

mysql - 如果我定义一个卷,Docker-compose 将不会启动 MySQL

node.js - 在 Nexus 中获取最新版本的 Node 包

javascript - 当我在滚动功能上添加动画时,导航栏熄灭

google-drive-api - 从 Google Drive "Computers"获取文件到