AttributeError: 'tuple' object has no attribute 'set_xlim' matplotlib python

AttributeError: 'tuple' object has no attribute 'set_xlim' matplotlib python

我正在尝试在 x 轴上绘制带有日期的 plot hist 并调整日期。 我的密码是

    ax=plt.hist(df[ (df['disease']==1) & (df['FARM_NUM']==1282000)]['DATE'],bins=20)
   ax.set_xlim([datetime.date(2020, 3, 15), datetime.date(2021, 7, 1)])
   plt.xticks(rotation=90)
   plt.show()

我得到一个错误:

AttributeError: 'tuple' object has no attribute 'set_xlim'

我做错了什么? 谢谢

plt.hist 不是 return 轴,它 return 是直方图和其他元数据的 bin。只需在 plt 本身上调用 xlim。

plt.xlim(left=leftValue, right=rightValue)

注意:这解决了坐标轴有数字时的问题...我不知道它会如何处理日期。勾选最佳解释xlim docs

改用plt.xlim

plt.hist(df[ (df['disease']==1) & (df['FARM_NUM']==1282000)]['DATE'],bins=20)
plt.xlim([datetime.date(2020, 3, 15), datetime.date(2021, 7, 1)])
plt.xticks(rotation=90)
plt.show()

这是我测试的代码:

import numpy as np
nums = np.random.randint(1, 4, 100)

plt.figure(figsize = (20,5))
plt.hist(nums)
plt.xlim(left = 1, right = 5)
plt.xticks(roation = 90)
plt.show()