How to change numbers on axis of colour bar

41 views Asked by At

I have produced a contour plot and have a colour bar but it's labels are such random numbers which I assume just comes from the data and I've been trying to find a way to relabel it so the numbers go from 1-12 instead and go up in integers. Is there any way I can do this? My colourbar

I tried changing the limits but it didn't change anything at all.

3

There are 3 answers

1
Muhammed Yunus On BEST ANSWER

When the colour bar gradient is smooth, I've found this works well:

enter image description here

#Create the colour bar
cbar = plt.colorbar() #alternatively: plt.colorbar(ticks=range(1, 13))

#Adjust ticks and trim the limits
cbar.set_ticks(range(1, 13))
cbar.ax.set_ylim(1, 12) #optional extra, to clip the overhang

If the gradient wasn't as smooth (i.e. fewer levels in the contour plot), this method wouldn't work as well.


Reproducible example

import matplotlib.pyplot as plt

#Test data
import numpy as np
xx, yy = np.meshgrid(*[np.linspace(0, 1)]*2)
z = np.cos(xx**2) * 9 + np.sin(yy**2) * 9 - 4

#Plot and adjust colour bar ticks
plt.contourf(xx, yy, z, cmap='PiYG', levels=100)
plt.gcf().set_size_inches(8, 3)
plt.axis('off')


cbar = plt.colorbar(label='colour bar label')
#alternatively: plt.colorbar(ticks=range(1, 13))

#Adjust ticks and trim limits
cbar.set_ticks(range(1, 13))
cbar.ax.set_ylim(1, 12) #optional extra, to clip the overhang
0
climate-coder On

Reading up on Matplotlib's documentation, you should have the answer. Let me reproduce that piece of code to suit your particular situation.

You need to manually adjust the tick labels on the instance of the figure. I've left comments on the last two lines of code for your reference.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
from numpy.random import randn


data = np.random.randint(1, 12, size=(4, 4))

fig, ax = plt.subplots()

cax = ax.imshow(data, cmap=cm.coolwarm)
ax.set_title('Gaussian noise with vertical colorbar')


# this is where the magic happens. 
# I first create the labels on the color map
ticks = np.linspace(1, 12, 12)

# I call in the colorer method on the fig instance previously instantiated and assign ticks
cbar = fig.colorbar(cax, ticks=ticks)
0
Chirantan Degloorkar On

What you can do here is use the set_ylim property of the colorbar.

Here's how you can do that -

colorbar().ax.set_ylim(0, 1)