Python MatPlotLib
In the previous article, we studied about
Scikit-Learn, its functions and their python implementations. In this article, we will be studying each of the matplotlib functions and their python implementation.
What is 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 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 was originally written by John D. Hunter, has an active development community, and is distributed under a BSD-style license. It was first released in 2003. The official website is
www.matplotlib.org.
What is Matplotlib PyPlot?
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).
Following is a list of all the Matplotlib PyPlot functions
Function |
Description |
acorr |
Plot the autocorrelation of x. |
angle_spectrum |
Plot the angle spectrum. |
annotate |
Annotate the point xy with text text. |
arrow |
Add an arrow to the axes. |
autoscale |
Autoscale the axis view to the data (toggle). |
axes |
Add axes to the current figure and make it the current axes. |
axhline |
Add a horizontal line across the axis. |
axhspan |
Add a horizontal span (rectangle) across the axis. |
axis |
Convenience method to get or set some axis properties. |
axvline |
Add a vertical line across the axes. |
axvspan |
Add a vertical span (rectangle) across the axes. |
bar |
Make a bar plot. |
barbs |
Plot a 2D field of barbs. |
barh |
Make a horizontal bar plot. |
box |
Turn the axes box on or off on the current axes. |
boxplot |
Make a box and whisker plot. |
broken_barh |
Plot a horizontal sequence of rectangles. |
cla |
Clear the current axes. |
clabel |
Label a contour plot. |
clf |
Clear the current figure. |
clim |
Set the color limits of the current image. |
close |
Close a figure window. |
cohere |
Plot the coherence between x and y. |
colorbar |
Add a colorbar to a plot. |
contour |
Plot contours. |
contourf |
Plot contours. |
csd |
Plot the cross-spectral density. |
delaxes |
Remove the Axes ax (defaulting to the current axes) from its figure. |
draw |
Redraw the current figure. |
errorbar |
Plot y versus x as lines and/or markers with attached errorbars. |
eventplot |
Plot identical parallel lines at the given positions. |
figimage |
Add a non-resampled image to the figure. |
figlegend |
Place a legend on the figure. |
fignum_exists |
Return whether the figure with the given id exists. |
figtext |
Add text to figure. |
figure |
Create a new figure. |
fill |
Plot filled polygons. |
fill_between |
Fill the area between two horizontal curves. |
fill_betweenx |
Fill the area between two vertical curves. |
findobj |
Find artist objects. |
gca |
Get the current Axes instance on the current figure matching the given keyword args, or create one. |
gcf |
Get the current figure. |
gci |
Get the current colorable artist. |
get_figlabels |
Return a list of existing figure labels. |
get_fignums |
Return a list of existing figure numbers. |
grid |
Configure the grid lines. |
hexbin |
Make a hexagonal binning plot. |
hist |
Plot a histogram. |
hist2d |
Make a 2D histogram plot. |
hlines |
Plot horizontal lines at each y from xmin to xmax. |
imread |
Read an image from a file into an array. |
imsave |
Save an array as an image file. |
imshow |
Display an image, i.e. |
install_repl_displayhook |
Install a repl display hook so that any stale figure is automatically redrawn when control is returned to the repl. |
ioff |
Turn the interactive mode off. |
ion |
Turn the interactive mode on. |
isinteractive |
Return the status of interactive mode. |
legend |
Place a legend on the axes. |
locator_params |
Control behaviour of major tick locators. |
loglog |
Make a plot with log scaling on both the x and y-axis. |
magnitude_spectrum |
Plot the magnitude spectrum. |
margins |
Set or retrieve autoscaling margins. |
matshow |
Display an array as a matrix in a new figure window. |
minorticks_off |
Remove minor ticks from the axes. |
minorticks_on |
Display minor ticks on the axes. |
pause |
Pause for interval seconds. |
pcolor |
Create a pseudocolor plot with a non-regular rectangular grid. |
pcolormesh |
Create a pseudocolor plot with a non-regular rectangular grid. |
phase_spectrum |
Plot the phase spectrum. |
pie |
Plot a pie chart. |
plot |
Plot y versus x as lines and/or markers. |
plot_date |
Plot data that contains dates. |
plotfile |
Plot the data in a file. |
polar |
Make a polar plot. |
psd |
Plot the power spectral density. |
quiver |
Plot a 2D field of arrows. |
quiverkey |
Add a key to a quiver plot. |
rc |
Set the current rc params. |
rc_context |
Return a context manager for managing rc settings. |
rcdefaults |
Restore the rc params from Matplotlib's internal default style. |
rgrids |
Get or set the radial gridlines on the current polar plot. |
savefig |
Save the current figure. |
sca |
Set the current Axes instance to ax. |
scatter |
A scatter plot of y vs x with varying marker size and/or color. |
sci |
Set the current image. |
semilogx |
Make a plot with a log scale on the x-axis. |
semilogy |
Make a plot with log scaling on the y-axis. |
set_cmap |
Set the default colormap. |
setp |
Set a property on an artist object. |
show |
Display a figure. |
specgram |
Plot a spectrogram. |
spy |
Plot the sparsity pattern of a 2D array. |
stackplot |
Draw a stacked area plot. |
stem |
Create a stem plot. |
step |
Make a step plot. |
streamplot |
Draw streamlines of a vector flow. |
subplot |
Add a subplot to the current figure. |
subplot2grid |
Create an axis at a specific location inside a regular grid. |
subplot_tool |
Launch a subplot tool window for a figure. |
subplots |
Create a figure and a set of subplots. |
subplots_adjust |
Tune the subplot layout. |
suptitle |
Add a centred title to the figure. |
switch_backend |
Close all open figures and set the Matplotlib backend. |
table |
Add a table to an Axes. |
text |
Add text to the axes. |
thetagrids |
Get or set the theta gridlines on the current polar plot. |
tick_params |
Change the appearance of ticks, tick labels, and gridlines. |
ticklabel_format |
Change the ScalarFormatter used by default for linear axes. |
tight_layout |
Automatically adjust subplot parameters to give specified padding. |
title |
Set a title for the axes. |
tricontour |
Draw contours on an unstructured triangular grid. |
tricontourf |
Draw contours on an unstructured triangular grid. |
tripcolor |
Create a pseudocolor plot of an unstructured triangular grid. |
triplot |
Draw an unstructured triangular grid as lines and/or markers. |
twinx |
Make and return a second axes that shares the x-axis. |
twiny |
Make and return a second axes that shares the y-axis. |
uninstall_repl_displayhook |
Uninstall the matplotlib display hook. |
violinplot |
Make a violin plot. |
vlines |
Plot vertical lines. |
xcorr |
Plot the cross-correlation between x and y. |
xkcd |
Turn on xkcd sketch-style drawing mode. |
xlabel |
Set the label for the x-axis. |
xlim |
Get or set the x limits of the current axes. |
xscale |
Set the x-axis scale. |
xticks |
Get or set the current tick locations and labels of the x-axis. |
ylabel |
Set the label for the y-axis. |
ylim |
Get or set the y-limits of the current axes. |
yscale |
Set the y-axis scale. |
yticks |
Get or set the current tick locations and labels of the y-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 labelling 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 which 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 which 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 proportion. 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 which 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 countour 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 article, we studied python matplotlib, matplotlib pyplot, matplotlib inline, installing matplotlib, the anatomy of a figure, backend in matplotlib, list of backend renderers, list of pyplot matplotlib functions, plotting 2D and 3D graphs, types of 2D and 3D graphs and python implementation of these functionalities. Hope you were able to understand each and everything. For any doubts, please comment on your query.
in the next article, we will learn about seaborn, library series.
congratulations!!! you have climbed your next step in becoming a successful ml engineer.
Next Article In this Series >>
Seaborn