1

I am using the following snippet to create a custom colorbar:

import pylab as pl
import numpy as np

a = np.array([[0,10000,100000,400000,500000]])
pl.figure(figsize=(9, 1.5))
mycmap = colors.ListedColormap(['yellow','orange','red','darkred'])
img = pl.imshow(a, cmap=mycmap)
pl.gca().set_visible(False)
cax = pl.axes([0.1, 0.2, 0.8, 0.6])
cbar=pl.colorbar(orientation='horizontal', cax=cax,spacing='proportional');
cbar.set_ticks([0,10000,100000,400000,500000])
cbar.set_ticklabels(['0','10000','100000','400000','500000'])

This is giving me a colorbar with regular intervals, although I have specified spacing='proportional': enter image description here

The intended result is, instead:

0-10000: yellow
10001-100000: orange
100001-400000: red
400001-500000: dark red

What am I doing wrong?

1
  • Do you want to set the ticklabels at the coloredges or do you want to have the colors represent the given values? Commented Dec 12, 2017 at 14:48

1 Answer 1

1

As can be seen when not turning the axes invisible, the colorbar is correctly representing the color of the data in the image.

enter image description here

If this is not what you want you should start by establishing how the data is represented in the image. Introducing a Normalization for the data to the colormap range is usually the way this is accomplished. Here a BoundaryNorm makes sense.

import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np

a = np.array([[0,10000,100000,400000,500000]])
plt.figure(figsize=(4, 2.5))

mycmap = matplotlib.colors.ListedColormap(['yellow','orange','red','darkred'])
norm = matplotlib.colors.BoundaryNorm(a[0], len(a[0])-1)
img = plt.imshow(a, cmap=mycmap, norm=norm)
cax = plt.axes([0.1, 0.1, 0.8, 0.1])
cbar=plt.colorbar(orientation='horizontal', cax=cax,spacing='proportional');

plt.show()

This now gives a meaningful representation with ticks at the edges of the colorranges.

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.