首页 > 解决方案 > 在 matplotlib 中有多个子图时,在颜色栏中添加线标记以突出显示地图中的特定值

问题描述

我想在我的颜色栏中添加值为 99.99 的特殊颜色的线标记。我的颜色条的范围是从 90 到 99.99,所以我想标记这个值以便在我的地图上看到最大值(我在图中有几个带有地图的子图)。我尝试了下一个添加 cbar.ax.plot([90, 99.99], 99.99, 'w') 的代码

#fix the colorbar to the figure
cb_ax = fig.add_axes([0.1, 0.1, 0.8, 0.02])
#define the tick labels to the colorbar
bounds=[90,95,96,97,98,99,99.99]
#add the color bar
cbar = fig.colorbar(im, cax=cb_ax,orientation='horizontal', boundaries=bounds,shrink=0.2, pad=0.09)
cbar.set_label('Percentile of precipitation, [%]', fontsize=20, fontweight='bold')

cbar.ax.plot([90, 99.99], 99.99, 'w')  

在此处输入图像描述

标签: pythonmatplotlibcolorbar

解决方案


更改颜色条不会更改图像。一种方法是更改​​创建图像的颜色图,然后生成相应的颜色条。

以下示例代码为颜色图设置了“over”颜色,并用于vmax=...强制使用该“over”颜色显示最高值。

import matplotlib.pyplot as plt
import numpy as np
from scipy.ndimage import gaussian_filter

data = gaussian_filter(np.random.rand(200, 200), sigma=20)
data -= data.min()
data = data / data.max() * 100

cmap = plt.get_cmap('Reds').copy()
cmap.set_over('yellow')
fig, ax = plt.subplots()
im = ax.imshow(data, cmap=cmap, vmax=99)
bounds = [90, 95, 96, 97, 98, 99, 99.99]
plt.colorbar(im, boundaries=bounds)
plt.show()

通过颜色图更改颜色条


推荐阅读