Issue
I want to remove a color bar from an axes in that way that the axes will return to its default position.
To make it clear, have a look at this code (or better run it):
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()
As you see, the following happens: In that moment I add the color bar to the axes, the axes itself is changing its position a litte bit. It is moving to the left to create some space for the color bar. In a more complex case, e.g. in a Gridspec, it might also change its size a bit.
What I want to get: In that moment I am removing the colorbar again, I want to get the axes back in its original position (and its original size).
This does not happen automatically when I remove the color bar. The axes is still on its left position and not back in the center. How do I achieve that?
I need something like the inverse of make_axes_locateable
.
Solution
make_axes_locatable
sets the axes locator to a new locator. To reverse this step you need to keep track of the old locator (original_loc = ax.get_axes_locator()
) and reset it to the axes (ax.set_axes_locator(original_loc)
) after you removed the colorbar.
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()
Answered By - ImportanceOfBeingErnest
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.