Implementing ticklabels keyword in plt.colorbar() by danuo · Pull Request #18884 · matplotlib/matplotlib · GitHub
Skip to content
44 changes: 35 additions & 9 deletions lib/matplotlib/colorbar.py
33 changes: 33 additions & 0 deletions lib/matplotlib/tests/test_colorbar.py
Original file line number Diff line number Diff line change
Expand Up @@ -705,3 +705,36 @@ def test_anchored_cbar_position_using_specgrid():
np.testing.assert_allclose(
[cx1, cx0],
[x1 * shrink + (1 - shrink) * p0, p0 * (1 - shrink) + x0 * shrink])


def test_colorbar_ticklabels_2():
fig = plt.figure()
plt.imshow(np.arange(100).reshape((10, 10)))
ticklabels = ['cat', 'dog']
cbar = plt.colorbar(ticks=[10, 90], ticklabels=ticklabels)
fig.canvas.draw()
for i, item in enumerate(cbar.ax.yaxis.get_ticklabels()):
assert ticklabels[i] == item.get_text()


def test_colorbar_ticklabels_3():
fig = plt.figure()
plt.imshow(np.arange(100).reshape((10, 10)))
ticklabels = ['cat', 'dog', 'elephant']
with pytest.warns(
UserWarning, match='The ticklabels need to be of the same '
'length as the ticks.'):
plt.colorbar(ticks=[10, 90], ticklabels=ticklabels)
fig.canvas.draw()


def test_colorbar_ticklabels_no_ticks():
fig = plt.figure()
plt.imshow(np.arange(100).reshape((10, 10)))
ticklabels = ['cat', 'dog', 'dog']
with pytest.warns(
UserWarning, match='To set explicit ticklabels, call colorbar'
'\\(\\) with ticks keyword or use set_ticks\\(\\) '
'method first.'):
plt.colorbar(ticks=None, ticklabels=ticklabels)
fig.canvas.draw()
51 changes: 27 additions & 24 deletions lib/mpl_toolkits/axes_grid1/colorbar.py