Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Matplotlib Colorbar Ticks

There are many matplotlib colorbar questions on stack overflow, but I can't make sense of them in order to solve my problem.

How do I set the yticklabels on the colorbar?

Here is some example code:

from pylab import *
from matplotlib.colors import LogNorm
import matplotlib.pyplot as plt

f = np.arange(0,101)                 # frequency 
t = np.arange(11,245)                # time
z = 20*np.sin(f**0.56)+22            # function
z = np.reshape(z,(1,max(f.shape)))   # reshape the function
Z = z*np.ones((max(t.shape),1))      # make the single vector to a mxn matrix
T, F = meshgrid(f,t)
fig = plt.figure()
ax = fig.add_subplot(111)
plt.pcolor(F,T,Z, norm=LogNorm(vmin=z.min(),vmax=z.max()))
plt.xlim((t.min(),t.max()))
mn=int(np.floor(Z.min()))        # colorbar min value
mx=int(np.ceil(Z.max()))         # colorbar max value
md=(mx-mn)/2                     # colorbar midpoint value
cbar=plt.colorbar()              # the mystery step ???????????
cbar.set_yticklabels([mn,md,mx]) # add the labels
plt.show()
like image 200
sequoia Avatar asked Jul 16 '11 05:07

sequoia


People also ask

How do you change the color bar label in MatPlotLib?

Method 2: Change and Rotate the position of the label To rotate the colorbar labels we will use set_xticklabels() and set_yticklabels() methods for horizontal and vertical.

How do I add a legend to my Colorbar?

To plot data and draw a colorbar or legend in one go, pass a location (e.g., colorbar='r' or legend='b' ) to the plotting command (e.g., plot or contour ). To pass keyword arguments to the colorbar and legend commands, use the legend_kw and colorbar_kw arguments (e.g., legend_kw={'ncol': 3} ).

How do I create a minor tick in MatPlotLib?

MatPlotLib with Python Create a figure and a set of subplots. Plot x and y data points using plot() method. To locate minor ticks, use set_minor_locator() method. To show the minor ticks, use grid(which='minor').


2 Answers

A working example (for any value range) with five ticks along the bar is:

m0=int(np.floor(field.min()))            # colorbar min value
m4=int(np.ceil(field.max()))             # colorbar max value
m1=int(1*(m4-m0)/4.0 + m0)               # colorbar mid value 1
m2=int(2*(m4-m0)/4.0 + m0)               # colorbar mid value 2
m3=int(3*(m4-m0)/4.0 + m0)               # colorbar mid value 3
cbar.set_ticks([m0,m1,m2,m3,m4])
cbar.set_ticklabels([m0,m1,m2,m3,m4])
like image 44
treerink Avatar answered Sep 22 '22 13:09

treerink


Update the ticks and the tick labels:

cbar.set_ticks([mn,md,mx])
cbar.set_ticklabels([mn,md,mx])
like image 140
Eryk Sun Avatar answered Sep 22 '22 13:09

Eryk Sun