How To Force Set X Ticks On Matplotlib, Or Set Datetime Type With No Year
Solution 1:
You can set the ticks used for the x axis via ax.set_xticks()
and labels via ax.set_xticklabels()
.
For instance you could just provide that method with a list of dates to use, such as every 20th value of the current pd.DataFrame
index (df.index[::20]
) and then set the formatting of the date string as below.
# Get the current axis
ax = plt.gca()
# Only label every 20th value
ticks_to_use = df.index[::20]
# Set format of labels (note year not excluded as requested)
labels = [ i.strftime("%-H:%M") for i in ticks_to_use ]
# Now set the ticks and labels
ax.set_xticks(ticks_to_use)
ax.set_xticklabels(labels)
Notes
If labels still overlap, you could also rotate the them by passing the rotatation argument (e.g. ax.set_xticklabels(labels, rotation=45)
).
There is a useful reference for time string formats here: http://strftime.org.
Solution 2:
I faced similar issue with my plot
Matplotlib automatically handles timestamps on axes, but only when they are in timestamp format. Timestamps in index
were in string format, so I changed read_csv
to
pd.read_csv(file_path, index_col=[0], parse_dates=True)
Try changing the index to timestamp format. This solved the problem for me hope it does the same for you.
Post a Comment for "How To Force Set X Ticks On Matplotlib, Or Set Datetime Type With No Year"