Shawn
Shawn

Reputation: 382

Matplotlib colorbar not showing labels for 2 discrete values

With an array of 3 discrete values I can use imshow to create a colorbar.

import numpy as np
from matplotlib import pyplot as plt

img_data1 = np.random.choice([0,1,2], size=100).reshape((10,10))

plt.imshow(img_data1)
plt.colorbar(ticks = [0,1,2], values = [0,1,2])

Produces:
enter image description here

But if the array only has 2 discrete values, [0,1], the colorbar labels are missing.

img_data2 = np.random.choice([0,1], size=100).reshape((10,10))

plt.imshow(img_data2)
plt.colorbar(ticks = [0,1], values = [0,1])

Produces:
enter image description here

How can I make the the color bar with 2 values have ticks marks and labels?

Upvotes: 1

Views: 1162

Answers (1)

Zephyr
Zephyr

Reputation: 12496

Your code work fine for me:

enter image description here

I am using matplotlib 3.4.2. Try to update your package if it is not up to date.


In any case, you can customize colorbar labels with:

cbar = plt.colorbar(ticks = [0,1], values = [0,1])
cbar.ax.get_yaxis().set_ticks([0, 0.25, 0.5, 0.75, 1]) # pass the array of labels you want

enter image description here

Upvotes: 1

Related Questions