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

1

10

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

Freiburg answered 2/9, 2013 at 11:31 Comment(4)
Actually it behaves as expected.set_aspect('equal') means that one unit on the x-axis is of same length as one unit on the y-axis, as seen in your Figure 1.Scarface
You can pass a numeric value to set_aspect, see the documentation. Taking the quotient of x and y you should be able to scale the axes so that they have the same length.Unimposing
Note that your first example (Figure 1) is not actually square; it's about 430 pixels wide by 400 pixels high. This is consistent with the slightly different data ranges for the two axes (0 to 3.5 for the x-axis, 0 to 3.25 for the y-axis), because set_aspect('equal') is forcing the same data scaling (data values per pixel) for both axes.Lightner
Possible duplicate of Aspect ratio in subplots with various y-axesAmabel
S
20

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())
Salsala answered 2/9, 2013 at 15:10 Comment(1)
Note that this command must appear after the plot command.Diligent

© 2022 - 2024 — McMap. All rights reserved.