Skip to main content
 首页 » 编程设计

python之Matplotlib Colorbar 显示数字

2024年10月24日10zengkefu

如何在 matplotlib 中准确指定颜色条标签?我经常需要创建非常具体的色标,但颜色条标签显示效果很差,您无法分辨色标是什么。我想手动定义颜色条刻度线旁边的文本,或者至少让它们以科学记数法显示。

这是一个示例图,您无法分辨底部的四个色 block 代表什么:

这是一个如何创建该图的工作示例:

import numpy as np 
import matplotlib.pyplot as plt 
from matplotlib import colors 
 
# mock up some data 
x = np.random.random(50) 
y = np.random.random(50) 
c = np.arange(0, 1, 1.0/50.0)  # color of points 
c[0] = 0.00001 
c[1] = 0.0001 
c[2] = 0.001 
c[3] = 0.01 
s = 500 * np.random.random(50) + 25  # size of points 
 
# set up some custom color scaling 
lcmap = colors.ListedColormap(['#FFFFFF', '#FF99FF', '#8000FF', 
                               '#0000FF', '#0080FF', '#58FAF4', 
                               '#00FF00', '#FFFF00', '#FF8000', 
                               '#FF0000']) 
bounds = [0.0, 0.000001, 0.00001, 0.0001, 
          0.001, 0.01, 0.1, 0.25, 0.5, 0.75, 1.0] 
norm = colors.BoundaryNorm(bounds, lcmap.N) 
 
# create some plot 
fig, ax = plt.subplots() 
im = ax.scatter(x, y, c=c, s=s, cmap=lcmap, norm=norm) 
 
# add the colorbar 
fig.colorbar(im, ax=ax) 
 
fig.savefig('temp.jpg') 

请您参考如下方法:

cbar = fig.colorbar(cax, ticks=[-1, 0, 1]) 
cbar.ax.set_xticklabels(['Low', 'Medium', 'High']) 

并使用任何你想要的迭代器而不是 ['Low', 'Medium', 'High']

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