matplotlib条的顺序不正确

2024-04-27 02:36:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个条形图,其中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

^{pr2}$

原因是什么?我该怎么解决? 谢谢!在


Tags: from列表titlefigmaxwhitemembersset
1条回答
网友
1楼 · 发布于 2024-04-27 02:36:09

大卫的评论是正确的。你可以通过使用数值来解决这个问题 将月份指定为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

相关问题 更多 >