1

I have a dataframe like this:

date_deaths = data[['date', 'deaths']]
deaths_by_date = date_deaths.groupby('date')['deaths'].sum()

I cannot get my plot to show xticks. When I plot without formatting I get daily ticks however, I want ticks by month

enter image description here

Code for the plot:

months = mdates.MonthLocator()

#Plot deaths over time.

fig, ax = plt.subplots(figsize = (12,5))
ax.plot(deaths_by_date, 'r--')
plt.ylabel("Deaths", fontsize = 12)
plt.title('Covid-19 Deaths in the United States', fontsize = 14)

#Format ticks
ax.xaxis.set_major_locator(months)
ax.grid(True)

plt.show()

Any help would be appreciated!

Update: Turns out I just needed to change the index to datetime. This code solved the issue beautifully.

deaths_by_date.index = pd.to_datetime(deaths_by_date.index)

Zachary Wyman
  • 299
  • 2
  • 11
  • https://matplotlib.org/3.2.1/gallery/text_labels_and_annotations/date.html – BigBen Aug 03 '20 at 21:13
  • @BigBen I just tried using that and while the plot looks much cleaner, now no ticks are showing up. I ran an error message when ```datemin = np.datetime64(data['date'][0], 'Y') datemax = np.datetime64(data['date'][-1], 'Y') + np.timedelta64(1, 'Y') ax.set_xlim(datemin, datemax)``` I tried to do this – Zachary Wyman Aug 03 '20 at 21:27
  • You don't need to do that... you just need `ax.xaxis.set_major_locator(months)`. – BigBen Aug 03 '20 at 21:29
  • @BigBen That's what I did at first. This resulted in no ticks shown on the x-axis. I'll edit my question accordingly. – Zachary Wyman Aug 03 '20 at 21:33
  • Pandas and Matplotlib don't work well together as far as dates go. – BigBen Aug 03 '20 at 21:34
  • Does https://stackoverflow.com/a/57600446/10315163 help you? – Ynjxsjmh Aug 04 '20 at 04:22
  • @Ynjxsjmh Actually quite helpful. I figured out I just needed to change the index to datetime. Thanks for the help – Zachary Wyman Aug 04 '20 at 20:06
  • @ZacharyWyman If that link helps you figure out how to solve your problem, you can answer your own question so that your answer can help those people who encounter the same problem as you. – Ynjxsjmh Aug 05 '20 at 02:06
  • @Ynjxsjmh I did! I put an edit at the end. – Zachary Wyman Aug 05 '20 at 16:26

0 Answers0