gpt4 book ai didi

python - matplotlib 条形图的顺序不正确

转载 作者:太空宇宙 更新时间:2023-11-03 14:23:28 27 4
gpt4 key购买 nike

我有一个条形图,其中 y 轴是从一月到十二月的月份列表,x 轴值按相应顺序存储在另一个列表中。当我绘制图表时,月份的顺序会混淆。

In:  

fig, ((ax1, ax2)) = plt.subplots(nrows=1, ncols=2, figsize=(10,5), sharex='row')

fig.suptitle("Income from members and supporters", fontsize=14)

ax1.barh(months, tag_max)
ax1.set_facecolor('white')
ax1.set_title("Maximum income from members")

ax2.barh(months, tam_max)
ax2.set_facecolor('white')
ax2.get_yaxis().set_visible(False)
ax2.set_title('Maximum income from supporters')

输出:

enter image description here

In:

months

Out:

['January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December']

原因是什么?我该如何解决?谢谢!

最佳答案

DavidG 的评论是正确的。您可以通过使用酒吧位置的数值来解决这个问题将月份指定为 yticklabels

from matplotlib import pyplot as plt
import numpy as np

months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
]

tag_max = np.random.rand(len(months))
tam_max = np.random.rand(len(months))

yticks = [i for i in range(len(months))]

fig, ((ax1, ax2)) = plt.subplots(nrows=1, ncols=2, figsize=(10,5), sharex='row')

fig.suptitle("Income from members and supporters", fontsize=14)

ax1.barh(yticks, tag_max)
ax1.set_facecolor('white')
ax1.set_title("Maximum income from members")
ax1.set_yticks(yticks)
ax1.set_yticklabels(months)


ax2.barh(yticks, tam_max)
ax2.set_facecolor('white')
ax2.get_yaxis().set_visible(False)
ax2.set_title('Maximum income from supporters')

plt.show()

这给出了以下输出:

result of the given code

关于python - matplotlib 条形图的顺序不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47790221/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com