我有一个使用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()
字符串
1条答案
按热度按时间pqwbnv8z1#
我通过修改来解决这个问题:From:
字符串
收件人:
型