user3419537 user3419537 - 1 year ago 278
Python Question

Matplotlib secondary axis with equal aspect ratio

I'm trying to create a secondary axis to an axis with equal aspect ratio using

, however, as can be seen in the example below, the secondary axis does not match the aspect ratio of the original.

Is there something additional that needs to be done, or is this a bug in matplotlib?


from matplotlib import pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111, adjustable='box-forced', aspect='equal')
ax2 = ax1.twinx()

Output figure:

matplotlib output

Answer Source

Creating the host axis with host_subplot like in the matplotlib example on parasitic axes instead of fig.add_subplot appears to resolve the issue. The plots now occupy the same space and have equal aspect ratios.

from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot

fig = plt.figure()
ax1 = host_subplot(111, adjustable='box-forced', aspect='equal')
ax2 = ax1.twinx()

I was able to achieve the same as above with the object-oriented API used in my actual program by creating the host axis with SubplotHost

from PyQt5 import QtWidgets
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from mpl_toolkits.axes_grid1.parasite_axes import SubplotHost

app = QtWidgets.QApplication([])

fig = Figure()
ax1 = SubplotHost(fig, 111, adjustable='box-forced', aspect='equal')
ax2 = ax1.twinx()
canvas = FigureCanvas(fig)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download