may
may

Reputation: 1185

Formatting datetime in matplot Python

I am having problems to adjust the datetime in a better way to visualize in my graph. Here is my code:

fig = plt.figure()
new.plot(title='(Graph)',figsize=(10,7), legend=None)

plt.tick_params(axis="both", which="both", bottom="off", top="off",    
                            labelbottom="on", left="off", right="off", labelleft="on")   
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5), frameon=False)
ax = plt.subplot(111)   
ax.spines["top"].set_visible(False)    
ax.spines["bottom"].set_visible(True)    
ax.spines["right"].set_visible(False)    
ax.spines["left"].set_visible(False)    
ax.get_xaxis().tick_bottom()    
ax.get_yaxis().tick_left()
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
pp.savefig(bbox_inches='tight')
pp.close()

I tried to add this library and in the ax nominations:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime
xfmt = mdates.DateFormatter('%Y-%m-%d %H:%M:%S')
ax.xaxis.set_major_formatter(xfmt)

enter image description here

Upvotes: 0

Views: 115

Answers (2)

may
may

Reputation: 1185

I just added the following line and it did it automatically

plt.gcf().autofmt_xdate()   

Upvotes: 0

Joe
Joe

Reputation: 12417

You can try rotating the labels adding the paramenter labelrotation https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.tick_params.html:

plt.tick_params(axis="both", which="both", bottom="off", top="off",    
                        labelbottom="on", left="off", right="off", 
                        labelleft="on", labelrotation=45)

Upvotes: 1

Related Questions