简体   繁体   中英

ax.locator_params(nbins=k) does not work in matplotlib

I have this simple piece of code where I try to plot simple graph while limiting number of x ticks. There are hundreds of items in iters variable and if they get plotted it would just create one fat black line. However, ax.locator_params does not work and the number of ticks aren't reduced. I have tried setting it on plt object, but no help. I also tried specifying x and y axes in locator_params, but no help as well. Finally, I have tried moving ax.locator_params before and after ax.plot , but nothing seemed to help. I am completely out of ideas.

fig, ax = plt.subplots(1, 1, figsize=(20,10))
ax.locator_params(tight=True, nbins=4)
ax.plot(iters, vals)
plt.xticks(rotation=30)
plt.show()

locator_params() with nbins= is only supported for numerical axes where the tick positions are set via MaxNLocator .

To get the same effect with text ticks, the current ticks can be stored in a list ( get_xticks ) and then be replaced by a subset. Note that changes to ticks (and to limits) should be called after the main plot functions.

xticks = ax.get_xticks()
ax.set_xticks(xticks[::len(xticks) // 4]) # set new tick positions
ax.tick_params(axis='x', rotation=30) # set tick rotation
ax.margins(x=0) # set tight margins

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM