Python Tutorial: Customizing axes

Learn to control what you see in Matplotlib plots using xlim, ylim, and axis functions. Set horizontal and vertical bounds separately, or use axis('equal') to scale both axes identically so circles actually look round.
Chapters
We've seen how to create axes and subplots, but the plots were a bit messy. Let's see how to adjust the X and Y axis limits of our plots. Sometimes we want to create a graph and zoom in to a specific region. To do this, the axis, XLIM and YLIM commands all control the left, right, upper and lower limits of the viewable portion of the axes. These can be set all at once using the axis command, or they can be set individually using XLIM and ylim. We can use tuples or lists to specify the upper and lower limits of the axes. Let's consider an example using the US gross domestic product from 1947 to 2016. The basic plot is simple to generate and label in our four lines of code. When we issue the show command, this is the figure generated. Notice the vertical scale is chosen for us to fit all the data. Suppose we want to zoom in on a portion of the graph, say the years from 1947 to 1957. We can do this by explicitly setting the horizontal axis limits using the command xlim. The resulting figure is not all that great. We can see that the vertical scale is too tall to see what's going on. It's the same default vertical scale that fits all the data. There's a similar command, ylim, that we can use to specify the upper and lower limits of the Y axis. We'll use XLIM to zoom in on the years 1947-57 and this time follow it with the YLIM command to clip the vertical axis from 0 to 1000. We can see the growth more clearly, but it's still a little flat. We could zoom in vertically even more in principle. Now we'll set the horizontal limits and the vertical limits all at once, replacing the calls to XLIM and YLIM by a single call to axis. This gives the same plot as before. The axis command accepts other strings and parameters as well. These include off to stop the axes from being drawn equal to force identical scaling of x and y axes and more. For example, here is a view of a circle in two subplots. The top plot uses the default axis scaling. The bottom plot uses axis equal to ensure that the circle is actually drawn as a circle. This is the code that produced the preceding figure. Again, it's the use of access equal that sets the scaling. Take a few minutes now to practice working with these commands on your own.
More from Richie

#359 My Best Friend is AI with Valerie Tiberius, Professor of Philosophy at University of Minnesota

How AI Agents Will Work While You Sleep | Ruslan Salakhutdinov, Professor at Carnegie Mellon

#358 How AI Agents Will Work While You Sleep | Ruslan Salakhutdinov, Professor at Carnegie Mellon







