matplotlib pyplot hist2D自定义色标时标记范围外bin的实现方法问询
实现方法
你当前已经使用了clim限制色阶范围、extend='min'标记下限溢出,仅需要额外给colormap设置under属性,就能给权重低于最小值的bin指定专属颜色,是改动最小的方案:
import matplotlib.pyplot as plotter import matplotlib.cm as cm 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 # 自定义colormap,指定低于clim下限的bin专属颜色 custom_cmap = cm.get_cmap('viridis').copy() custom_cmap.set_under('lightgray') # 可替换为任意你想要的颜色,比如'red'、'#ff0000' bins = [[0, 1, 2, 3], [0, 1, 2, 3]] # 绘图时传入自定义的colormap histo = plotter.hist2d(x, y, bins=bins, weights=w, cmap=custom_cmap) plotter.colorbar(histo[3], extend='min') plotter.clim(minimum, max(w)) plotter.show()
如果你想要用特殊标识而非不同颜色标记低权重bin,可以额外增加以下代码,在对应bin的位置绘制标记:
# 在plotter.show()之前插入以下内容 hist_vals = histo[0] x_edges, y_edges = histo[1], histo[2] # 筛选权重低于最小值的bin坐标 low_weight_pos = hist_vals < minimum # 计算bin的中心坐标 x_centers = (x_edges[:-1] + x_edges[1:]) / 2 y_centers = (y_edges[:-1] + y_edges[1:]) / 2 low_x = x_centers[low_weight_pos.nonzero()[1]] low_y = y_centers[low_weight_pos.nonzero()[0]] # 在对应位置绘制叉号标记 axis_field.scatter(low_x, low_y, marker='x', c='red', s=60)
内容的提问来源于stack exchange,提问作者user16972668
相关产品推荐
相关产品推荐

