ATP
ATP

Reputation: 643

Python 3 Adding a Colorbar with Matplotlib

I've done a fair amount of research on adding a colorbar to a plot but I'm still really confused about how to add one. The examples I've seen use different ways of doing so, which just confuses me because I don't get what the "right" way is.

I've seen there is a colorbar method and a colorbar() function, so what should one use to simply add a colorbar?

Some examples do this:

fig,ax = plt.subplots()
s = ax.scatter(x,y,cmap = coolwarm)
matplotlib.colorbar.ColorbarBase(ax=ax, cmap=coolwarm, values=sorted(v),
                             orientation="horizontal")

While some others simply call the function:

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
image = np.random.poisson(10., (100, 80))
i = ax.imshow(image, interpolation='nearest')
fig.colorbar(i)

I'm probably missing something here, but I just don't see how these both create a colorbar (I just copied the code for the colorbar and excluded that of the data).

My question is simply: what is the simplest way to add a colorbar to a plot? Thanks!

Upvotes: 4

Views: 5952

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339745

The first example you quote creates an instance of ColorbarBase. This is usually not the recommended way; there might be some exceptions, but in general there is absolutely no reason to use this.

The second example you quote is one or even the way to create a colorbar inside a figure. Using this, you are on the save side. Using the colorbar method of the figure instance makes it clear in which figure to place the colorbar and supplying the respective ScalarMappable (in this case an AxesImage) ensures that the colorbar uses the correct colors from that ScalarMappable.

fig, ax = plt.subplots()
im = ax.imshow(image)
fig.colorbar(im)

or

fig, ax = plt.subplots()
sc = ax.scatter(x,y, c=something)
fig.colorbar(sc)

There is an even easier method, which would be to simply call

plt.colorbar()

Note however that this may lead to confusions as it tries to automatically determine the plot for which the colorbar should be created. Thus, there is some chance that it fails and I would not recommend using it.

Upvotes: 4

Related Questions