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()
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
You may check if the axes has a shared axes. This would not necessarily be a twin though. But together with querying the position this will suffice.
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2,2)
ax5 = axes[0,1].twinx()
def has_twinx(ax):
s = ax.get_shared_x_axes().get_siblings(ax)
if len(s) > 1:
for ax1 in [ax1 for ax1 in s if ax1 is not ax]:
if ax1.bbox.bounds == ax.bbox.bounds:
return True
return False
print has_twinx(axes[0,1])
print has_twinx(axes[0,0])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With