Formatting Axes in Python-Matplotlib - GeeksforGeeks

22 Jun, 2020
Matplotlib is a python library for creating static, animated and interactive data visualizations.
Note: For more information, refer to Introduction to Matplotlib
This is what you think of as ‘plot’. It is the region of the image that contains the data space. The Axes contains two or three-axis(in case of 3D) objects which take care of the data limits. Below is an image illustrating the different parts of a figure which contains the graph.
The different aspects of the Axes can be changed according to the requirements.
1. Labelling x, y-Axis
Syntax:
for x-axisAxes.set_xlabel(self, xlabel, fontdict=None, labelpad=None, \*\*kwargs)
for y-axisAxes.set_ylabel(self, ylabel, fontdict=None, labelpad=None, \*\*kwargs)
These functions are used to name the x-axis and y-axis.
Example:
# importing matplotlib moduleimport matplotlib.pyplot as pltimport numpy as np  # x-axis & y-axis valuesx = [3, 2, 7, 4, 9]y = [10, 4, 7, 1, 2]  # create a figure and axesfig, ax = plt.subplots()  # setting title to graphax.set_title('Example Graph')  # label x-axis and y-axisax.set_ylabel('y-AXIS')ax.set_xlabel('x-AXIS')  # function to plot and show graphax.plot(x, y)plt.show()
Output:
2. Limits of x, y-Axis
Syntax:
For x-axis:
Axes.set_xlim(self, left=None, right=None, emit=True, auto=False, \*, xmin=None, xmax=None)
Parameters:
left and right – float, optionalThe left xlim(starting point) and right xlim(ending point) in data coordinates. Passing None leaves the limit unchanged.
auto – bool or None, optionalTo turn on autoscaling of the x-axis. True turns on, False turns off (default action), None leaves unchanged.
xmin, xmax : They are equivalent to left and right respectively, and it is an error to pass both xmin and left or xmax and right.Returns:right, left – (float, float)
Returns:right, left – (float, float)
For y-axis:
Axes.set_ylim(self, bottom=None, top=None, emit=True, auto=False, \*, ymin=None, ymax=None)
Parameters:
bottom and top – float, optionalThe bottom ylim(starting point) and top ylim(ending point) in data coordinates. Passing None leaves the limit unchanged.
auto – bool or None, optionalTo turn on autoscaling of the y-axis. True turns on, False turns off (default action), None leaves unchanged.
ymin, ymax : They are equivalent to left and right respectively, and it is an error to pass both ymin and left or ymax and right.Returns:bottom, top – (float, float)
Returns:bottom, top – (float, float)
Example:
import matplotlib.pyplot as pltimport numpy as np  x = [3, 2, 7, 4, 9]y = [10, 4, 7, 1, 2]  # create a figure and axesfig, 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 graphax.plot(x, y)plt.show()
Output:
3. Major and Minor Ticks
The Ticks are the values/magnitude of the x and y axis. Minor ticks are divisions of major ticks. There are two classes Locator and Formatter. Locators determine where the ticks are and Formatter controls the formatting of the ticks. These two classes must be imported from matplotlib.
MultipleLocator() places ticks on multiples of some base.
MultipleLocator() places ticks on multiples of some base.
FormatStrFormatter uses a format string (e.g., ‘%d’ or ‘%1.2f’ or ‘%1.1f cm’ ) to format the tick labels.
Note: Minor ticks are OFF by default and they can be turned ON by without labels by setting the minor locator and minor tick labels can be turned ON by minor formatter.
Example:
# importing matplotlib module and respective classesimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.ticker import (MultipleLocator,                               FormatStrFormatter,                               AutoMinorLocator)  x = [3, 2, 7, 4, 9]y = [10, 4, 7, 1, 2]  fig, ax = plt.subplots()  ax.set_title('Example Graph')  ax.set_ylabel('y-AXIS')ax.set_xlabel('x-AXIS')  ax.set_xlim(0, 10)ax.set_ylim(0, 10)  # Make x-axis with major ticks that # are multiples of 11 and Label major # ticks with '% 1.2f' formattingax.xaxis.set_major_locator(MultipleLocator(10))ax.xaxis.set_major_formatter(FormatStrFormatter('% 1.2f'))  # make x-axis with minor ticks that # are multiples of 1 and label minor # ticks with '% 1.2f' formattingax.xaxis.set_minor_locator(MultipleLocator(1))ax.xaxis.set_minor_formatter(FormatStrFormatter('% 1.2f'))  ax.plot(x, y)plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python