Python:在contourf图中设置零值颜色,其中需要对数比例颜色条

时间:2017-12-03 06:51:52

标签: python matplotlib

我正在尝试从一些数据文件制作轮廓图。我遇到的麻烦是我希望颜色条上最小值以下的z值与最小值颜色相同。 当使用例如线性标度时,这很容易。 extend="both"的{​​{1}}选项,或者使用contourf作为色彩映射。不幸的是,使用logscale时这些选项都不起作用。任何人都可以建议解决方法?我只是想摆脱下面情节中的白色区域:

enter image description here

cmap.set_under()

1 个答案:

答案 0 :(得分:0)

extend关键字不适用于日志比例似乎是known issue matplotlib

粗略的解决方法是将所有值强制转换为绘制范围(注意min_drawn_valuemax_drawn_value上的注释,值必须在该范围内):

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()

enter image description here