对数颜色条和等高线的色标

时间:2019-03-20 13:28:56

标签: python matplotlib contourf

我开发了以下MWE,其数据分散到两个非常不同的规模。我想制作一个轮廓图,可以很好地可视化数据。

from matplotlib import ticker
import numpy as np               
import matplotlib.pyplot as plt 
data = np.random.rand(25,25)
data2 = np.random.rand(25,25)*1e-32
data = np.hstack([data,data2])
xGrid, yGrid = np.meshgrid(np.linspace(0,1,data.shape[1]),np.linspace(0,1,data.shape[0]))

levels=np.logspace(np.log10(1e-6),np.log10(2),100)
locator = ticker.LogLocator(base=10)
cs = plt.contourf(xGrid, yGrid, data, levels, vmin = 1e-6, vmax = 2, locator=locator)
plt.colorbar(cs, ticks=locator)

使用上面的代码,我得到:enter image description here

我不明白为什么一半的值都是空白

1 个答案:

答案 0 :(得分:2)

好吧,由于另一个post,我发现了问题所在。需要使用选项extend =“ both”。不幸的是,该选项不适用于对数刻度。

解决方案是手动重新调整数据范围。下面提供了一个示例:

from matplotlib import ticker
import numpy as np               
import matplotlib.pyplot as plt 
data = np.random.rand(25,25)
data2 = np.random.rand(25,25)*1e-32
data = np.hstack([data,data2])
xGrid, yGrid = np.meshgrid(np.linspace(0,1,data.shape[1]),np.linspace(0,1,data.shape[0]))

levels=np.logspace(np.log10(1e-16),np.log10(2),100)
locator = ticker.LogLocator(base=10)

#mask data
dataMasked = np.where(data < 1e-16, 1e-16, data)

cs = plt.contourf(xGrid, yGrid, dataMasked, levels, vmin = 1e-16, vmax = 2, extend="both", locator=locator)
plt.colorbar(cs, ticks=locator)