matplotlib axes.set_aspect('equal') doesn't behave like expected

fidelitas picture fidelitas · Sep 2, 2013 · Viewed 11.8k times · Source

I need a figure in matplotlib where both axes are always the same length. For this I am using the option 'equal'. In most cases it works quite well and I get the expected results (see figure 1), but when the values of the y-axis are much higher than x, the figure shows an unexpected behaviour (see figure 2). Does anyone know this behavior of matplotlib?

Danke, Jörg

        host = SubplotHost(fig, 111)
        try:
            min_x_val = min(x for x in self.x_values if x is not None)
            max_x_val = max(self.x_values)
        except ValueError:
            return

        max_y_val = list()
        for n, evaluator in enumerate(self.cleaned_evaluators):
            max_y_val.append(max(self.y_values[n]))

        # axis settings
        host.axis['left'].label.set_fontsize('small')
        host.axis['left'].major_ticklabels.set_fontsize('small')
        host.axis['bottom'].label.set_fontsize('small')
        host.axis['bottom'].major_ticklabels.set_fontsize('small')
        host.axis['bottom'].major_ticklabels.set_rotation(0)
        host.set_ylabel(y_label)
        host.set_xlabel(x_label)


        host.set_xlim(0, max_x_val)
        host.set_ylim(0, max_y_val)

        host.minorticks_on()
        host.toggle_axisline(False)
        host.axes.set_aspect('equal')
        host.grid(True, alpha=0.4)

        return fig

Figure 1:

When it works

Figure 2:

When it doesn't work

Answer

btel picture btel · Sep 2, 2013

equal means that the x and y dimensions are the same length in data coordinates. To obtain square axis you can set manually the aspect ratio:

ax.set_aspect(1./ax.get_data_ratio())