Matplotlib set y axis range


matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK+.

Basic Plotting with matplotlib

matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK+.

There are many ways to use matplotlib, from interactively exploring data from the Python shell to running standalone scripts or embedded within a large application. In this section we will focus on using matplotlib in a script.

The most basic plot you can do with matplotlib is one line. For example, to plot x versus y:

import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
This will give you the following plot:
Image result for matplotlib set y axis range

Plotting with DataFrames

If you have a DataFrame, you can easily plot its contents using the plot function. This function is very versatile and can take several different arguments to customize your plot. Here, we’ll use a simple DataFrame with some generated data to illustrate how this works.

First, let’s import pandas and matplotlib:

import pandas as pd
import matplotlib.pyplot as plt
Now, let’s create a DataFrame with some fake data:

df = pd.DataFrame({“x”: range(10), “y”: range(10)})
And now we can plot it using the plot function:

This will create a basic line plot with the data in our DataFrame. By default, the x-axis will be index values (in this case, 0-9), and the y-axis will be the column values (in this case, also 0-9). If we want to change what is being plotted on each axis, we can use the x and y arguments. For example, if we wanted to plot the “y” column on the x-axis and the “x” column on the y-axis, we would do:

df.plot(x=”y”, y=”x”)
This would give us a vertical line plot with 0 on the x-axis and 9 on the y-axis (because that’s where those values are in our DataFrame). We could also switch things around and do:

df.plot(y=”y”, x=”x”)
which would give us exactly the same plot. The point is that you can control which columns are plotted on each axis by using these arguments.

Customizing plots

In this section, we will discuss how to change the range of the y-axis in the matplotlib library. We will also discuss how to change the font size and style of the plot.

Setting the title

You can use the title() method in both the plot() and figure() functions to set the plot title and the overall figure title, respectively. The respective simple syntaxes are as follows −

plot() − plt.title(‘string’)
figure() − plt.figure(title=“string”)

Setting the axis labels

In this exercise, you’ll set the x and y axis labels using plt.xlabel() and plt.ylabel(), respectively.

You’ll also be using the fontdict parameter, which allows you to specify font parameters for the text.

The specified fontdict takes precedence over font properties that are passed in via ax.tick_params(). By default, tick_params configures the appearance of ticks and tick labels; however, it also accepts some keyword arguments that configure the label fonts too. These are axes.labelsize (the size of tick labels), axes.fontname (the font family to use for tick labels), and axes.fontweight (the weight of the ticks). Therefore, if you want to configure both ticks and labels at once, it’s simpler to use fontdict than to call ax.tick_params() multiple times as shown in this exercise`.

In [1]: import matplotlib.pyplot as plt
%matplotlib inline

   fig = plt.figure() # Create figure axis = fig.add_subplot(1, 1, 1) `# Create axis

   # Plot in blue the % of degrees awarded to women in Computer Science`cs_women = df['Computer Science'] / df['Total'] `axis.plot(df['Year'], cs_women*100, 'blue') `# Set position of x-tick labels ('bottom', 'top', 'both', 'default', or 'none')`axis.tick_params(bottom="off", top="off", left="off", right="off")`# Set position of x axis label ('bottom', 'top', 'left', or 'right')`axis`.xlabel('Percentage of Degrees Awarded to Women in Computer Science\n(US)'), # Set position of y axis label ('left', 'right'); set its color`cs_men = 1 - cs_women `axis`.ylabel('Percentage of Degrees Awarded\nto Men in Computer Science\n(US)').yaxis</p><br /><h3>Setting the ticks</h3><br /><p>

Ticks are the markers denoting data points on axes. We can explicitly determine where we want to set ticks. In this article, we will see how to control every aspect of our axes, from where to position the ticks, to formatting the tick labels for dates and times.

Setting the tick labels

Tick labels are the labels displayed on the axis ticks. By default, Matplotlib tries to make reasonable choices for the tick positions and tick labels, but sometimes you will want to control this yourself. This section will give you some tips on how to do this.

One common task is to plot multiple lines on one graph. For example, you might want to compare the results of two different experiments, or plot data with different units on the same axes. In these cases, it is often useful to be able to automatically generate plot legends that give information about each line. This can be done by calling legend with a list of strings, one for each line:

Setting the x and y limits

In this example, we’ll plot the x and y data from our previous example on a different scale. By default, matplotlib will make reasonable assumptions about the x and y limits for your plot. However, sometimes it is desirable to explicitly set these values. This can be accomplished by passing in the xlim and ylim parameters to plot, as follows:

import matplotlib.pyplot as plt
plt.plot([1, 4, 9, 16])
plt.xlim(0, 20)
plt.ylim(-10, 10)

({% include image-caption.html filename=”matplotlib-set-y-axis-range-1″ %})

This produces a plot that looks like this:

![matplotlib set y axis range 2]({{ site.url }}/images/matplotlib-set-y-axis-range-2.png){: .aligncenter width=”70%” height=”70%”}

Setting the aspect ratio

Aspect ratio is the ratio of width to height. Matplotlib allows you to set the aspect ratio of a plot using the aspect keyword. The default aspect ratio is 1. However, sometimes we may want to plot a figure with a different aspect ratio, such as 4/3 or 16/9.

To set the aspect ratio, we can use the aspect keyword when we create the figure. For example, to create a figure with an aspect ratio of 2, we can do the following:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(6,3))

ax = fig.add_subplot(1,1,1)

Set axis limits so that they span from -5 to 5


Set equal aspect ratio so that followers are 1:1 in shape


Saving plots

Plots can be saved using the plt.savefig() command. This saves the plot as a png, pdf, jpeg, or other file type depending on the specified filename extension. For example:

The default resolution is 72 dpi, but this can be changed by specifying the dpi argument. For example:

Higher resolution plots take longer to save and can take up more space on your disk.


In conclusion, when you want to set the y axis range in matplotlib, you can use either the set_ylim() or the set_yrange() function. If you want to modify both the x and y axis ranges, then you can use the set_xlim() and set_ylim() functions. Finally, if you want to make sure that your plot doesn’t extend beyond a certain range, then you can use the restrict_xrange() or restrict_yrange() function.

Leave a Reply

Your email address will not be published. Required fields are marked *