Issue
How can one detect if an axis has a twin axis written on top of it? For example, if given ax
below, how can I discover that ax2
exists?
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1, 2, 3])
ax2 = ax.twinx()
Solution
I don't think there's any built-in to do this, but you could probably just check whether any other axes in the figure has the same bounding box as the axes in question. Here's a quick snippet that will do this:
def has_twin(ax):
for other_ax in ax.figure.axes:
if other_ax is ax:
continue
if other_ax.bbox.bounds == ax.bbox.bounds:
return True
return False
# Usage:
fig, ax = plt.subplots()
print(has_twin(ax)) # False
ax2 = ax.twinx()
print(has_twin(ax)) # True
Answered By - jakevdp
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.