matplotlib 如何使堆叠条形图行共享同一轴

wz3gfoph  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(120)

我有一个使用matplotlib.pyplot的堆叠水平条形图。它会产生以下输出:

我希望x轴的宽度为100%,这样颜色将占据与样式相同的宽度,假设各个分段将更宽,以扩展到空闲空间。
我以为用相等的值除以100来填充numpy数组可以确保这些值按比例缩放。
但是,根据输出颜色,不会向外扩展。
有谁能给我指出解决这个问题的方向吗?
下面是一个可重现示例的代码。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

plt.rcParams.update(plt.rcParamsDefault)

dummy = {
    'colours': ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven'],
    'style': ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', '13', '14']
}

df = pd.DataFrame.from_dict(dummy, orient="index")

y_labels_colors = df.loc["colours"].dropna().tolist()
y_values_colors = np.full(len(y_labels_colors), len(y_labels_colors) / 100)

y_labels_styles = df.loc["style"].dropna().tolist()
y_values_styles = np.full(len(y_labels_styles), len(y_labels_styles) / 100)

fig, ax = plt.subplots(figsize=(12, 1))

cumulative_size_colors = 0
cumulative_size_styles = 0

for label, value in zip(y_labels_colors, y_values_colors):
    ax.barh("colours", value, left=cumulative_size_colors, color='lightskyblue', edgecolor='white', linewidth=1)
    cumulative_size_colors += value
    ax.text(cumulative_size_colors - value / 2, 0, label, ha='center', va='center')

for label, value in zip(y_labels_styles, y_values_styles):
    ax.barh("styles", value, left=cumulative_size_styles, color='lightsteelblue', edgecolor='white', linewidth=1)
    cumulative_size_styles += value
    ax.text(cumulative_size_styles - value / 2, 1, label, ha='center', va='center')

ax.set_frame_on(False)
ax.set_xticks([])

plt.show()

字符串

pqwbnv8z

pqwbnv8z1#

我通过修改来解决这个问题:From:

y_values_colors = np.full(len(y_labels_colors), len(y_labels_colors) / 100)
y_values_styles = np.full(len(y_labels_styles), len(y_labels_styles) / 100)

字符串
收件人:

y_values_colors = np.full(len(y_labels_colors), 1 / len(y_labels_colors))
y_values_styles = np.full(len(y_labels_styles), 1 / len(y_labels_styles))
``

By adjusting y_values_colors and y_values_styles to have equal values (1 divided by the number of items in each category). This ensures the space is evenly distributed for both "colours" and "styles" in the stacked bar chart.

相关问题