cristian9804
cristian9804

Reputation: 93

python matplotlib dates are squashed together

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!

Upvotes: 2

Views: 1512

Answers (2)

Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83716

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.

Upvotes: 0

pintert3
pintert3

Reputation: 117

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')

Upvotes: 2

Related Questions