Formatting Axes in Python-Matplotlib
Last Updated :
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
What is Axes?
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-axis
Axes.set_xlabel(self, xlabel, fontdict=None, labelpad=None, \*\*kwargs)
for y-axis
Axes.set_ylabel(self, ylabel, fontdict=None, labelpad=None, \*\*kwargs)
These functions are used to name the x-axis and y-axis.
Example:
import matplotlib.pyplot as plt
import numpy as np
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.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:
For y-axis:
Axes.set_ylim(self, bottom=None, top=None, emit=True, auto=False, \*, ymin=None, ymax=None)
Parameters:
Example:
import matplotlib.pyplot as plt
import numpy as np
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 )
ax.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.
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:
import matplotlib.pyplot as plt
import numpy as np
from 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 )
ax.xaxis.set_major_locator(MultipleLocator( 10 ))
ax.xaxis.set_major_formatter(FormatStrFormatter( '% 1.2f' ))
ax.xaxis.set_minor_locator(MultipleLocator( 1 ))
ax.xaxis.set_minor_formatter(FormatStrFormatter( '% 1.2f' ))
ax.plot(x, y)
plt.show()
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...