'plt.contourf' 具有给定的对数刻度级别数

'plt.contourf' with given number of levels in logscale

有了这些线条,目前我有这样的身材。

fig, ax = plt.subplots()
X, Y = np.meshgrid(x, y)
cs = ax.contourf(X, Y, Z, 50, cmap=cm.get_cmap('jet')) # linear mapping
#cs = ax.contourf(X, Y, Z, 50, locator=ticker.LogLocator(), cmap=cm.get_cmap('jet')) # log mapping
cbar = fig.colorbar(cs)
plt.show()

现在我想以对数比例绘制它,所以如果我激活注释行,我会得到这种结果,它似乎忽略了设置为“50”的 'levels' 参数。

我已经达到了这个 post (Python matplotlib contour plot logarithmic color scale),但我很确定有一种方法我不必手动设置所有级别的值。

有没有人有评论,或任何其他方便的 python 多级对数等高线图函数?

将级别数设置为整​​数不适用于 logscale,但您可以使用 np.logspace(np.log10(z.min()),np.log10(z.max()), 50) 轻松设置值。在这种情况下,Matplotlib 3.3.3 在正确格式化颜色条刻度方面似乎有一些困难,因此您需要手动调整一下。

import matplotlib.pyplot as plt
from matplotlib import ticker, cm
import numpy as np

x = np.linspace(-3.0, 3.0, 100)
y = np.linspace(-2.0, 2.0, 100)
X, Y = np.meshgrid(x, y)

Z1 = np.exp(-(X)**2 - (Y)**2)
Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2)
z = Z1 + 50 * Z2

fig, ax = plt.subplots()

n_levels = 50
cs = ax.contourf(X, Y, z, 
                 np.logspace(np.log10(z.min()),np.log10(z.max()), n_levels), 
                 locator=ticker.LogLocator(), 
                 cmap=cm.jet
                 )

cbar = fig.colorbar(cs)
cbar.locator = ticker.LogLocator(10)
cbar.set_ticks(cbar.locator.tick_values(z.min(), z.max()))
cbar.minorticks_off()