matplotlib contourf不反映带边界的ListedColormap

koaltpgm  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(136)

是否可以将自定义颜色条与边界应用于图形?例如contourf
因为我可以改变colorbar的边界,但contourf并不反映这些边界。

colors = ["#ffffff", "#FFD8CA", "#FFAB98", "#FF7765", "#FF3E33", "#FF0000"]
cmap = matplotlib.colors.ListedColormap(colors)

m = plt.cm.ScalarMappable(cmap=cmap)
m.set_array(zi)
m.set_clim(min(z), max(z))
plt.colorbar(m, boundaries=[min(z), 0.35, 0.7, 1.05, 1.4, min(z)])
plt.contourf(xi, yi, zi, 6, cmap=cmap,alpha=0.7, vmin=min(z), vmax=max(z))
uinbv5nw

uinbv5nw1#

如果有6个边界值,则需要5种颜色。
边界是轮廓的levels。通过levels参数指定。然后颜色条将自动正确。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors

x,y = np.meshgrid(np.linspace(-3,3), np.linspace(-3,3))
z = np.exp(-x**2-y**2)*1.5+0.2

colors = ["white", "mistyrose", "lightcoral", "firebrick", "black"]
cmap= matplotlib.colors.ListedColormap(colors)
boundaries=[z.min(), 0.35, 0.7, 1.05, 1.4, z.max()]

m = plt.contourf(x, y, z, levels = boundaries, cmap=cmap)

plt.colorbar(m, spacing="proportional")
plt.show()

相关问题