Python: Setting The Zero Value Color In A Contourf Plot, Where Log Scale Colorbar Is Required
I am trying to make a contour plot from some data files. The trouble I am having is that I want the z-values below the minimum on the color bar to be the same color as the minimum
Solution 1:
It appears that the extend
keyword not working with a log scale is a known issue with matplotlib
.
A crude workaround would be to coerce all the values into the drawn range (notice the comments on the min_drawn_value
and max_drawn_value
, the values must be inside that range):
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
N = 100 # number of points for plotting/interpolation
min_exp = -8
max_exp = -2
min_drawn_value = 1.000001 * 10.**min_exp # above 10.**min_exp
max_drawn_value = 0.999999 * 10.**max_exp # below 10.**max_exp
xi = np.linspace(0, 1, N)
yi = np.linspace(0, 1, N)
zi = np.random.rand(N, N) *\
10. ** np.random.randint(min_exp - 1, max_exp + 2, (N, N))
zi = np.sort(zi.flatten()).reshape(N,N)
# Coerce values outside of colorbar range to lie within
zi_masked = np.where(zi < 10.**min_exp, min_drawn_value, zi)
zi_masked = np.where(zi_masked > 10.**max_exp, max_drawn_value, zi_masked)
fig, (ax,ax2) = plt.subplots(ncols=2)
c1 = ax.contourf(xi, yi, zi, levels=10.**np.arange(min_exp, max_exp+1),
cmap=plt.cm.jet, norm=LogNorm())
c2 = ax2.contourf(xi, yi, zi_masked, levels=10.**np.arange(min_exp, max_exp+1),
cmap=plt.cm.jet, norm=LogNorm())
ax.set_title("direct plot of array")
ax2.set_title("coerce outlier values")
fig.colorbar(c1, ax=ax)
fig.colorbar(c2, ax=ax2)
fig.subplots_adjust(wspace=0.3)
plt.show()
Post a Comment for "Python: Setting The Zero Value Color In A Contourf Plot, Where Log Scale Colorbar Is Required"