Formatting the Axes in Matplotlib
In this tutorial, we will cover how to format the Axes in the Matplotlib. Let us first learn what is Axes in Matplotlib.
Matplotlib Axes
The region of the image that contains the data space is mainly known as Axes.
- The Axes in the Matplotlib mainly contains two-axis( in case of 2D objects) or three-axis(in case of 3D objects)which then take care of the data limits.
Let us show you different parts of the figure that contains the graph:
You can change different aspects of the Axes according to your requirements and the further sections of this tutorial we will learn how to do that.
1. Labelling of x-axis and y-axis
In this section we will cover how to label x and y axis in Matplotlib.
Given below is the syntax for labelling of x-axis and y-axis:
For x-axis:
Axes.set_xlabel(self, xlabel, fontdict=None, labelpad=None, \*\*kwargs)
For y-axis:
Axes.set_ylabel(self, ylabel, fontdict=None, labelpad=None, \*\*kwargs)
In this way with the help of above two functions you can easily name the x-axis and y-axis.
Labelling x-axis and y-axis Example:
Now let us take a look at an example where we will make use of above two functions in order to name x-axis and y-axis.
import matplotlib.pyplot as plt
import numpy as np
a = [1, 2, 7, 4, 12]
b = [11, 3, 7, 5, 2]
# below function will create a figure and axes
fig,ax = plt.subplots()
# setting title to graph
ax.set_title('Sample')
# label x-axis and y-axis
ax.set_ylabel('Vertical / yaxis')
ax.set_xlabel('Horizontal / xaxis')
# function to plot and show graph
ax.plot(a, b)
plt.show()
And the output:
2. Set Limit of x-axis and y-axis
In this section we will cover how to set the limit for x and y axis in Matplotlib.
Given below is the syntax for labelling of x-axis and y-axis:
For x-axis:
Axes.set_xlim(self, left=None, right=None, emit=True, auto=False, \*, xmin=None, xmax=None)
Function Parameters:
-
left, right
These two parameters are in float and are optional
The left xlim that is starting point and right xlim that is ending point in data coordinates. If you will pass None
to it then it will leave the limit unchanged.
-
auto
This parameter is in bool
and it is optional too.
If you want to turn on the autoscaling of the x-axis, then the value of this parameter should be true, and false value of this parameter means turns off the autoscaling (which is the default action), and the None
value leaves it unchanged.
-
xmin, xmax
These two parameters are equivalent to left and right respectively, and it causes an error if you will pass value to both xmin and left or xmax and right.
Returned Values:
This will return right and left value that is (float, float)
For y-axis:
Axes.set_ylim(self, bottom=None, top=None, emit=True, auto=False, \*, ymin=None, ymax=None)
Function Parameters:
-
bottom and top
These two parameters are in float and are optional.
The bottom ylim(that is starting point) and top ylim that is ending point in data coordinates. If you will pass None
to it then it will leave the limit unchanged.
-
auto
This parameter is in bool
and it is optional.
If you want to turn on the autoscaling of the y-axis then the value of this parameter should be true and the false value of this parameter means turns off autoscaling and the None
value leaves it unchanged.
-
ymin, ymax
These two parameters are equivalent to bottom and top respectively, and it causes an error if you will pass value to both xmin and bottom or xmax and top.
Returned Values:
This will return bottom and left value that is (float, float)
Set Limit for x-axis and y-axis Example:
Now let us take a look at an example where we will make use of above two functions in order to set the limit of x-axis and y-axis.
import matplotlib.pyplot as plt
import numpy as np
x = [2, 4, 9, 5, 10]
y = [10, 4, 7, 1, 2]
# create a figure and axes
fig, ax = plt.subplots()
ax.set_title('Example Graph')
ax.set_ylabel('y_axis')
ax.set_xlabel('x_axis')
# set x, y-axis limits
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
# function to plot and show graph
ax.plot(x, y)
plt.show()
Here is the output:
3. Major and Minor Ticks
In Matplotlib, the Ticks are basically the values of the x and y axis. Basically Minor Ticks are divisions of major ticks (like centimeter and millimeter, where CM can be major tick and MM can be minor tick).
We have two classes Locator
and Formatter
for controlling the ticks:
You must need to import these two classes from matplotlib:
1. MultipleLocator()
This function helps to place ticks on multiples of some base.
2. FormatStrFormatter
It will use a string format like for example: '%d' or '%1.2f' or '%1.1f cm' in order to format the tick labels.
Note: It is important to note here that Minor ticks are by default OFF and they can be turned ON without labels and just by setting the minor locator while minor tick labels can be turned ON with the help of minor formatter.
Major and Minor Ticks Example:
Let's see an example,
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter,
AutoMinorLocator)
t = np.arange(0.0, 100.0, 0.1)
s = np.sin(0.1 * np.pi * t) * np.exp(-t * 0.01)
fig, ax = plt.subplots()
ax.plot(t, s)
# Make a plot with major ticks that are multiples of 10 and minor ticks that
# are multiples of 5. Label major ticks with '%d' formatting but don't label
# minor ticks.
ax.xaxis.set_major_locator(MultipleLocator(10))
ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
# For the minor ticks, use no labels; default NullFormatter.
ax.xaxis.set_minor_locator(MultipleLocator(5))
plt.show()
Here is the output:
Summary:
In this tutorial we covered the various ways of formatting Axes in a matplotlib figure, which includes adding labels for axis, setting limit for axis and adding the major/minor ticks.