0

Hi I am trying to change the x-axis into a month axis but cant seem to do it.
I can't find a way to insert the datetime axis, and when I do I run into errors.

This is my datetime variables, basically its simple, just want to create a weekly counter that starts on 2020 for 1 year:

date = pd.date_range(start='2020-01-01', periods=52, freq='w')

This is my plot code:

cumm19=fcst2019.cumsum()
cumm20=fcst2020.cumsum()
cumm20w=fcst2020w.cumsum()

plt.axhline(y=cumm19['no._of_cases'][51], color='r', label= '2019 numbers (15,910)')
plt.plot(cumm20[:21], label ='2020 current')
plt.plot(cumm20[20:], label ='2020 predictions')
plt.plot(cumm20w[20:], label ='2020 worse case predictions')
plt.xlabel('Months')
plt.ylabel('Cumulative no. of cases')
plt.legend()
plt.show()   

How do i combine them?

my current results

user7378789
  • 99
  • 1
  • 5

1 Answers1

0

If you set the datetime variable as the index of the dataframes, the x-axis ticks automatically get date labels with an appropriate format:

import numpy as np                 # v 1.19.2
import pandas as pd                # v 1.2.3
import matplotlib.pyplot as plt    # v 3.3.4
import matplotlib.dates as mdates

# Create sample datasets
date = pd.date_range(start='2020-01-01', periods=52, freq='w')
fcst2020 = pd.DataFrame(dict(fcst=np.repeat([500, 750], [21, 31])), index=date)
fcst2020w = pd.DataFrame(dict(fcst=np.repeat([500, 600], [21, 31])), index=date)

cumm20 = fcst2020.cumsum()
cumm20w = fcst2020w.cumsum()

# Plot data
plt.plot(cumm20[:21], label ='2020 current')
plt.plot(cumm20[20:], label ='2020 predictions')
plt.plot(cumm20w[20:], label ='2020 worse case predictions')
plt.axhline(y=15910, color='r', label= '2019 numbers (15,910)', zorder=0)
plt.xlabel('Months')
plt.ylabel('Cumulative no. of cases')
plt.legend()

plt.show()

xaxis_dates


You can customize the format of the tick labels by using the matplotlib dates DateFormatter:

# Edit x-axis tick labels
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m'))

plt.show()

xaxis_dates_formatted

Patrick FitzGerald
  • 3,280
  • 2
  • 18
  • 30