首页 > 解决方案 > Matplotlib 修复 y 轴

问题描述

我正在尝试使用 matplotlib 创建水平条形图。我的数据点是以下两个数组

distance = [100, 200, 300, 400, 500, 3000]
value = [10, 15, 50, 74, 95, 98]

我生成水平条形图的代码如下

plt.barh(distance, value, height=75)
plt.savefig(fig_name, dpi=300)
plt.close()

问题是我的图像是这样的

https://imgur.com/a/Q8dvHKR

有没有办法确保所有块的宽度相同并跳过 500 到 300 之间的空格

标签: python-3.xmatplotlibbar-chart

解决方案


您可以这样做确保 Matplotlib 将您的标签视为标签,而不是数字。您可以通过将它们转换为字符串来做到这一点:

import matplotlib.pyplot as plt

distance = [100, 200, 300, 400, 500, 3000]
value = [10, 15, 50, 74, 95, 98]
distance = [str(number) for number in distance]
plt.barh(distance, value, height=0.75)

请注意,您必须更改高度。


推荐阅读