在matplotlib

时间:2019-03-04 09:12:36

标签: 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,但不适用于Contourf。我想要的结果如下所示,但是使用了contourf。

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

1 个答案:

答案 0 :(得分:1)

以下内容始终会产生一个条形,其颜色与图形中的颜色相对应,但对于[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