使用轮廓设置颜色条范围 [英] set colorbar range with contourf
问题描述
这似乎是该问题的重复:
如何使用轮廓f强制将颜色栏范围设置为0到2?
contourf
确实与其他 ScalarMappable
的工作方式略有不同.如果指定级别数(在这种情况下为20),它将使它们介于最小数据和最大数据之间(大约).如果你想在两个特定值 vmin
和 vmax
之间有 n
级,你需要将它们提供给轮廓函数
levels = np.linspace(vmin,vmax,n + 1)plt.contourf(fld,levels=levels,cmap='coolwarm')
完整代码:
将 numpy 导入为 np导入matplotlib.pyplot作为pltfld = np.random.rand(10,10)等级= np.linspace(0,2,21)img = plt.contourf(fld,levels = levels,cmap ='coolwarm')plt.colorbar(img)plt.show()
This would appear to be a duplicate of this question:
Set Colorbar Range in matplotlib
Essentially I want to set the colorbar range to set limits, e.g. 0 to 2. When I use vmin and vmax, the range of colors in contourf is correctly set, but colorbar only shows the clipped range, i.e. the solution in the link doesn't seem to work when using contourf. Am I missing something obvious?
import numpy as np
import matplotlib.pyplot as plt
fld=np.random.rand(10,10)
img=plt.contourf(fld,20,cmap='coolwarm',vmin=0,vmax=2)
plt.colorbar(img)
Resulting in
How can I force the colorbar range to be 0 to 2 with contourf?
contourf
indeed works a bit differently than other ScalarMappable
s. If you specify the number of levels (20 in this case) it will take them between the minimum and maximum data (approximately). If you want to have n
levels between two specific values vmin
and vmax
you would need to supply those to the contouring function
levels = np.linspace(vmin, vmax, n+1)
plt.contourf(fld,levels=levels,cmap='coolwarm')
Complete code:
import numpy as np
import matplotlib.pyplot as plt
fld=np.random.rand(10,10)
levels = np.linspace(0,2,21)
img=plt.contourf(fld,levels=levels,cmap='coolwarm')
plt.colorbar(img)
plt.show()
这篇关于使用轮廓设置颜色条范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!