python - 在 matplotlib 中使用 "contourf"设置颜色条范围

标签 python matplotlib colorbar

与 contourf 一起使用时如何减少颜色条限制?图表本身的颜色界限用“vmin”和“vmax”很好地设置,但颜色条界限没有被修改。

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(20)
y = np.arange(20)
data = x[:,None]+y[None,:]

X,Y = np.meshgrid(x,y)
vmin = 0
vmax = 15

#My attempt
fig,ax = plt.subplots()
contourf_ = ax.contourf(X,Y,data, 400, vmin=vmin, vmax=vmax)
cbar = fig.colorbar(contourf_)
cbar.set_clim( vmin, vmax )

enter image description here
# With solution from https://stackoverflow.com/questions/53641644/set-colorbar-range-with-contourf
levels = np.linspace(vmin, vmax, 400+1)
fig,ax = plt.subplots()
contourf_ = ax.contourf(X,Y,data, levels=levels, vmin=vmin, vmax=vmax)
cbar = fig.colorbar(contourf_)
plt.show()

enter image description here

Set Colorbar Range in matplotlib ”的解决方案适用于 pcolormesh,但不适用于轮廓。我想要的结果如下所示,但使用的是轮廓。
fig,ax = plt.subplots()
contourf_ = ax.pcolormesh(X,Y,data[1:,1:], vmin=vmin, vmax=vmax)
cbar = fig.colorbar(contourf_)

enter image description here

set colorbar range with contourf ”的解决方案如果限制被延长就可以了,但如果限制被减少则不行。

我正在使用 matplotlib 3.0.2

最佳答案

以下始终生成一个颜色与图中颜色相对应的条,但不显示 [vmin,vmax] 之外的值的颜色。范围。
可以对其进行编辑(请参阅内嵌注释)以准确提供您想要的结果,但是条形的颜色仍然与图形中的颜色相对应,这仅是由于使用的特定颜色图(我认为):

# Start copied from your attempt
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(20)
y = np.arange(20)
data = x[:, None] + y[None, :]

X, Y = np.meshgrid(x, y)
vmin = 0
vmax = 15


fig, ax = plt.subplots()

# Start of solution
from matplotlib.cm import ScalarMappable
levels = 400

level_boundaries = np.linspace(vmin, vmax, levels + 1)

quadcontourset = ax.contourf(
    X, Y, data,
    level_boundaries,  # change this to `levels` to get the result that you want
    vmin=vmin, vmax=vmax
)


fig.colorbar(
    ScalarMappable(norm=quadcontourset.norm, cmap=quadcontourset.cmap),
    ticks=range(vmin, vmax+5, 5),
    boundaries=level_boundaries,
    values=(level_boundaries[:-1] + level_boundaries[1:]) / 2,
)
始终正确的解决方案无法处理 [vmin,vmax] 之外的值:
always correct solution that can't handle values outside [vmin,vmax]
要求的解决方案:
requested solution

关于python - 在 matplotlib 中使用 "contourf"设置颜色条范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54979958/

相关文章:

python - 对字典键的子集进行排序

python:模块 'Crypto.Cipher.AES' 没有属性 'MODE_CCM',即使安装了 pycrypto

python - jupyter 笔记本上找不到 PhantomJS

python - python 列表中不太常见的单词

python - 如何更改 matplotlib 图例框中的名称?

python - 如何使用美元符号和小数格式化 bar_label

python - 如何使线图出现在同一个图形上而不是不同的图形上?

python - 具有均匀间隔颜色的颜色条的不均匀(不规则)间隔数据

python - 我怎样才能让 matplotlib 制作一个颜色以 0 为中心的颜色条?

python - 轮廓f中cmap的含义