'Easiest way to show all x-values in a plt.plot_date Python

What's the easiest way to show all x-values during when running plt.plot_date ? I saw another similar question but the code was so confusing that I could not understand the answer.

Here is my df:

month_year = ['2019-12', '2020-01', '2020-03', '2020-04', '2020-05', '2020-06', '2020-07', '2020-08', '2020-09', '2020-10',
             '2020-11', '2020-12', '2021-01', '2021-02', '2021-03', '2021-04', '2021-05', '2021-06', '2021-07', 
             '2021-09', '2021-10', '2021-11', '2021-12', '2022-01']

value = [3374, 1241,  388, 3272, 1946, 1648, 1491, 1014, 1432,  157, 1367, 568, 2081, 1293, 1755,  450, 1939, 
         1677,  846, 1700, 2581, 2078, 1797,  466]

df1 = pd.DataFrame({'month_year': month_year, 'value':value})
df1['month_year'] = pd.to_datetime(df1['month_year']).dt.to_period('M')

df1

enter image description here

And here is my plt code:

# Add title and axis names
plt.title('Distribuition of tenders per year-month')
plt.xlabel('year-month')
plt.ylabel('sum_of_tenders')

#Rotate:
plt.xticks(rotation=45)

#Plot:
plt.plot_date(df1['month_year'], 
              df1['value'], c = 'red')

enter image description here

How can I easily force all the x-values to appear?



Solution 1:[1]

If I understand that right, you first need to create an ax object, to get access to set_ticks and set_xticklabels. create simple data with the length of your df1 and then set them year_month dates as labels on that.

Is that what you need?

fig, ax = plt.subplots(1,1)

x = np.arange(0,len(df1),1)
y = df1['value']

ax.set_xticks(x)
ax.set_xticklabels(df1['month_year'],rotation='vertical')

ax.set_title('Distribuition of tenders per year-month')
ax.set_xlabel('year-month')
ax.set_ylabel('sum_of_tenders')
ax.plot(x,y, c= 'red')

plt.show()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1