matplotlib 中的离散对数颜色条

问题描述 投票:0回答:2

我想创建一个带有

离散
对数颜色条的pcolormesh图。一些分辨率会丢失,但如果颜色图是离散的,颜色和值之间的匹配似乎更容易(至少对我来说)。

下面的代码片段生成具有首选值范围的连续日志颜色图。我怎样才能使它离散? 在这里我找到了如何创建离散线性色彩图,但我无法将其扩展到对数比例。

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

colormap
2个回答
0
投票

我已经成功创建了一个间距均匀的对数颜色条。但是,我无法弄清楚如何创建具有对数间距的颜色条的离散对数颜色条。我希望这有帮助!

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

X = np.arange(0, 50)
Y = np.arange(0, 50)
Z = np.random.rand(50, 50)*10
bounds = [0, 0.1, 0.2, 0.3, 0.4, 0.5, .7, .8, .9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
num_c = len(bounds)
cmap = mpl.colormaps['viridis'].resampled(num_c)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

fig, ax  = plt.subplots()
fig.set_size_inches(4*2.5, 3*2.5)

ax.pcolormesh(X, Y, Z, norm=norm, cmap=cmap)
plt.xlabel("X", horizontalalignment='right', x=1.0)
plt.ylabel("Y", horizontalalignment='right', y=1.0)

fig.colorbar(mpl.cm.ScalarMappable(cmap=cmap, norm=norm))
plt.tight_layout()

enter image description here


0
投票

plt.colorbar() 中的参数 boundariesspacing='proportional' 就可以解决问题。使用达丽丝给出的例子:

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

© www.soinside.com 2019 - 2024. All rights reserved.