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 is also a procedural "pylab" interface based on a state machine (like OpenGL), designed to closely resemble that of MATLAB, though its use is discouraged. SciPy makes use of Matplotlib.
matplotlib.pyplot is a collection of command style functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure
For Example, creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc.
In
matplotlib.pyplot
various states are preserved across function calls so that it keeps track of things like the current figure and plotting area, and the plotting functions are directed to the current axes (please note that "axes" here and in most places in the documentation refers to the axes part of a figure and not the strict mathematical term for more than one axis).
What is Matplotlib Inline?
%matplotlib inline is how we use inline in a jupyter document. With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document. When using the 'inline' backend, your matplotlib graphs will be included in your notebook, next to the code.
Installing Matplotlib
1. Ubuntu/ Linux
- sudo apt update -y
- sudo apt upgrade -y
- sudo apt install python3-tk python3-pip -y
- sudo pip install matplotlib -y
2. Anaconda Prompt
- conda install -c conda-forge matplotlib
1. Feature
The figure keeps track of all the child Axes, a smattering of 'special' artists (titles, figure legends, etc), and the canvas. A figure can have any number of Axes, but to be useful should have at least one.
2. Axes
This is what you think of as 'a plot', it is the region of the image with the data space. A given figure can contain many Axes, but a given Axes object can only be in one Figure. The Axes contains two (or three in the case of 3D) Axis objects (be aware of the difference between Axes and Axis) which take care of the data limits (the data limits can also be controlled via set via the set_xlim() and set_ylim()Axes methods). Each Axes has a title (set via set_title()), an x-label (set via set_xlabel()), and a y-label set via set_ylabel()).
The Axes class and its member functions are the primary entry point to working with the OO interface.
3. Axis
These are the number-line-like objects. They take care of setting the graph limits and generating the ticks (the marks on the axis) and ticklabels (strings labeling the ticks). The location of the ticks is determined by a Locator object and the ticklabel strings are formatted by a Formatter. The combination of the correct Locator and Formatter gives very fine control over the tick locations and labels.
4. Artist
Basically everything you can see on the figure is an artist (even the Figure, Axes, and Axis objects). This includes Text objects, Line2D objects, collection objects, Patch objects ... (you get the idea). When the figure is rendered, all of the artists are drawn to the canvas. Most Artists are tied to an Axes; such an Artist cannot be shared by multiple Axes or moved from one to another.
Note:
here are several toolkits that are available that extend python matplotlib functionality. Some of them are separate downloads, others can be shipped with the matplotlib source code but have external dependencies.
- Basemap: It is a map plotting toolkit with various map projections, coastlines, and political boundaries.
- Cartopy: It is a mapping library featuring object-oriented map projection definitions, and arbitrary point, line, polygon and image transformation capabilities.
- Excel tools: Matplotlib provides utilities for exchanging data with Microsoft Excel.
- Mplot3d: It is used for 3-D plots.
- Natgrid: It is an interface to the natgrid library for irregular gridding of the spaced data.
What is Backend in Mayplotlib?
Matplotlib targets many different use cases and output formats. Some people use matplotlib interactively from the python shell and have plotting windows pop up when they type commands. Some people run Jupyter notebooks and draw inline plots for quick data analysis. Some people use matplotlib in batch scripts to generate postscript images from numerical simulations, and still, others run web application servers to dynamically serve up graphs.
To support all of these use cases, matplotlib can target different outputs, and each of these capabilities is called a backend; the "frontend" is the user-facing code, i.e., the plotting code, whereas the "backend" does all the hard work behind-the-scenes to make the figure.
There are two types of backends: user interface backends (for use in pygtk, wxpython, tkinter, qt4, or macosx; also referred to as "interactive backends") and hardcopy backends to make image files (PNG, SVG, PDF, PS; also referred to as "non-interactive backends").
Following is the list of Backend renderers
Backend | Description |
Qt5Agg | Agg rendering in a Qt5 canvas (requires PyQt5). This backend can be activated in IPython with %matplotlib qt5. |
ipympl | Agg rendering embedded in a Jupyter widget. (requires ipympl). This backend can be enabled in a Jupyter notebook with %matplotlib ipympl. |
GTK3Agg | Agg rendering to a GTK 3.x canvas (requires PyGObject, and pycairo or cairocffi). This backend can be activated in IPython with %matplotlib gtk3. |
macosx | Agg rendering into a Cocoa canvas in OSX. This backend can be activated in IPython with %matplotlib osx. |
TkAgg | Agg rendering to a Tk canvas (requires TkInter). This backend can be activated in IPython with %matplotlib tk. |
nbAgg | Embed an interactive figure in a Jupyter classic notebook. This backend can be enabled in Jupyter notebooks via %matplotlib notebook. |
WebAgg | On show() will start a tornado server with an interactive figure. |
GTK3Cairo | Cairo rendering to a GTK 3.x canvas (requires PyGObject, and pycairo or cairocffi). |
Qt4Agg | Agg rendering to a Qt4 canvas (requires PyQt4 or pyside). This backend can be activated in IPython with %matplotlib qt4. |
WXAgg | Agg rendering to a wxWidgets canvas (requires wxPython 4). This backend can be activated in IPython with %matplotlib wx. |
Plotting 2D Graphs
2D or 2-dimensional graphs are those which have only 2 axes i.e. x and y, they are planar graphs
1. Line 2D Plot
A line chart or line plot or line graph or curve chart is a type of chart that displays information as a series of data points called 'markers' connected by straight line segments. It is a basic type of chart common in many fields.
- import matplotlib.pyplot as plt
-
-
- x = [1,2,3]
-
- y = [3,1,2]
-
-
- plt.plot(x, y)
-
-
- plt.xlabel('x - axis')
-
- plt.ylabel('y - axis')
-
-
- plt.title('2D Line Plot!')
-
-
- plt.show()
Output
2. Custom 2D Plot
a custom 2D plot is a plot which can be enhanced graphically
- import matplotlib.pyplot as plt
-
-
- x = [1,2,3,4,5,6]
-
- y = [2,4,1,5,2,6]
-
-
- plt.plot(x, y, color='green', linestyle='dashed', linewidth = 3,
- marker='o', markerfacecolor='blue', markersize=12)
-
-
- plt.ylim(1,8)
- plt.xlim(1,8)
-
-
- plt.xlabel('x - axis')
-
- plt.ylabel('y - axis')
-
-
- plt.title('Custom Plots!')
-
-
- plt.show()
Output
3. Bar 2D Chart
A bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally. A vertical bar chart is sometimes called a line graph.
- import matplotlib.pyplot as plt
-
-
- left = [1, 2, 3, 4, 5]
-
-
- height = [10, 20, 30, 40, 50]
-
-
- tick_label = ['one', 'two', 'three', 'four', 'five']
-
-
- plt.bar(left, height, tick_label = tick_label,
- width = 0.8, color = ['blue', 'green', 'red','yellow','black'])
-
-
- plt.xlabel('x - axis')
-
- plt.ylabel('y - axis')
-
- plt.title('bar chart!')
-
-
- plt.show()
Output
4. Histogram 2D Plot
A histogram is an accurate representation of the distribution of numerical data. It is an estimate of the probability distribution of a continuous variable and was first introduced by Karl Pearson. It differs from a bar graph, in the sense that a bar graph relates two variables, but a histogram relates only one.
- import matplotlib.pyplot as plt
-
-
- ages = [2,5,70,40,30,45,50,45,43,40,44,
- 60,7,13,57,18,90,77,32,21,20,40]
-
-
- range = (0, 100)
- bins = 5
-
-
- plt.hist(ages, bins, range, color ='red',
- histtype = 'bar', rwidth = 0.8)
-
-
- plt.xlabel('age')
-
- plt.ylabel('No. of people')
-
- plt.title('My histogram')
-
-
- plt.show()
Output
5. Scatter 2D Plot
A scatter plot is a type of plot or mathematical diagram using Cartesian coordinates to display values for typically two variables for a set of data. If the points are coded, one additional variable can be displayed
- import matplotlib.pyplot as plt
-
-
- x = [2,4,5,7,6,8,9,11,12,12]
-
- y = [1,2,3,4,5,6,7,8,9,10]
-
-
- plt.scatter(x, y, label= "stars", color= "green",
- marker= "x", s=30)
-
-
- plt.xlabel('x - axis')
-
- plt.ylabel('y - axis')
-
- plt.title('Scatter plot!')
-
- plt.legend()
-
-
- plt.show()
Output
6. Pie-Chart 2D Plot
A pie chart is a circular statistical graphic, which is divided into slices to illustrate numerical proportions. In a pie chart, the arc length of each slice is proportional to the quantity it represents.
- import matplotlib.pyplot as plt
-
-
- activities = ['eat', 'sleep', 'work', 'play']
-
-
- slices = [3, 7, 8, 6]
-
-
- colors = ['r', 'y', 'g', 'b']
-
-
- plt.pie(slices, labels = activities, colors=colors,
- startangle=90, shadow = True, explode = (0.3, 0, 0.1, 0),
- radius = 1.2, autopct = '%1.1f%%')
-
-
- plt.legend()
-
-
- plt.show()
Output
Plotting 3D Graphs
Toolkits are collections of application-specific functions that extend Matplotlib.
mplot3d
The mplot3d toolkit adds simple 3D plotting capabilities to matplotlib by supplying an axes object that can create a 2D projection of a 3D scene. The resulting graph will have the same look and feel as regular 2D plots.
1. Line 3D Plot
A line chart or line plot or line graph or curve chart is a type of chart that displays information as a series of data points called 'markers' connected by straight line segments. It is a basic type of chart common in many fields.
-
- from mpl_toolkits.mplot3d import Axes3D
-
- import numpy as np
- import matplotlib.pyplot as plt
-
-
- plt.rcParams['legend.fontsize'] = 10
-
- fig = plt.figure()
- ax = fig.gca(projection='3d')
-
-
- theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
- z = np.linspace(-2, 2, 100)
- r = z**2 + 1
- x = r * np.sin(theta)
- y = r * np.cos(theta)
-
- ax.plot(x, y, z, label='parametric curve')
- ax.legend()
-
- plt.show()
Output
2. Scatter 3D Plot
A scatter plot is a type of plot or mathematical diagram using Cartesian coordinates to display values for typically two variables for a set of data. If the points are coded, one additional variable can be displayed
-
- from mpl_toolkits.mplot3d import Axes3D
-
- import matplotlib.pyplot as plt
- import numpy as np
-
-
- np.random.seed(19680801)
-
-
- def randrange(n, vmin, vmax):
- ''
-
-
-
- return (vmax - vmin)*np.random.rand(n) + vmin
-
- fig = plt.figure()
- ax = fig.add_subplot(111, projection='3d')
-
- n = 100
-
-
-
- for m, zlow, zhigh in [('o', -50, -25), ('^', -30, -5)]:
- xs = randrange(n, 23, 32)
- ys = randrange(n, 0, 100)
- zs = randrange(n, zlow, zhigh)
- ax.scatter(xs, ys, zs, marker=m)
-
- ax.set_xlabel('X Label')
- ax.set_ylabel('Y Label')
- ax.set_zlabel('Z Label')
-
- plt.show()
Output
3. WireFrame 3D Plot
Wireframe plot takes a grid of values and projects it onto the specified three-dimensional surface, and can make the resulting three-dimensional forms quite easy to visualize.
- from mpl_toolkits.mplot3d import axes3d
- import matplotlib.pyplot as plt
-
-
- fig = plt.figure()
- ax = fig.add_subplot(111, projection='3d')
-
-
- X, Y, Z = axes3d.get_test_data(0.05)
-
-
- ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)
-
- plt.show()
Output
4. Surface 3D Plot
Surface plots are diagrams of three-dimensional data. Rather than showing the individual data points, surface plots show a functional relationship between a designated dependent variable (Y), and two independent variables (X and Z). The plot is a companion plot to the contour plot.
-
- from mpl_toolkits.mplot3d import Axes3D
-
- import matplotlib.pyplot as plt
- from matplotlib import cm
- from matplotlib.ticker import LinearLocator, FormatStrFormatter
- import numpy as np
-
-
- fig = plt.figure()
- ax = fig.gca(projection='3d')
-
-
- X = np.arange(-5, 5, 0.5)
- Y = np.arange(-5, 5, 0.5)
- X, Y = np.meshgrid(X, Y)
- R = np.sqrt(X**2 + Y**2)
- Z = np.sin(R)
-
-
- surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
- linewidth=0, antialiased=False)
-
-
- ax.set_zlim(-1.01, 1.01)
- ax.zaxis.set_major_locator(LinearLocator(10))
- ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
-
-
- fig.colorbar(surf, shrink=0.5, aspect=5)
-
- plt.show()
Output
5. Tri-Surface 3D Plot
A triangulation of a compact surface is a finite collection of triangles that cover the surface in such a way that every point on the surface is in a triangle, and the intersection of any two triangles is either void, a common edge, or a common vertex. A triangulated is called tri-surface.
- from mpl_toolkits.mplot3d import Axes3D
- import matplotlib.pyplot as plt
- import numpy as np
-
-
- n_radii = 16
- n_angles = 16
-
-
- radii = np.linspace(0.125, 1.0, n_radii)
- angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
-
-
- angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
-
-
-
-
- x = np.append(0, (radii*np.cos(angles)).flatten())
- y = np.append(0, (radii*np.sin(angles)).flatten())
-
-
- z = np.sin(-x*y)
-
- fig = plt.figure()
- ax = fig.gca(projection='3d')
-
- ax.plot_trisurf(x, y, z, linewidth=0.2, antialiased=True)
-
- plt.show()
Output
6. Contour 3D Plot
A contour line of a function of two variables is a curve along which the function has a constant value so that the curve joins points of equal value. It is a plane section of the three-dimensional graph of the function f parallel to the plane. A contour plot is a graphical technique for representing a 3-dimensional surface by plotting constant z slices, called contours, on a 2-dimensional format. That is, given a value for z, lines are drawn for connecting the (x,y) coordinates where that z value occurs.
- from mpl_toolkits.mplot3d import axes3d
- import matplotlib.pyplot as plt
- from matplotlib import cm
-
- fig = plt.figure()
- ax = fig.gca(projection='3d')
- X, Y, Z = axes3d.get_test_data(0.005)
- cset = ax.contour(X, Y, Z, extend3d=True, cmap=cm.coolwarm)
- ax.clabel(cset, fontsize=9, inline=1)
-
- plt.show()
Output
7. Filled Contour 3D Plot
This is a type of contour plot where each 3D artist is filled
- from mpl_toolkits.mplot3d import axes3d
- import matplotlib.pyplot as plt
- from matplotlib import cm
-
- fig = plt.figure()
- ax = fig.gca(projection='3d')
- X, Y, Z = axes3d.get_test_data(0.005)
- cset = ax.contourf(X, Y, Z, cmap=cm.coolwarm)
- ax.clabel(cset, fontsize=9, inline=1)
-
- plt.show()
Output
8. Polygon 3D Plot
A Polygon plot is a type of 3D plot, where the artists can be of different shapes and sizes with no restriction on the shape or size of any artist
- from mpl_toolkits.mplot3d import Axes3D
- from matplotlib.collections import PolyCollection
- import matplotlib.pyplot as plt
- from matplotlib import colors as mcolors
- import numpy as np
-
-
- fig = plt.figure()
- ax = fig.gca(projection='3d')
-
-
- def cc(arg):
- return mcolors.to_rgba(arg, alpha=0.9)
-
- xs = np.arange(0, 10, 0.2)
- verts = []
- zs = [0.0, 1.0, 2.0, 3.0]
- for z in zs:
- ys = np.random.rand(len(xs))
- ys[0], ys[-1] = 0, 0
- verts.append(list(zip(xs, ys)))
-
- poly = PolyCollection(verts, facecolors=[cc('r'), cc('g'), cc('b'),
- cc('y')])
- poly.set_alpha(0.9)
- ax.add_collection3d(poly, zs=zs, zdir='y')
-
- ax.set_xlabel('X')
- ax.set_xlim3d(0, 10)
- ax.set_ylabel('Y')
- ax.set_ylim3d(-1, 4)
- ax.set_zlabel('Z')
- ax.set_zlim3d(0, 1)
-
- plt.show()
Output
9. Bar 3D Plot
A bar chart or bar graph is a chart or graph that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. The bars can be plotted vertically or horizontally. A vertical bar chart is sometimes called a line graph.
- from mpl_toolkits.mplot3d import Axes3D
- import matplotlib.pyplot as plt
- import numpy as np
-
- fig = plt.figure()
- ax = fig.add_subplot(111, projection='3d')
- for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):
- xs = np.arange(100)
- ys = np.random.rand(100)
-
-
-
- cs = [c] * len(xs)
- cs[0] = 'c'
- ax.bar(xs, ys, zs=z, zdir='y', color=cs, alpha=0.8)
-
- ax.set_xlabel('X')
- ax.set_ylabel('Y')
- ax.set_zlabel('Z')
-
- plt.show()
Output
10. Quiver 3D
A quiver plot displays velocity vectors as arrows with components (u,v) at the points (x,y) .
- from mpl_toolkits.mplot3d import axes3d
- import matplotlib.pyplot as plt
- import numpy as np
-
- fig = plt.figure()
- ax = fig.gca(projection='3d')
-
-
- x, y, z = np.meshgrid(np.arange(-0.8, 1, 0.4),
- np.arange(-0.8, 1, 0.3),
- np.arange(-0.8, 1, 0.3))
-
-
- u = np.sin(np.pi * x) * np.cos(np.pi * y) * np.cos(np.pi * z)
- v = -np.cos(np.pi * x) * np.sin(np.pi * y) * np.cos(np.pi * z)
- w = (np.sqrt(2.0 / 3.0) * np.cos(np.pi * x) * np.cos(np.pi * y) *
- np.sin(np.pi * z))
-
- ax.quiver(x, y, z, u, v, w, length=0.2, normalize=True)
-
- plt.show()
Output
Conclusion
In this chapter, we studied Python MatPlotLib. In the next chapter, we will learn about Python Seaborn.
Python Seaborn is a Python data visualization library based on Python MatPlotLib. It provides a high-level interface for drawing attractive and informative statistical graphics.