Home > database >  AttributeError: 'tuple' object has no attribute 'set_xlim' matplotlib python
AttributeError: 'tuple' object has no attribute 'set_xlim' matplotlib python

Time:04-14

I am trying to plot plot hist with dates in x axes and adjust dates. My code is

    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()

and I get an error:

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

What am I doing wrong? thx

CodePudding user response:

plt.hist does not return the axis, it returns the bins of the histogram and other metadata. Just call xlim on plt itself.

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

Caution: This solves the problem when the axes has numbers... I do not know how it will behave with dates. Check the xlim docs of the best explanation.

CodePudding user response:

Use plt.xlim instead.

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()

This is the code I tested this on:

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()
  • Related