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

Will Hardy
  • 14,588
  • 5
  • 44
  • 43
fidelitas
  • 1,113
  • 2
  • 12
  • 14
  • 3
    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. – sodd Sep 02 '13 at 11:43
  • You can pass a numeric value to `set_aspect`, see the [documentation](http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_aspect). Taking the quotient of `x` and `y` you should be able to scale the axes so that they have the same length. – Bakuriu Sep 02 '13 at 11:45
  • 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. – Peter Erwin Sep 18 '16 at 14:45
  • Possible duplicate of [Aspect ratio in subplots with various y-axes](https://stackoverflow.com/questions/14907062/aspect-ratio-in-subplots-with-various-y-axes) – jdhao Jan 08 '18 at 01:52

1 Answers1

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())
btel
  • 5,563
  • 6
  • 37
  • 47