python - 如何删除颜色条

标签 python matplotlib axes colorbar divider

我想从轴上删除颜色条,以便轴返回到其默认位置。

为了清楚起见,请看一下这段代码(或者更好地运行它):

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

# Init figure
figure, axes = plt.subplots()
axes.set_aspect(1)

# Create some random stuff
image = axes.imshow(np.random.random((10, 10)))
plt.pause(2)

# Add a color bar to the axes
cax = make_axes_locatable(axes).append_axes("right", size="5%", pad=0.05)
colorBar = figure.colorbar(image, cax=cax)
colorBar.ax.tick_params(length=0, labelright=False)
plt.pause(2)

# Remove the color bar
colorBar.remove()

plt.show()

如您所见,会发生以下情况:在那一刻,我将颜色条添加到轴上,轴本身正在稍微改变其位置。它向左移动以为颜色条创造一些空间。在更复杂的情况下,例如在 Gridspec 中,它也可能会稍微改变其大小。

我想要得到的:在那一刻,我再次删除颜色条,我想让轴回到原来的位置(及其原始大小)。

当我删除颜色条时,这不会自动发生。轴仍位于左侧位置,而不是回到中心。 我如何实现这一目标?

我需要类似 make_axes_locateable 的倒数.

最佳答案

make_axes_locatable 将轴定位器设置为新定位器。要反转此步骤,您需要跟踪旧定位器 (original_loc = ax.get_axes_locator()) 并将其重置到轴 (ax.set_axes_locator(original_loc))删除颜色条后。

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

# Init figure
fig, ax = plt.subplots()
ax.set_aspect(1)

# Create some random stuff
image = ax.imshow(np.random.random((10, 10)))
plt.pause(2)

# Add a color bar to the axes
original_loc = ax.get_axes_locator()
cax = make_axes_locatable(ax).append_axes("right", size="5%", pad=0.05)
colorBar = fig.colorbar(image, cax=cax)
colorBar.ax.tick_params(length=0, labelright=False)
plt.pause(2)

# Remove the color bar
colorBar.remove()
ax.set_axes_locator(original_loc)
plt.pause(0.0001)

plt.show()

关于python - 如何删除颜色条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57402528/

相关文章:

python - 将数据帧输出与一个索引合并

python - 如何在 Python 中编写 ffmpeg 命令 "-ss"

python - 对seaborn histplot 中的重叠条有一些指示

python - Matplotlib:生成多个具有不同和倒比例尺的双轴

python - 具体模型阅读 xlsx 文档 Pyomo

python - Python如何区分作为类成员的回调函数?

python - pyqt5 应用程序中的 matplotlib 工具栏

python - Pyplot 如何从多个列表的平均值创建直方图?

excel - 交换 x 和 y 轴,无需手动交换值

d3.js - d3 不均匀分布缩放