Matplotlib colorbar:如何手动设置间隔? [英] Matplotlib colorbar: how to manually set the intervals?
问题描述
我正在使用以下代码段创建自定义颜色栏:
I am using the following snippet to create a custom colorbar:
import pylab as pl
import numpy as np
a = np.array([[0,10000,100000,400000,500000]])
pl.figure(figsize=(9, 1.5))
mycmap = colors.ListedColormap(['yellow','orange','red','darkred'])
img = pl.imshow(a, cmap=mycmap)
pl.gca().set_visible(False)
cax = pl.axes([0.1, 0.2, 0.8, 0.6])
cbar=pl.colorbar(orientation='horizontal', cax=cax,spacing='proportional');
cbar.set_ticks([0,10000,100000,400000,500000])
cbar.set_ticklabels(['0','10000','100000','400000','500000'])
这虽然给我指定了 spacing ='proportional'
,但仍以固定的间隔为我提供了一个彩条:
This is giving me a colorbar with regular intervals, although I have specified spacing='proportional'
:
预期的结果是:
0-10000: yellow
10001-100000: orange
100001-400000: red
400001-500000: dark red
我在做什么错了?
推荐答案
可以看到,当不使轴不可见时,颜色条正确地表示了图像中数据的颜色.
As can be seen when not turning the axes invisible, the colorbar is correctly representing the color of the data in the image.
如果这不是您想要的,则应首先确定图像中数据的表示方式.将数据归一化到色图范围通常是完成此操作的方法.在这里, BoundaryNorm
是有意义的.
If this is not what you want you should start by establishing how the data is represented in the image. Introducing a Normalization for the data to the colormap range is usually the way this is accomplished. Here a BoundaryNorm
makes sense.
import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np
a = np.array([[0,10000,100000,400000,500000]])
plt.figure(figsize=(4, 2.5))
mycmap = matplotlib.colors.ListedColormap(['yellow','orange','red','darkred'])
norm = matplotlib.colors.BoundaryNorm(a[0], len(a[0])-1)
img = plt.imshow(a, cmap=mycmap, norm=norm)
cax = plt.axes([0.1, 0.1, 0.8, 0.1])
cbar=plt.colorbar(orientation='horizontal', cax=cax,spacing='proportional');
plt.show()
这现在给出了有意义的表示,在色彩范围的边缘带有刻度.
This now gives a meaningful representation with ticks at the edges of the colorranges.
这篇关于Matplotlib colorbar:如何手动设置间隔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!