I have a function which visualizes matrix elements using bar3d
. I was trying to remove margins at the bounding limits of z-axis. I found this answer(first one) which uses monkey patching. So my code looks like this:
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.axis3d import Axis
# function which applies monkey patching
def _remove_margins():
"""
Removes margins about z=0 and improves the style
"""
if not hasattr(Axis, "_get_coord_info_old"):
def _get_coord_info_new(self, renderer):
mins, maxs, centers, deltas, tc, highs = \
self._get_coord_info_old(renderer)
mins += deltas/4
maxs -= deltas/4
return mins, maxs, centers, deltas, tc, highs
Axis._get_coord_info_old = Axis._get_coord_info
Axis._get_coord_info = _get_coord_info_new
# function which visualizes the matrix
# ✅ this function should be affected by monkey patching
def visualize_matrix(M, figsize, ... ):
_remove_margins()
fig = plt.figure(figsize=figsize)
ax = Axes3D(fig)
ax.bar3d(...)
.
.
.
return fig, ax
# another function that uses Axes3D
# ⛔️ this function should not be affected by monkey patching
def visualize_sphere(...):
fig = plt.figure(figsize=figsize)
ax = Axes3D(fig)
.
.
.
return fig, ax
Problem:
In future calls of Axes3D
(e.g. using visualize_sphere
function) the changes made by monkey patching still remains.
Question:
How to monkey patch safely to solve the problem?