Python/Matplotlib:colobar的间距为class='proportional'时工作不正常

2024-04-29 13:27:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个具有比例间距的颜色条,但当我使用spacing='Propirative'时,颜色条工作不正常,会产生以下错误:

anaconda3/envs/env_py01/lib/python3.6/site-packages/matplotlib/colorbar.py:1094: RuntimeWarning: invalid value encountered in double_scalars
  automin = (y[2] - y[1]) / clen
anaconda3/envs/env_py01/lib/python3.6/site-packages/matplotlib/colorbar.py:1095: RuntimeWarning: invalid value encountered in double_scalars
  automax = (y[-2] - y[-3]) / clen

当我使用spacing='uniform'时,没有错误,但是颜色栏没有成比例的间距。我还尝试使用边界,但没有得到好的结果。 这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
from matplotlib.colors import BoundaryNorm

x = np.arange(-6,6,0.25)
y = np.arange(-6,6,0.25)
x, y = np.meshgrid(x,y)
z = np.random.random(x.shape)*10.0


newcolors = np.vstack((plt.cm.YlGn(np.linspace(0, 1, 4))[1:,:], plt.cm.Blues(np.linspace(0, 1, 6))))
palette = ListedColormap(newcolors, name='test')

palette.set_over('darkred')
palette.set_under('yellow')

tickslabels=[0.5,1.0,1.5,2.0,4.0,6.0,8.0,10.0,12.0,14.0]
norm=BoundaryNorm(tickslabels, palette.N)


fig1 = plt.figure('spacing = uniform')
img=plt.contourf(x, y, z, cmap=palette, levels=tickslabels, extend='both', norm=norm)
cbar=plt.colorbar(img, ticks=tickslabels, spacing='uniform')
plt.title('spacing = uniform')


fig2 = plt.figure('spacing = proportional')
img=plt.contourf(x, y, z, cmap=palette, levels=tickslabels, extend='both', norm=norm)
cbar=plt.colorbar(img, ticks=tickslabels, spacing='proportional')
plt.title('spacing = proportional')


fig3 = plt.figure('spacing = proportional and boundaries')
img=plt.contourf(x, y, z, cmap=palette, levels=tickslabels, extend='both', norm=norm)
cbar=plt.colorbar(img, ticks=tickslabels, spacing='proportional', boundaries=[-100.0]+tickslabels+[100.0])
plt.title('spacing = proportional and boundaries')

plt.show()

spacing='uniform'spacing='proportional'spacing='proportional' and boundaries

我做错了什么


Tags: importnormimgmatplotlib颜色nppltuniform