当与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 )
# 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()
来自"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_)
如果扩展限制,来自"set colorbar range with contourf“的解决方案将是可以的,但如果减少限制,则不是这样。
我使用的是matplotlib 3.0.2
发布于 2020-06-30 22:28:05
下面的代码始终生成一个条形图,其颜色与图形中的颜色相对应,但不显示[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]
以外的值:
请求的解决方案:
https://stackoverflow.com/questions/54979958
复制相似问题