Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discrete logarithmic colorbar in matplotlib

Tags:

colormap

I want to create a pcolormesh plot with a discrete logarithmic colorbar. Some resolution is lost, but the matching between colors and values seems to be easier (at least for me) if the colormap is discrete.

The code snippet below produces a continuous log colormap with the preferred value range. How can I make it discrete? Here I found how to create a discrete linear colormap, but I couldn't extend it to log scale.

plt.pcolormesh(X,Y,Z,norm=mcolors.LogNorm(vmin=0.01, vmax=100.))
plt.colorbar()
fig  = matplotlib.pyplot.gcf()
fig.set_size_inches(4*2.5, 3*2.5)
plt.xlabel("X", horizontalalignment='right', x=1.0)
plt.ylabel("Y", horizontalalignment='right', y=1.0)
plt.tight_layout()

Continuous log scale

like image 761
Kitchensink Avatar asked Jun 28 '26 09:06

Kitchensink


1 Answers

The parameters boundaries and spacing='proportional' in plt.colorbar() do the trick. Using the example given by Talis:

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

X = np.arange(0, 50)
Y = np.arange(0, 50)
Z = np.random.rand(50, 50)*10

bounds = [0.1, 0.2, 0.5, .7, .8, .9, 1, 2, 3, 4, 5, 6, 7, 10]

plt.pcolormesh(X,Y,Z,vmin=min(bounds),vmax=max(bounds),norm=colors.LogNorm(), cmap='RdBu_r')
cbar = plt.colorbar(boundaries=bounds,spacing='proportional')
cbar.set_ticks(bounds)

enter image description here

like image 65
MKo Avatar answered Jul 01 '26 00:07

MKo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!