在 pyplot hist2D 中,自定义颜色条标记箱超出颜色条范围

in pyplot hist2D with customized colorbar mark bins outside colorbar range

我正在绘制一个加权二维直方图,每个 bin 都分配了一个值。这是一个最小的例子:


import matplotlib.pyplot as plotter

plot_field, axis_field = plotter.subplots()



x = [0.5, 1.5, 2.5, 0.5, 1.5, 2.5, 0.5, 1.5, 2.5]
y = [0.5, 0.5, 0.5, 1.5, 1.5, 1.5, 2.5, 2.5, 2.5]
w = [2, 1, 0, 3, 0, 0, 1, 0, 3]


minimum = 1
bins = [[0, 1, 2, 3], [0, 1, 2, 3]]
histo = plotter.hist2d(x, y, bins=bins, weights=w)

plotter.colorbar(histo[3], extend='min')
plotter.clim(minimum, max(w))
plotter.show()

限制颜色栏的范围效果很好。但是,我希望以某种方式标记重量低于最小值的垃圾箱。颜色不同或以其他方式表示。

有没有简单的方法可以做到这一点?

非常感谢!

您可以创建自己的 colormap 例如:

import numpy as np
import matplotlib.pyplot as plotter
from matplotlib import cm
from matplotlib.colors import ListedColormap


plot_field, axis_field = plotter.subplots()

viridis = cm.get_cmap('viridis', 256)
newcolors = viridis(np.linspace(0, 1, 256))
pink = np.array([248/256, 24/256, 148/256, 1])
newcolors[0, :] = pink
newcmp = ListedColormap(newcolors)

x = [0.5, 1.5, 2.5, 0.5, 1.5, 2.5, 0.5, 1.5, 2.5]
y = [0.5, 0.5, 0.5, 1.5, 1.5, 1.5, 2.5, 2.5, 2.5]
w = [2, 1, 0, 3, 0, 0, 1, 0, 3]

minimum = 1
bins = [[0, 1, 2, 3], [0, 1, 2, 3]]
_, _, _, mesh = plotter.hist2d(
    x, y, bins=bins, weights=w, cmap=newcmp, vmin=minimum, vmax=max(w)
)

plotter.colorbar(mesh, extend='min')
plotter.show()