Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 57 ยท Line Plots and Basic Styling

Limits, Scales and Aspect

Control what part of your data Matplotlib shows: xlim and ylim, margins, log and symlog scales, inverted axes, equal aspect, secondary and twin axes.

By default Matplotlib looks at your data and picks axis limits that fit it with a little padding. That is usually fine, but not always: sometimes you want to zoom in, to compare several charts on the same range, to show data that spans many orders of magnitude, or to draw a circle that looks like a circle. This lesson covers the tools for all of that.

Each of these settings belongs to an Axes object, as described in Anatomy of a Figure. Where the labels and tick marks themselves are concerned, continue with Ticks, Locators and Formatters.

What you can change

Limits Zoom to a range of x or y.
Scale Linear, log, symlog or logit.
Direction Invert an axis.
Aspect Make one unit the same length on both axes.

All four are methods on the Axes.

1 / 2

Setting limits

ax.set_xlim(left, right) and ax.set_ylim(bottom, top) choose the visible range. Passing only one end keeps the other automatic: ax.set_ylim(bottom=0) is the standard way to anchor a bar or area chart at zero. Calling ax.get_xlim() returns the current pair.

Limits only change the view. The data is still there, so zooming in does not delete anything, and lines that leave the view are simply clipped by the axes edge.

Autoscaling is what Matplotlib does when you have not set limits: it adds margins, a small padding (5% by default) around the data. Change it with ax.margins(x=0) to make a line touch the left and right edges, or ax.margins(y=0.2) for more air. ax.autoscale(enable=True, axis="x", tight=True) snaps the limits to the data on one axis.

Python Zooming with limits and margins

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The second panel's curve spans the full width, and the printout shows the exact limits: the default view extends a little beyond 0 and 10, while margins(x=0) makes them exactly 0 and 10. sharey=True makes all three panels use the same vertical range so they are comparable; more on that in Multiple Subplots.

Inverting an axis

Swapping the two ends reverses the direction. ax.invert_yaxis() flips the vertical axis, ax.set_xlim(10, 0) flips the horizontal one. This is natural for depth profiles (depth grows downward), rankings (rank 1 at the top), and image coordinates (row 0 at the top).

Axis scales

ax.set_xscale(name) and ax.set_yscale(name) change how values are spread along the axis.

  • "linear" is the default.
  • "log" spaces values by orders of magnitude. Equal distances mean equal ratios. Values must be positive, and a straight line on a log y-axis means exponential growth.
  • "symlog" is linear near zero and logarithmic far away from it, so it can show both positive and negative values that span many magnitudes. The linthresh option sets the size of the linear region.
  • "logit" is for probabilities between 0 and 1. It stretches both ends.

ax.loglog(x, y), ax.semilogx and ax.semilogy are shortcuts that plot and set the scales together.

Python Linear, log and symlog scales

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

On the log axis, the exponential growth that looked like a hockey stick becomes a straight line, because doubling at each step is a constant increase in the logarithm. If you try set_yscale("log") with zeros or negative values, Matplotlib clips them to a tiny positive value by default (or can mask them) because the logarithm is undefined there. Use symlog or filter the data first.

Aspect ratio

The aspect is the ratio of one unit on the y-axis to one unit on the x-axis, measured in screen length. The default "auto" stretches the axes to fill the available box, which is why a circle drawn in data coordinates can look like an egg. ax.set_aspect("equal") forces one unit to be the same length on both axes. Use it for maps, geometry, images and any plot where distances matter. With ax.set_aspect("equal", adjustable="box") Matplotlib shrinks the box rather than changing the limits.

Python Equal aspect makes circles round

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Secondary axes and twin axes

Sometimes the same quantity should be shown in two units, for example Celsius and Fahrenheit. ax.secondary_xaxis("top", functions=(forward, inverse)) adds a second axis along the top whose scale is computed from the first with a pair of functions. Because it is only a different labelling, the data is plotted once. secondary_yaxis("right", functions=...) works the same for the vertical direction.

ax.twinx() is different: it creates a second Axes that shares the x-axis but has its own y-axis, for plotting different quantities on one chart. That is powerful but easy to misuse, because the viewer cannot tell how the two curves relate. Use it sparingly and color-code each axis, as discussed in Shared, Twin and Secondary Axes.

Python A secondary axis and a twin axis

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The right-hand axis labelled in Fahrenheit is a pure re-labelling of the same data. The rainfall bars use a separate y-scale pushed outward so the two right-hand axes do not overlap. Setting a higher zorder on the main axes keeps the line drawn above the bars.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does ax.set_ylim(bottom=0) do?

    set_ylim only changes the view. Giving just bottom keeps the top limit automatic.
  2. 2. A series doubles every step. On which y-axis scale does it appear as a straight line?

    On a log axis equal ratios are equal distances, so constant doubling gives a straight line.
  3. 3. Why does a circle sometimes look like an ellipse?

    With aspect auto, one x unit and one y unit can have different lengths. ax.set_aspect("equal") fixes that.
  4. 4. What is the main difference between secondary_yaxis and twinx?

    A secondary axis is a different unit scale for the same quantity. A twin axis plots another quantity with its own scale.

Summary

  • set_xlim/set_ylim change the visible range without altering data; margins and autoscale control the automatic padding.
  • Swap the limits or call invert_yaxis to reverse a direction.
  • log suits data spanning orders of magnitude, symlog handles zero and negatives, logit handles probabilities.
  • set_aspect("equal") keeps shapes true; leave aspect on auto for ordinary charts.
  • secondary_xaxis/secondary_yaxis show the same quantity in other units; twinx plots a different quantity and should be used with care.

Next, fine-tune the marks along each axis in Ticks, Locators and Formatters.