2

Here is my code:

# Graph for both infections and closures

# # plotting the points  
plt.plot(graph_date, graph_daily_infections, label = "Infections per day")
plt.plot(graph_date, graph_total_infections, label = "Infection overall")
plt.plot(graph_date, graph_daily_closure, label = "Closures per day")  
plt.plot(graph_date, graph_total_closure, label = "Closure overall") 
# # naming the x axis 
plt.xlabel('Date') 
# naming the y axis 
plt.ylabel('Number of Infections/Closure') 
# giving a title to my graph 
plt.title('Daily infections and closure overtime \n Infection Rate: {0} | Closure Threshold: {1}'.format(infectionRate,closeThreshold)) 
# show a legend on the plot
plt.legend()
# # changing the scale of the x ticks at the bottom

# # plt.locator_params(nbins=4)

# # set size of the graph
plt.rcParams["figure.figsize"] = (20,15)
# # function to show the plot

plt.show()

The problem with this code is that the dates are squashed together on the x axis when they are being displayed. See below: enter image description here

Is there a way to only show the months, or to only shows the months and the years ? the interval for which the graph should display the data is for 4 months so showing only the months / year and month would be ideal. Thanks!

2 Answers 2

2

Try using autofmt_xdate() to auto format the x-axis.

According to matplotlib.org, you would have to add this before plt.show():

fig, ax = plt.subplots()
ax.plot(date, r.close)

# rotate and align the tick labels so they look better
fig.autofmt_xdate()

And for the months and years, you can add:

ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')
Sign up to request clarification or add additional context in comments.

Comments

0

Here is another recipe:

import matplotlib.dates as mdates
 
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m"))

More information about different format options in matplotlib.mdates module.

Comments

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.