【发布时间】:2021-05-20 18:43:10
【问题描述】:
所以,我必须为需要共享颜色条范围的不同日期制作一堆 contourf 图。这很容易做到,但有时会发生给定日期的最大值高于颜色条范围,并且以我不需要的方式改变了绘图的外观。发生这种情况时,我希望它处理它的方式是在“原始颜色条”上方添加扩展三角形。附图中很清楚。
我需要代码自动运行,现在我只输入数据和颜色条范围并输出图像,所以代码中颜色条的拟合需要是自动的,我不能添加填充因为图形大小会根据要求绘制的区域而变化。
我需要这种行为的原因是因为最终我想制作一个.gif,而我不能让颜色条在那个短视频中移动。我需要在需要时将三角形添加到顶部(和下方),而不会弄乱“主要”颜色条。
谢谢!
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize, BoundaryNorm
from matplotlib import cm
###############
## Finds the appropriate option for variable "extend" in fig colorbar
def find_extend(vmin, vmax, datamin, datamax):
#extend{'neither', 'both', 'min', 'max'}
if datamin >= vmin:
if datamax <= vmax:
extend="neither"
else:
extend="max"
else:
if datamax <= vmax:
extend="min"
else:
extend="both"
return extend
###########
vmin=0
vmax=30
nlevels=8
colormap=cm.get_cmap("rainbow")
### Creating data
z_1=30*abs(np.random.rand(5, 5))
z_2=37*abs(np.random.rand(5, 5))
data={1:z_1, 2:z_2}
x=range(5)
y=range(5)
## Plot
for day in [1, 2]:
fig = plt.figure(figsize=(4,4))
## Normally figsize=get_figsize(bounds) and bounds is retrieved from gdf.total_bounds
## The function creates the figure size based on the x/y ratio of the bounds
ax = fig.add_subplot(1, 1, 1)
norm=BoundaryNorm(np.linspace(vmin, vmax, nlevels+1), ncolors=colormap.N)
z=data[day]
cs=ax.contourf(x, y, z, cmap=cmap, norm=norm, vmin=vmin, vmax=vmax)
extend=find_extend(vmin, vmax, np.nanmin(z), np.nanmax(z))
fig.colorbar(cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax, extend=extend)
plt.close(fig)
【问题讨论】:
-
调整收缩和纵横参数?但我总是会显示扩展。我不知道你为什么想让他们眨眼/眨眼。
-
稍后我将使用
set_over和set_under更改extend颜色,这就是我需要它在需要时显示的原因。我不知道shrink参数是否会做任何事情,因为我不确定扩展三角形是否是 y 轴范围、数据值或给定设置宽度的百分比。我在网上看到过长三角形和其他短三角形的图,所以我不确定shrink是否可行。
标签: python-3.x matplotlib colorbar