我的理解是,您想用两张幻灯片进行演示,一张带有不带彩条的情节,下一张幻灯片带有带有彩条的相同情节。两张幻灯片中的绘图应具有相同的大小,以便在更改幻灯片时绘图不会跳转或调整大小。
设置颜色图将调整原始Axes
实例的大小。您可以使用ax.get_position()
来获取调整大小的边界框Axes
。它返回一个边界框:Bbox(array([[ 0.125, 0.1 ], [ 0.745, 0.9 ]]))
它给出左、下、右和上边缘。我发现它更容易作弊并使用ax._position.bounds
,它提供了一个矩形(左边缘、下边缘、宽度、高度),您可以直接使用它来制作新轴,如下所示。
import matplotlib
import matplotlib.pyplot as plt
min_val = 0
max_val = 1
my_cmap = matplotlib.cm.get_cmap('jet')
norm = matplotlib.colors.Normalize(min_val, max_val)
cmmapable = matplotlib.cm.ScalarMappable(norm, my_cmap)
cmmapable.set_array(range(min_val, max_val))
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
cbar = plt.colorbar(cmmapable, ax = ax1, ticks=[0, 1])
cbar.ax.set_yticklabels(['Min', 'Max'])
# gives bounding box with left, right, bottom, top
print(ax1.get_position())
# gives rectangle with left, bottom, width, height
print(ax1._position.bounds)
fig2 = plt.figure()
ax2 = fig2.add_axes(ax1._position.bounds)
plt.show()
更新:在上面的解决方案中没有颜色条,在下面的解决方案中有一个颜色条,但是您将其设为白色并删除标签和刺。如果图形的背景颜色不是白色,您将看到一个白色矩形,颜色条应该是。
import matplotlib
import matplotlib.pyplot as plt
min_val = 0
max_val = 1
my_cmap = matplotlib.cm.get_cmap('jet')
norm = matplotlib.colors.Normalize(min_val, max_val)
cmmapable = matplotlib.cm.ScalarMappable(norm, my_cmap)
cmmapable.set_array(range(min_val, max_val))
fig1 = plt.figure()
ax1 = fig1.add_subplot(111)
# set opacity to 0
cbar = plt.colorbar(cmmapable, ax = ax1, ticks=[0, 1], alpha = 0)
# remove the tick labels
cbar.ax.set_yticklabels(['', ''])
# set the tick length to 0
cbar.ax.tick_params(axis = 'y', which = "both", length = 0)
# set everything that has a linewidth to 0
for a in cbar.ax.get_children():
try:
a.set_linewidth(0)
except:
pass
plt.show()