如何“剪切”颜色条中不需要的部分

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

假设您使用

imshow
创建图像,如下所示:

plt.set_cmap('viridis')
im=plt.imshow(mydata, interpolation='nearest',origin='lower')
plt.title('mymap')
cbar=plt.colorbar()
a=round(mydata.max(),0)
cbar.set_ticks([17,23,a])
cbar.set_ticklabels([17,23,a])

假设您有一个类似连续的数据集,其中大多数值为 0,但随后会出现跳转到最高值范围的情况。

如何“剪切”颜色条以确保它从

mydata.min()=17
开始,到
mydata.max()=27
结束,而不更改图像中的颜色?


我不想要这个:

python matplotlib colorbar
2个回答
4
投票

没有限制颜色条中颜色范围的标准解决方案,因为显示的颜色通常直接链接到图像中的颜色。

因此,解决方案是创建一个独立于图像的颜色条,并填充不同的颜色图。通过剪掉所需的相应部分,可以从原始颜色图中获取此附加颜色图。

import matplotlib.pyplot as plt import matplotlib import matplotlib.colors import numpy as np # some data between 0 and 27 image = np.random.rand(30,60)*27 image[:,30:] = np.sort(image[:,30:].flatten()).reshape(30,30) plt.figure(figsize=(8,3)) cmap = plt.get_cmap('jet') im=plt.imshow(image, interpolation='nearest',origin='lower', cmap = cmap) plt.title('mymap') a=round(image.max(),0) vmin=17 #minimum value to show on colobar vmax = a #maximum value to show on colobar norm = matplotlib.colors.Normalize(vmin=vmin, vmax =vmax) #generate colors from original colormap in the range equivalent to [vmin, vamx] colors = cmap(np.linspace(1.-(vmax-vmin)/float(vmax), 1, cmap.N)) # Create a new colormap from those colors color_map = matplotlib.colors.LinearSegmentedColormap.from_list('cut_jet', colors) # create some axes to put the colorbar to cax, _ = matplotlib.colorbar.make_axes(plt.gca()) cbar = matplotlib.colorbar.ColorbarBase(cax, cmap=color_map, norm=norm,) cbar.set_ticks([17,23,a]) cbar.set_ticklabels([17,23,a]) plt.show()


1
投票
尝试:

fig, ax = plt.subplots() cax = ax.imshow(mydata,interpolation='nearest',origin='lower') cbar = fig.colorbar(cax, ticks=[17,23,a]) cbar.ax.set_yticklabels(["add your label names"]) plt.show()

另请参阅:

http://matplotlib.org/examples/pylab_examples/colorbar_tick_labelling_demo.html

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