Reducing the number of x-axis ticks on Matplotlib plot from Panda

Question:

I need to reduce or manually set the number of ticks on the x-axis of a Matplotlib line plot. This question has been asked many times here, I’ve gone through as many of those answers as I can find and through the Matplotlib docs and I haven’t found a solution I can get working so I’m hoping for some help.

I have a Python dictionary with two sets of key:value pairs – datetime.datetime and float. There’s hundreds of values in each set – but here’s a snippet of the first elements just for reference:

ws_kline_dict_01 = {'time': [datetime.datetime(2023, 2, 15, 10, 35, 8)], 'close': [22183.07]}

I’ve converted that dictionary to a Pandas dataframe so I can see it more easily in Jupyter and also stripped out the year, month and day from ‘time’ using:

df_kline_dict_01 = pd.DataFrame(ws_kline_dict_01)
df_kline_dict_01['time'] = df_kline_dict_01['time'].dt.strftime('%H:%M:%S')

When I plot this via Matplotlib using ‘time’ as the x-axis – it prints every value as a tick which is way too cluttered (see ‘Plot: Post-Panda format’ below).

If I leave the datetime.datetime in its original form – Matplotlib seems to auto-select how many values it displays and it displays "Day Hour:Minutes" instead of "Hour:Minutes:Seconds" – which isn’t working for me (see ‘Plot: Pre-Panda format’ below).

I’ve tried plt.locator_params(axis='x', nbins=n) – but this is giving me an error message:

"UserWarning: 'set_params()' not defined for locator of type <class 'matplotlib.category.StrCategoryLocator'>".

For reference – this is the code I’m using to produce the plot:

plt.plot(df_kline_dict_01['time'], df_kline_dict_01['close'], color = 'green', label = 'close')
plt.xticks(rotation=45, ha='right')
plt.show()

How do I (at least) reduce or (ideally) explicitly set the number of values/ticks shown on the x-axis?
Seems like this should be a pretty simple formatting task – but so far it’s beating me and I’d appreciate some help getting this sorted.

Plot: Pre-Panda format
Plot: Post-Panda format

Asked By: robobozo

||

Answers:

Put some parameters for the locations like $plt.xticks(np.arange(min,max,step),rotation=45, ha=’right’)$
fill the min and max and steps as you wish

Answered By: SaeidAli

Here is a possible solution using the .xaxis.set_major_locator() method. You can adjust the max_xticks variable to suit your use-case.

...
df_kline_dict_01['time'] = df_kline_dict_01['time'].dt.strftime('%H:%M:%S')
fig, ax = plt.subplots()
ax.plot(df_kline_dict_01['time'], df_kline_dict_01['close'], color='green', label='close')

max_xticks = 6
ax.xaxis.set_major_locator(ticker.MaxNLocator(max_xticks))

plt.xticks(rotation=45, ha='right')
plt.show()

Note: I assigned max_xticks = 6 so it helps you understand the code otherwise you could just set the value in .MaxNLocator(6) in the next line of code.

Answered By: Jamiu S.
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.