使用轮廓设置颜色条范围 [英] set colorbar range with contourf

查看:45
本文介绍了使用轮廓设置颜色条范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是该问题的重复:

如何使用轮廓f强制将颜色栏范围设置为0到2?

解决方案

contourf 确实与其他 ScalarMappable 的工作方式略有不同.如果指定级别数(在这种情况下为20),它将使它们介于最小数据和最大数据之间(大约).如果你想在两个特定值 vminvmax 之间有 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 ScalarMappables. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆