0

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

3
  • stackoverflow.com/questions/34388800/… Commented Apr 14, 2022 at 6:49
  • plt.hist obviously returns a tuple. What object were you expecting? Commented Apr 14, 2022 at 6:51
  • Have you tried defining the axis object and use it subsequently fig, ax = plt.subplots(); ax.hist(....? You may also want to read about the differences between pyplot and OOP. Commented Apr 14, 2022 at 7:14

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Can you share the dataframe you are working on?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.