- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在用 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) .
在这里,我将使用 matplotlib 中的 hbar
向您展示类似的输出。主要思想是重建细胞网格。每行代表一个类(例如 A
、B
或 C
)。每行由相同数量的单元格组成。每个单元格具有相同的宽度。单元格的颜色由数据的二进制转换定义。
要调整 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()
关于python-3.x - 如何在 Python 中创建具有每个变量值之间差距的堆积条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56378621/
我使用 Dojo fadeIn 和 fadeOut 以及一个计时器旋转了三个堆叠图像。只有最后一个的 href 可用。是否也可以旋转 href? 这是它的 CSS: #main-slides
给定一个 numpy 数组,我想总结统一的元素 block 以形成一个新的、更小的数组。它与分箱类似,但不是按频率分箱。除了通过示例(如下)之外,我不确定如何描述它。 问题:是否有用于此的函数或更清晰
我正在尝试实现某种按钮控制的幻灯片放映,其中包括用于页面顶部全 Angular 图片的 div,用于页面顶部的 div页面底部的另一张全 Angular 图片和中央内容的最终 div(包括控制“幻
嘿,我正在使用 D3JS 作为图表库,我真的很想利用气泡图中的超酷功能。上主D3JS chart站点下面的Bubble Chart用来比较两组数据: Bubble Chart . 我想知道是否有人真的
我是一名优秀的程序员,十分优秀!