Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a twin axis has been generated for a matplotlib axis

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()
like image 664
Brett Morris Avatar asked Mar 24 '16 20:03

Brett Morris


2 Answers

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
like image 87
jakevdp Avatar answered Sep 17 '22 20:09

jakevdp


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])
like image 35
ImportanceOfBeingErnest Avatar answered Sep 18 '22 20:09

ImportanceOfBeingErnest