FrankTheTank
FrankTheTank

Reputation: 1689

How to set number of ticks in plt.colorbar?

When I plot a matrix with a colorbar, then the colorbar has 10 ticks. Since the colorbar has to be pretty small, the ticklabels overlap. Therefore I want to reduce the number of ticks from 10 to 5. I do not want to reduce the font size!

Is there an easy way to do this? I do not want to set the ticks manually...

Upvotes: 28

Views: 40781

Answers (3)

Sam A.
Sam A.

Reputation: 453

I see that the two solutions using cbar.ax.locator_params and ticker don't seem to be consistent in getting the same results always. ticker seems to be consistent in getting the number of bins, while locator_params seems to want to enforce that the endpoints have ticks (rather than, say a tick mark near the endpoint but not at it). I am not sure what the difference in behavior is, but suffice it to say they are not identical. Again, this assumes that you want the number of ticks to be exactly what you specify. I'd say that if you want to set the number of ticks (but have their positions determined automatically) and want to supply your own different labels, then maybe use ticker to make sure these are consistent (although usually if you supply your own labels you would want the positions to be guaranteed).

from matplotlib import ticker
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(4)
nbins = 7

z = np.random.normal(size=(5,10))
fig, ax = plt.subplots(1, 1)
img = ax.matshow(z, cmap="bwr_r", aspect='auto', vmin=-10, vmax=10)
cbar = fig.colorbar(img)
cbar.ax.locator_params(nbins=nbins)
ax.set_title('locator_params')
plt.show() 

fig, ax = plt.subplots(1, 1)
img = ax.matshow(z, cmap="bwr_r", aspect='auto', vmin=-10, vmax=10)
cbar = fig.colorbar(img)
tick_locator = ticker.MaxNLocator(nbins=nbins)
cbar.locator = tick_locator
cbar.update_ticks()
ax.set_title('ticker')
plt.show()

enter image description here enter image description here

Upvotes: 0

ezatterin
ezatterin

Reputation: 756

For the record, this is now possible also via:

cbar = plt.colorbar()
cbar.ax.locator_params(nbins=5)

which talks to ticker.MaxNLocator.

Upvotes: 16

Bonlenfum
Bonlenfum

Reputation: 20155

The MaxNLocator ticker might suit your purposes?

class matplotlib.ticker.MaxNLocator

Select no more than N intervals at nice locations

For example:

from matplotlib import ticker

# (generate plot here)
cb = plt.colorbar()
tick_locator = ticker.MaxNLocator(nbins=5)
cb.locator = tick_locator
cb.update_ticks()
plt.show()

Upvotes: 51

Related Questions