show date in ranges in python plot graph

Question:

I have plotted a graph of a data in python using the following code, this is the data

{'2022-01-30': 50, '2022-01-31': 152, '2022-02-01': 41, '2022-02-02': 50,'2022-02-03': 50, '2022-02-04': 50,
'2022-02-05': 50, '2022-02-06': 50, '2022-02-07': 50, '2022-02-08': 50, '2022-02-09': 50, ......., '2022-09-30': 50, }

df = pd.Series(data, name='Quantity').rename_axis('Date').reset_index()
df.plot(kind='scatter', x='Date', y='Quantity')
plt.show()

and it gave me the graph but the days which I expected to be in range are all squashed to the point that it was not visible

I expected the date to come out in ranges like 2022-01-30, 2022-02-28, etc or 2022-01-30, 2022-03-31 etc

Please how can i achieve that

Asked By: William Page

||

Answers:

You have multiple possibilities:

import matplotlib.dates as mdates

ax = df.plot(kind='scatter', x='Date', y='Quantity')

Example 1: ax.xaxis.set_major_locator(mdates.DayLocator(interval=3))

enter image description here

Example 2: ax.xaxis.set_major_locator(mdates.MonthLocator(bymonthday=-1))

enter image description here

You can know more by reading the matplotlib.dates documentation.

Answered By: Corralien
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.