0% found this document useful (0 votes)
9 views

Data Visualization and Matplotlib

data visulization
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Data Visualization and Matplotlib

data visulization
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Visualization with Matplotlib

https://www.w3schools.com/pytho
n/matplotlib_scatter.asp

Data Visualization
● Data Visualization refers to the graphical or visual representation of information and data
using visual elements like charts, graphs, maps etc
● It is immensely useful in decision making to understand the meaning of data to drive
business decision
● For data visualization in Python the Matplotlib library’s pyplot is used
● Pyplot is a collection of methods within matplotlib library of python to construct 2D plot
easily and interactively
● Matplotlib library is preinstalled with Anaconda distribution
● In order to use pyplot for data visualization, user need to import the pyplot module as
follows:
import matplotlib.pyplot as plt
What is Matplotlib?
Matplotlib is a low level graph plotting library in python that serves as a visualization utility.

Matplotlib was created by John D. Hunter.

Matplotlib is open source and we can use it freely.

Matplotlib is mostly written in python, a few segments are written in C, Objective-C and Javascript for Platform
compatibility.

Installation of Matplotlib
If you have Python and PIP already installed on a system, then installation of Matplotlib is very easy.

Install it using this command:

C:\Users\Your Name>pip install matplotlib

Import Matplotlib
Once Matplotlib is installed, import it in your applications by adding the import module statement:

import matplotlib

Checking Matplotlib Version


The version string is stored under __version__ attribute.

import matplotlib

print(matplotlib.__version__)

output

2.0.0
Matplotlib Pyplot
Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under the
plt alias:

import matplotlib.pyplot as plt

Now the Pyplot package can be referred to as plt .

Types of Plots

Matplotlib consists of several plots like

● Line

● Bar

● Scatter

● histogram

● Pie etc.
Matplotlib Plotting
Plotting x and y points
The plot() function is used to draw points (markers) in a diagram.

By default, the plot() function draws a line from point to point.

The function takes parameters for specifying points in the diagram.

Parameter 1 is an array containing the points on the x-axis.

Parameter 2 is an array containing the points on the y-axis.

The x-axis is the horizontal axis.

The y-axis is the vertical axis.

Example
Draw a line in a diagram from position (1, 3) to position (8, 10):

import matplotlib.pyplot as plt


import numpy as np

xpoints = np.array([1, 8])


ypoints = np.array([3, 10])

plt.plot(xpoints, ypoints)
plt.show()
Plotting Without Line
To plot only the markers, you can use shortcut string notation parameter 'o', which means
'rings'.
Example:
Draw two points in the diagram, one at position (1, 3) and one in position (8, 10):

import matplotlib.pyplot as plt

import numpy as np

xpoints = np.array([1, 8])

ypoints = np.array([3, 10])

plt.plot(xpoints, ypoints, 'o')

plt.show()

Multiple Points
We can plot as many points as we like,but there should be same number of points in both axis.

Example
Draw a line in a diagram from position (1, 3) to (2, 8) then to (6, 1) and finally to position (8, 10):

import matplotlib.pyplot as plt

import numpy as np

xpoints = np.array([ 1, 2, 6, 8])

ypoints = np.array([ 3, 8, 1, 10])

plt.plot(xpoints, ypoints)

plt.show()
Default X-Points
If we do not specify the points on the x-axis, they will get the default values 0, 1, 2, 3 (etc., depending on
the length of the y-points. So, if we take the same example as above, and leave out the x-points The
x-points in the example will take [0, 1, 2, 3, 4, 5], the diagram will look like this:

Example Plotting without x-points:

import matplotlib.pyplot as plt

import numpy as np

ypoints = np.array([ 3, 8, 1, 10, 5, 7])

plt.plot(ypoints)

plt.show()

Matplotlib Markers
Markers
You can use the keyword argument marker to emphasize each point with a specified marker:

Example: Mark each point with a circle:


import matplotlib.pyplot as plt
import numpy as np

ypoints = np.array([ 3, 8, 1, 10])

plt.plot(ypoints, marker = 'o')


plt.show()
Example
Mark each point with a star:

...
plt.plot(ypoints, marker = '*')
...

Marker Reference 'P' Pentagon

You can choose any of these markers: 'H' Hexagon

Marker Description 'H' Hexagon

'O' Circle 'V' Triangle Down

'*' Star
'^' Triangle Up
'.’ Point
'<' Triangle Left
',' Pixel
'>' Triangle Right
'X’ X
'1' Tri Down
'X' X (filled)
'2' Tri Up
'+' Plus
'3' Tri Left
'P' Plus (filled)
'4' Tri Right
'S' Square
'|' Vline
'D' Diamond
'_' Hline
'D' Diamond (thin)
Format Strings fmt
You can use also use the shortcut string notation parameter to specify the marker.This parameter is
also called fmt, and is written with this syntax:

Marker|line|color

The line value can be one of the following:


Line Reference
Line Syntax Description
'-' Solid line
':' Dotted line
'--' Dashed line
'-.' Dashed/dotted line
Note: If you leave out the line value in the fmt parameter, no line will be plotted.

The short color value can be one of the following:

Color Reference
Color Syntax Description
'r' Red
'g' Green
'b' Blue
'c' Cyan
'm' Magenta
'y' Yellow
'k' Black
'w' White
We can also use Hexadecimal color values by giving color prefixed with # followed by hexadecimal
code for red, green and blue from 0-9 and A-F, eg: #3CAA9F

We can also give color names like red, blue , green, pink, hotpink etc
Example Mark each point with a circle dotted line in red
color:

import matplotlib.pyplot as plt

import numpy as np

ypoints = np.array([ 3, 8, 1, 10])

plt.plot(ypoints, 'o:r')

plt.show()

Marker Size
The keyword argument markersize or the shorter version, ms is used to set the size of the markers:

Example Set the size of the markers to 20:

import matplotlib.pyplot as plt

import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, marker = 'o', ms = 20)

plt.show()
Marker Color
The keyword argument markeredgecolor or the shorter mec to set the color of the edge of the markers:

Example Set the EDGE color to red:

import matplotlib.pyplot as plt

import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, marker = 'o', ms = 20, mec = 'r')

plt.show()

Markerfacecolor keyword:

The keyword argument markerfacecolor or the shorter mfc is used to set the color inside the edge of
the markers:

Example Set the FACE color to red:

import matplotlib.pyplot as plt

import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, marker = 'o', ms = 20, mfc = 'r')

plt.show()
Using both the mec and mfc arguments to color the entire marker:

Example Set the color of both the edge and the face to red:

import matplotlib.pyplot as plt

import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, marker = 'o', ms = 20, mec = 'r', mfc = 'r')

plt.show()

Example
Mark each point with a beautiful green color using hexadecimal code for coloring markeredgecolor mec and
markerfacecolor mfc:

import matplotlib.pyplot as plt

import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, marker = 'o', ms = 20, mec = '#4CAF50', mfc = '#4CAF50')

plt.show()
Matplotlib Line
Linestyle
The keyword argument linestyle, or shorter ls, to change the style of the plotted line:

Line Styles

You can choose any of these styles:

Style Or

'solid' (default) '-'

'dotted' ':'

'dashed' '--'

'dashdot' '-.'

'None' '' or ' '

Example Use a dotted line:

import matplotlib.pyplot as plt

import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, linestyle = 'dotted')

plt.show()
Example:
Use a dashed line:

plt.plot(ypoints, linestyle = 'dashed')

Shorter Syntax
The line style can be written in a shorter syntax:

linestyle can be written as ls.

dotted can be written as :.

dashed can be written as –

Example
plt.plot(ypoints, ls = ':')

Line Color
The keyword argument color or the shorter c is used to set the color of the line:

Color Reference
Color Syntax Description
'r' Red
'g' Green
'b' Blue
'c' Cyan
'm' Magenta
'y' Yellow
'k' Black
'w' White
We can also use Hexadecimal color values by giving color prefixed with # followed by hexadecimal code for red,
green and blue from 0-9 and A-F, eg: #3CAA9F

We can also give color names like red, blue , green, pink, hotpink etc
Example
Set the line color to red:

import matplotlib.pyplot as plt


import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, color = 'r')


plt.show()

You can also use Hexadecimal color values:

Example
Plot with a beautiful green line:

plt.plot(ypoints, c = '#4CAF50')

Example
Plot with the color named "hotpink":

plt.plot(ypoints, c = 'hotpink')

Line Width
You can use the keyword argument linewidth or the shorter lw to change the width of the line.

The value is a floating number, in points:

Example Plot with a 20.5pt wide line:


import matplotlib.pyplot as plt

import numpy as np

ypoints = np.array([3, 8, 1, 10])

plt.plot(ypoints, linewidth = '20.5')

plt.show()
Multiple Lines
We can plot as many lines as needed by simply adding more plt.plot() functions:

Example
Draw two lines by specifying a plt.plot() function for each line:

import matplotlib.pyplot as plt

import numpy as np

y1 = np.array([3, 8, 1, 10])

y2 = np.array([6, 2, 7, 11])

plt.plot(y1)

plt.plot(y2)

plt.show()

Example
Draw two lines by specifiyng the x- and y-point values for both lines:

import matplotlib.pyplot as plt


import numpy as np

x1 = np.array([0, 1, 2, 3])
y1 = np.array([3, 8, 1, 10])
x2 = np.array([0, 1, 2, 3])
y2 = np.array([6, 2, 7, 11])

plt.plot(x1, y1, x2, y2)


plt.show()
Matplotlib Labels and Title
Create Labels for a Plot
The functions xlabel() and ylabel() functions to set a label for the x- and y-axis.

Example
Add labels to the x- and y-axis:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.plot(x, y)

plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
plt.show()

Create a Title for a Plot


The function title() function to set a title for the plot.

Example : Add a plot title and labels for the x- and y-axis:
import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 85, 90, 95, 100, 105, 110,
115, 120, 125])
y = np.array([240, 250, 260, 270, 280,
290, 300, 310, 320, 330])
plt.plot(x, y)
plt.title("Sports Watch Data")
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
plt.show()
Matplotlib Adding Grid Lines
Add Grid Lines to a Plot
The grid() function with Pyplot is used to add grid lines to the plot

the axis parameter in the grid() function to specify which grid lines to display.

Legal values are: 'x', 'y', and 'both'. Default value is 'both'.

Example
Add grid lines to the plot:

import numpy as np
import matplotlib.pyplot as plt
x = np.array([ 80, 85, 90, 95, 100, 105,
110, 115, 120, 125])
y = np.array([ 240, 250, 260, 270, 280,
290, 300, 310, 320, 330])
plt.title( "Sports Watch Data" )
plt.xlabel( "Average Pulse" )
plt.ylabel( "Calorie Burnage" )
plt.plot(x, y)
plt.grid()
plt.show()

Example
Display only grid lines for the x-axis:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.title("Sports Watch Data")


plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

plt.plot(x, y)

plt.grid(axis = 'x')

plt.show()
Example
Display only grid lines for the y-axis:

import numpy as np
import matplotlib.pyplot as plt

x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])

plt.title("Sports Watch Data")


plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

plt.plot(x, y)

plt.grid(axis = 'y')

plt.show()

Set Line Properties for the Grid


The line properties of the grid, like this: grid(color = 'color', linestyle = 'linestyle', linewidth =
number).

Example Set the line properties of the grid:


import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 85, 90, 95, 100, 105,
110, 115, 120, 125])
y = np.array([240, 250, 260, 270,
280, 290, 300, 310, 320, 330])
plt.title("Sports Watch Data")
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")

plt.plot(x, y)

plt.grid(color = 'green', linestyle = '--', linewidth = 0.5)

plt.show()
Matplotlib Subplot
Display Multiple Plots
The subplot() function is used to draw multiple plots in one figure:

The subplot() Function


The subplot() function takes three arguments that describes the layout of the figure and it takes 3 arguments

The layout is organized in rows and columns, which are represented by the first and second argument.

The third argument represents the index of the current plot.


Example:
plt.subplot(1, 2, 1)
#the figure has 1 row, 2 columns, and this plot is thefirst plot.
plt.subplot(1, 2, 2)
#the figure has 1 row, 2 columns, and this plot is thesecond plot.
If we want a figure with 2 rows an 1 column (meaning that the two plots will be displayed on top of each other
instead of side-by-side), then we can define subplot like plt.subplot(2,1,1) refers first plot and plt.subplot(2,1,2)
second plot

Example
Draw 2 plots:

import matplotlib.pyplot as plt


import numpy as np

#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(1, 2, 1)
plt.plot(x,y)

#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

plt.subplot(1, 2, 2)
plt.plot(x,y)

plt.show()
Example
Draw 2 plots on top of each other:

import matplotlib.pyplot as plt


import numpy as np

#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(2, 1, 1)
plt.plot(x,y)

#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

plt.subplot(2, 1, 2)
plt.plot(x,y)

plt.show()

Example plt.subplot(2, 3, 4)
Draw 6 plots: plt.plot(x,y)

import matplotlib.pyplot as plt x = np.array([0, 1, 2, 3])


import numpy as np y = np.array([3, 8, 1, 10])

x = np.array([0, 1, 2, 3]) plt.subplot(2, 3, 5)


y = np.array([3, 8, 1, 10]) plt.plot(x,y)

plt.subplot(2, 3, 1) x = np.array([0, 1, 2, 3])


plt.plot(x,y) y = np.array([10, 20, 30, 40])

x = np.array([0, 1, 2, 3]) plt.subplot(2, 3, 6)


y = np.array([10, 20, 30, 40]) plt.plot(x,y)

plt.subplot(2, 3, 2) plt.show()
plt.plot(x,y)

x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(2, 3, 3)
plt.plot(x,y)

x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
Title
The title to each plot can be added with the title() function

Super Title
The title to the entire figure is added with the suptitle() function

Example
Add a title and super title for the entire figure:

import matplotlib.pyplot as plt


import numpy as np

#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(1, 2, 1)
plt.plot(x,y)
plt.title("SALES")

#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.title("INCOME")
#super title
plt.suptitle("MY SHOP")
plt.show()
Matplotlib Scatter
Creating Scatter Plots
With Pyplot, the scatter() function is used to draw a scatter plot.
The scatter() function plots one dot for each observation. It needs two arrays of the same length, one for the
values of the x-axis, and one for values on the y-axis

Example: A simple scatter plot:The observation in the example above is the result of 13 cars passing by.
The X-axis shows how old the car is. The Y-axis shows the speed of the car when it passes.

import matplotlib.pyplot as plt


import numpy as np
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,
94,78,77,85,86])
plt.scatter(x, y)
plt.show()

Compare Plots
In the example above, there seems to be a relationship between speed and age, but what if we plot the observations
from another day as well the plot can be show the relationship between two days car performance

Example Draw two plots on the same figure:

import matplotlib.pyplot as plt


import numpy as np

#day one, the age and speed of 13 cars:


x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)
#day two, the age and speed of 15 cars:
x = np.array([2,2,8,1,15,8,12,9,7,3,11,4,7,14,12])
y = np.array([100,105,84,105,90,99,90,95,94,100,79,112,91,80,85])
plt.scatter(x, y)

plt.show()

Note: The two plots are plotted with two different colors, by default blue and orange we can change the colors
Colors
Color argument is used to set own color for each scatter plot or in short we can use c argument:

Example
Set your own color of the markers:
import matplotlib.pyplot as plt
import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y, color = 'hotpink')

x = np.array([2,2,8,1,15,8,12,9,7,3,11,4,7,14,12])
y = np.array([100,105,84,105,90,99,90,95,94,100,79,112,91,80,85])
plt.scatter(x, y, color = '#88c999')

plt.show()

Color Each Dot


C argument is used to set a specific color for each dot by using an array of colors as value for the c argument:

Note: We cannot use the color argument for this, only the c argument is used

Example: Set your own color of the markers:


import matplotlib.pyplot as plt
import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
colors = np.array(["red","green","blue","yellow","pink",
"Black","orange","purple","beige","brown","gray",
"cyan","magenta"])

plt.scatter(x, y, c=colors)

plt.show()

.
ColorMap
The Matplotlib module has a number of available colormaps.

A colormap is like a list of colors, where each color has a value that ranges from 0 to 100.

This colormap is called 'viridis' and it ranges from 0, which is a purple color, up to 100, which
is a yellow color.

Here is an example of a colormap

How to Use the ColorMap


The colormap is specified with the keyword argument cmap with the value of the colormap,
The ‘viridis' is one of the built-in colormaps available in Matplotlib.

In addition we have to create an array with values (from 0 to 100), one value for each point
in the scatter plot

colorbar()

Colormap can be included in the figure by using colorbar() function of pyplot lib

Example
Create a color array, and specify a colormap in the scatter plot:

import matplotlib.pyplot as plt


import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90,
100])

plt.scatter(x, y, c=colors, cmap='viridis')

plt.show()
You can include the colormap in the drawing by including the plt.colorbar() statement:

Example for including colormap

import matplotlib.pyplot as plt

import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])

y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])

colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60,

70, 80, 90, 100])

plt.scatter(x, y, c=colors, cmap='viridis')

plt.colorbar()

plt.show()

Example for include the actual colormap using colorbar():

import matplotlib.pyplot as plt

import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])

y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])

colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70,
80, 90, 100])

plt.scatter(x, y, c=colors, cmap='viridis')

plt.colorbar()

plt.show()
Available ColorMaps
Some of the the built-in colormaps:

Name Reverse
Accent Accent_r
Blues Blues_r
BrBG BrBG_r
BuGn BuGn_r
BuPu BuPu_r
CMRmap CMRmap_r
Dark2 Dark2_r
GnBu GnBu_r
Greens Greens_r
Greys Greys_r
OrRd OrRd_r
Oranges Oranges_r
PRGn PRGn_r
Paired Paired_r
Pastel1 Pastel1_r
Pastel2 Pastel2_r
PiYG PiYG_r

Size
The size of the dots can be changed using the s argument.
The array of sizes having same length as the array of for the x- and y-axis is passed as value for the
argument

Example Set your own size for the markers:

import matplotlib.pyplot as plt


import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])

y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])

sizes = np.array([20,50,100,200,500,1000,60,90,10,300,600,800,75])

plt.scatter(x, y, s=sizes)

plt.show()
Alpha
The transparency of the dots can be set using the alpha argument. This take value ranging from 0 to 1, 0 being
more transparent and 1 more opaque

Example Set your own size for the markers:

import matplotlib.pyplot as plt

import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])

y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])

sizes = np.array([20,50,100,200,500,1000,60,90,10,300,600,800,75])

plt.scatter(x, y, s=sizes, alpha=0.5)

plt.show()

Example: Combine Color Size and Alpha

Create random arrays with 100 values for x-points, y-points, colors and sizes:

import matplotlib.pyplot as plt

import numpy as np

x = np.random.randint(100, size=(100))

y = np.random.randint(100, size=(100))

colors = np.random.randint(100, size=(100))

sizes = 10 * np.random.randint(100, size=(100))

plt.scatter(x, y, c=colors, s=sizes, alpha=


0.5, cmap='nipy_spectral')

plt.colorbar()

plt.show()
Visualizing Errors

data visualization is the graphical representation of information and data by using visual elements like charts graphs and maps.

data visualization tools provide an accessible way to see and understand trends outliers and patterns in data.

error bars help to indicate estimated error or uncertainty to give a general sense of how precise a measurement is done, through
the use of markers drawn over the original graph and its data points.

Typically error bars are used to display either the standard deviation standard error confidence intervals or the minimum and
maximum values in ranged dataset.

Usage of Error bars to Visualize errors:


● Error is a mistake or we can say that difference between the calculated value and actual
value.
● When we graphical represent the data, some of the data have irregularity. To indicate these
irregularities or uncertainties we use Error Bars.
● Basically, error bars are used to represent errors in the graphical plot.
● The length of an Error Bar helps reveal the uncertainty of a data point:
● A short Error Bar shows that values are concentrated, signalling that the plotted average value is
more likely, while a long Error Bar would indicate that the values are more spread out and less
reliable.
● Also depending on the type of data, the length of each pair of Error Bars tend to be of equal length
on both sides. However, if the data is skewed, then the lengths on each side would be unbalanced.
● Error Bars always run parallel to a quantitative scale axis, so they can be displayed either vertically
or horizontally, depending on whether the quantitative scale is on the Y or X axis. If there are two
quantitative scales, then two pairs of Error Bars can be used for both axes.
The following steps are used to plot error bars in matplotlib which is outlined below:

● Defining Libraries: Import the libraries which are required to plot error bars (For data
creation and manipulation: Numpy, For data visualization: pyplot from matplotlib).
● Define X and Y: Define the data values used for plotting. Data values of x-axis and
y-axis.
● Plot error bars: By using the errorbar() method we can plot the error bars.
● Display: Finally we have to use the show() method to display the plot.
matplotlib.pyplot.errorbar() Function:

The errorbar() function in pyplot module of matplotlib library is used to plot y versus x as lines
and/or markers with attached errorbars.
The syntax to plot error bars is as below:
matplotlib.pyplot.errorbar(x, y, yerr=None, xerr=None, fmt='', ecolor=None,
elinewidth=None, capsize=None, barsabove=False, lolims=False, uplimes=False,
xlolims=False, xuplims=False, errorevery=1, capthick=None, * , data=None,
**kwargs)

The above-used parameters are as below:

● x: specifies horizontal coordinates of the data points.


● y: specifies vertical coordinates of the data points.
● xerr: Define the horizontal error bar sizes. Must have a float or array-like shape.
● yerr: Define the vertical error bar sizes. Must have a float or array-like shape.

● fmt: Contains string value. By default, this plot error bars with markers. Use ‘none’ to
plot error bars without markers.

● ecolor: specifies the color of the error bars.

● elinewidth: specifies linewidth of the error bars.

● capsize: specifies the length of error bars in points or float.

● capthick: specifies the thickness of error bars cap in float or points.

● barsabove: It contains bool value. By default value is False, if the value is True error
bars are plotted above the plot symbol.

● lolims,uplims,xlolims,xuplims: specifies that value gives only upper and lower limits.
It contains bool value.

● errorevery: It contains integer values and is used to draw error bars on the subset of
the data.
Example
# Import Library
import matplotlib.pyplot as plt

# Define Data
x= [1, 2, 3, 5]
y= [9, 15, 20, 25]

# Plot error bar


plt.errorbar(x, y, xerr = 0.9)

# Display graph
plt.show()
● In the above, example we import the matplotlib.pyplot library.
● Then we define the x-axis and y-axis data points.
● plt.errorbar() method is used to plot error bars and we pass the argument x,
y, and xerr and set the value of xerr = 0.9. Which is the length of the error
line
● Then we use plt.show() method to display the error bar plotted graph.

Matplotlib plot interactive error bars


We can format or customizing the error bar according to our choice by setting the parameters of
errorbar function, to make the error bar more interactive.

Let’s change the following things in the error bars to become it more interactive:

● fmt: change style of marker. Set it to circle.

● color: change the color of the marker. Set it to orange.

● ecolor: change the color of the error bar. Set it to lightgreen.

● elinewidth: change the line width of the error bar. Set it to 5.

● capsize: change the capsize of the error bar. Set it to 10.


Example

# Import Library
import matplotlib.pyplot as plt

# Define Data
x= [1, 2, 3, 5]
y= [9, 15, 20, 25]

# Plot error bar


plt.errorbar(x, y, xerr = 0.9, fmt = 'o',color = 'orange',
ecolor = 'lightgreen', elinewidth = 5, capsize=10)

# Display graph
plt.show()

Matplotlib chart error bars


We use plt.errorbar() method to plot error bars in bar charts.

The following are the cases in the bar chart in which we draw error bars:

● Error in x values
● Error in y values
● Error in both x and y values
Matplotlib chart error bars to plot error in x values
The plt.errorbar() method is used to plot the error bars and pass the argument xerr to plot error
on the x values.

The syntax for this is:

matplotlib.pyplot.errorbar(x, y, xerr=None)

Where xerr parameter takes error line size

# Import Library
import matplotlib.pyplot as plt

# Define Data
x= [6, 15, 2.3, 9]
y= [9, 15, 20, 25]

# Define Error
x_error = [2.3, 5.1, 1, 3.1]

# Plot Bar chart


plt.bar(x,y)

# Plot error bar


plt.errorbar(x, y, xerr = x_error,fmt='o',ecolor = 'red',color='yellow')

# Display graph
plt.show()
● In the above example, we import matplotlib.pyplot library and
define the data point on the x-axis and y-axis.
● Then we define the error value and use the plt.bar() method to
plot a bar chart.
● plt.errorbar() method is used to plot error bars and we pass
xerr as an argument and set its value to be x_error value which
are defined.

Matplotlib chart error bars in y values


By using the plt.errorbar() method we plot the error bars and pass the argument yerr to
plot error on the y values.

The syntax to plot error bars on y values:


matplotlib.pyplot.errorbar(x, y, yerr=None)

Example
# Import Library # Plot Bar chart
import matplotlib.pyplot as plt plt.bar(x,y)

# Define Data # Plot error bar


x= [6, 15, 2.3, 9] plt.errorbar(x, y, yerr = y_error,fmt='o',ecolor =
y= [9, 15, 20, 25] 'red',color='yellow')
# Define Error
y_error = [2.3, 5.1, 1, 3.1] # Display graph
plt.show()
● In the above example, we import matplotlib.pyplot library

● After this defines the data point on the x-axis and y-axis.

● Then we define the error value and use the plt.bar() method to plot a bar
chart and use plt.errorbar() method is used to plot error bars.

● Pass yerr as an argument and set its value to equal y_error value which we
define.

Matplotlib chart error bars in x and y values


By using the plt.errorbar() method we plot the error bars and pass the argument xerr and yerr
to plot error on both x and y values respectively.

The syntax to plot error bars on both the values is as given below:

matplotlib.pyplot.errorbar(x, y, xerr=None, yerr=None)


Example
# Import Library
import matplotlib.pyplot as plt

# Define Data
x= [6, 15, 2.3, 9]
y= [9, 15, 20, 25]

# Define Error
x_error = [4.2, 6, 10, 8.6]
y_error = [2.3, 5.1, 1, 3.1]
● In the above plot after drawing bar
# Plot Bar chart chart using the plt.bar() method , plot
plt.bar(x,y) error bars using plt.errorbar() method
● Pass xerr, yerr as an argument and
# Plot error bar
set its value to equal x_error, y_error
plt.errorbar(x, y, xerr = x_error, yerr = y_error,
fmt='o', ecolor = 'red',color='yellow') values which are define
# Display graph
plt.show()

Matplotlib scatter plot error bars


plt.errorbar() method can be to plot error bars in scatter plot , same as on bar chart

The following are the cases in the scatter plot in which we draw error bars:

● Error in x values: Using errorbar() we plot the error bars and pass the argument xerr to
plot error on the x values in the scatter plot using syntax
matplotlib.pyplot.errorbar(x, y, xerr=None)

● Error in y values : Using errorbar() we plot the error bars and pass the argument yerr
to plot error on the y values in the scatter plot using syntax
matplotlib.pyplot.errorbar(x, y, yerr=None)

● Error in both x and y values: Using errorbar() we plot the error bars and pass the
arguments xerr, yerr to plot error on the x and y values in the scatter plot using syntax
matplotlib.pyplot.errorbar(x, y, yerr=None)
Example: Plotting error on x values in scatter plot
# Import Library
import matplotlib.pyplot as plt

# Define Data
x= [10, 20, 30, 40]
y= [4, 8, 12, 16]

# Define Error
x_error = [2, 4, 6, 8]

# Plot scatter plot


plt.scatter(x,y)

# Plot error bar


plt.errorbar(x, y, xerr = x_error,fmt='o',ecolor = 'cyan',color='black')

# Display graph
plt.show()

Example: Plotting error on y values in scatter plot


# Import Library
import matplotlib.pyplot as plt

# Define Data
x= [10, 20, 30, 40]
y= [4, 8, 12, 16]

# Define Error
y_error = [2, 4, 6, 8]

# Plot Scatter Plot


plt.scatter(x,y)

# Plot error bar


plt.errorbar(x, y, yerr = y_error,fmt='o',ecolor = 'cyan',color='black')

# Display graph
plt.show()
Example: Plotting error on y values in scatter plot
# Import Library
import matplotlib.pyplot as plt

# Define Data
x= [10, 20, 30, 40]
y= [4, 8, 12, 16]

# Define Error
x_error= [3, 6, 9, 12]
y_error = [2, 4, 6, 8]

# Plot Scatter Plot


plt.scatter(x,y)

#Plot error bar


plt.errorbar(x, y, xerr= x_error, yerr = y_error,fmt='o',ecolor = 'cyan',color='black')

# Display graph
plt.show()

Density Plot
Density Plot is a type of data visualization tool. It is a variation of the histogram that uses
‘kernel smoothing’ while plotting the values. It is a continuous and smooth version of a
histogram inferred from a data.
Density plots uses Kernel Density Estimation (so they are also known as Kernel density
estimation plots or KDE) which is a probability density function. The region of plot with a
higher peak is the region with maximum data points residing between those values.
Density plots can be made using pandas, seaborn, etc. , we will generate density plots
using Pandas. We will be using two datasets of the Seaborn Library namely –
‘car_crashes’ and ‘tips’.
Syntax: pandas.DataFrame.plot.density | pandas.DataFrame.plot.kde

where pandas -> the dataset of the type ‘pandas dataframe’


Dataframe -> the column for which the density plot is to be drawn
plot -> keyword directing to draw a plot/graph for the given column
density -> for plotting a density graph
kde -> to plot a density graph using the Kernel Density Estimation function

The easiest way to create a density plot in Matplotlib is to use the


kdeplot() function from the seaborn visualization library:

import seaborn as sns

#define data
data = [value1, value2, value3, ...]

#create density plot of data


sns.kdeplot(data)
Example
import seaborn as sns
import matplotlib.pyplot as plt
#define data
data = [2, 2, 3, 5, 6, 6, 7, 8, 9, 10,
12, 12, 13, 15, 16]

#create density plot of data


sns.kdeplot(data)
plt.show()

The x-axis shows the data values and


the y-axis shows the corresponding probability density
values.

bw_method argument:
This argument is used to adjust the smoothness of density plot , if its
value is low it leads to ore wiggly plot and if the value is high leads to
smoother plot
Example 2: Adjust Smoothness of Density Plot

You can use the bw_method argument to adjust the smoothness of the density plot.
Lower values lead to a more “wiggly” plot.

import seaborn as sns


import matplotlib.pyplot as plt
#define data
data = [2, 2, 3, 5, 6, 6, 7, 8, 9,
10, 12, 12, 13, 15, 16]

#create density plot of data with low bw_method value


sns.kdeplot(data, bw_method = .3)
plt.show()
Example: Drawing density plot with smoother plot
import seaborn as sns
import matplotlib.pyplot as plt

#define data
data = [2, 2, 3, 5, 6, 6, 7, 8, 9, 10, 12, 12, 13, 15, 16]

#create density plot of data with high bw_method value


sns.kdeplot(data, bw_method = .8)
plt.show()

Example 3: Customize Density Plot

You can also customize the color and style of the density plot:

import matplotlib.pyplot as plt


import seaborn as sns

#define data
data = [2, 2, 3, 5, 6, 6, 7, 8, 9, 10, 12, 12, 13, 15, 16]

#create density plot of data with high bw_method value


sns.kdeplot(data, color='red', fill=True, alpha=.3, linewidth=0)
plt.show()
Contour plots
Contour plots (sometimes called Level Plots) are a way to show a three-dimensional surface on a
two-dimensional plane. It graphs two predictor variables X Y on the y-axis and a response variable Z as
contours. These contours are sometimes called the z-slices or the iso-response values.

A contour plot is appropriate if you want to see how alue Z changes as a function of two inputs X and Y, such
that Z = f(X,Y). A contour line or isoline of a function of two variables is a curve along which the function has a
constant value.

The independent variables x and y are usually restricted to a regular grid called meshgrid. The
numpy.meshgrid creates a rectangular grid out of an array of x values and an array of y values.

Matplotlib API contains contour() and contourf() functions that draw contour lines and filled contours,
respectively. Both functions need three parameters x,y and z.

Example:
import numpy as np
import matplotlib.pyplot as plt
xlist = np.linspace(0, 5, 50)
ylist = np.linspace(0, 5, 50)
x,y= np.meshgrid(xlist, ylist)
z = np.sin(x)**8+np.cos(20+y*x)*np.cos(y)
plt.contour(x,y,z)
plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.title("Contour Plot Example")
plt.colorbar()
plt.show()
Note: The above example draw outlined contour plot
The contour plot can be formatted with attributes
colors=”name of the color” like red, blue, green, pink etc
linestyles=”style of line” like dashed, dasheddotted, dotted , solid(default style)
linewidths=numberic value (default is 1.5)
Eg:
plt.contour(x,y,z, linestyles=”dotted”,linewidths=”3”,colors=”red”)
plt.show()

Example to plot filled contour plot using contourf() method


import numpy as np
import matplotlib.pyplot as plt
xlist = np.linspace(0, 5, 50)
ylist = np.linspace(0, 5, 50)
x,y= np.meshgrid(xlist, ylist)
z = np.sin(x)**8+np.cos(20+y*x)*np.cos(y)
plt.contourf(x,y,z)
plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.title("Contour Plot Example")
plt.colorbar()
plt.show()
The contour plot can be formatted with attributes
cmap=”Colormap style” like RdGn(Red & Green), RdGy(Red & Gray),
BuGy(Blue & Gray), autumn_r,BuPu etc
Alpha=any range of values from 0 to 1 to set the transparency (0 being more
transparent , 1 being more opaque)

Eg:
plt.contourf(x,y,z,cmap="Spectral", alpha=0.8)
plt.show()

Matplotlib Histograms
Histogram
A histogram is a graph showing frequency distributions. It is a graph showing the number
of observations within each given interval.

Each interval is represented with a bar, placed next to the other intervals on a number line.

The height of the bar represents the frequency of values in that interval.

Create Histogram
In Matplotlib, we use the hist() function to create histograms.

The hist() function will use an array of numbers to create a histogram,


the array is sent into the function as an argument.
Attribute parameter

x array or sequence of array

bins optional parameter contains integer or sequence or strings

density optional parameter contains boolean values

range optional parameter represents upper and lower range of bins

histtype optional parameter used to create type of histogram [bar, barstacked, step, stepfilled], default is “bar”

align optional parameter controls the plotting of histogram [left, right, mid]

weights optional parameter contains array of weights having same dimensions as x

bottom location of the baseline of each bin

rwidth optional parameter which is relative width of the bars with respect to bin width

Attribute parameter

color optional parameter used to set color or sequence of color specs

label optional parameter string or sequence of string to match with multiple datasets

log optional parameter used to set histogram axis on log scale

Example:
import numpy as np
import matplotlib.pyplot as plt
blood_sugar=[113,85,90,150,149,88,93,115,135,80,
77,82,129]
plt.hist(blood_sugar,bins=[80,100,125,150],
rwidth=0.9,color='r')
plt.show()
Example of drawing histogram using multiple datasets

import numpy as np
import matplotlib.pyplot as plt
men_blood_sugar=[113,85,90,150,149,88,93,
115,135,80,77,82,129]
women_blood_sugar=[67,98,89,120,133,
150,84,69,89,79,120,112,100]
plt.hist([women_blood_sugar,men_blood_sugar],
bins=[80,100,125,150],rwidth=0.9,
color=["#23A2AB","#ACFAA1"],label=['women','men'])
plt.legend()
plt.xlabel("Sugar Ranges")
plt.ylabel("Sugar Values")
plt.title("Sugar Readings vs Ranges")
plt.show()

Density Plot
A density plot is an extension of the histogram. As opposed to the histogram, the density
plot can smooth out the distribution of values and reduce the noise. It visualizes the
distribution of data over a given period, and the peaks show where values are concentrated.

Density Plot is the continuous and smoothed version of the Histogram estimated from the data. It
is estimated through Kernel Density Estimation.
In this method Kernel (continuous curve) is drawn at every individual data point and then all these
curves are added together to make a single smoothened density estimation.
Histogram fails when we want to compare the data distribution of a single variable over the
multiple categories at that time Density Plot is useful for visualizing the data.
Approach:

● Import the necessary libraries.


● Create or import a dataset from seaborn library.
● Select the column for which we have to make a plot.
● For making the plot we are using distplot() function provided by seaborn library for plotting Histogram
and Density Plot together in which we have to pass the dataset column.
● We can also make Histogram and Density Plot individually using distplot() function according to our
needs.
● For creating Histogram individually we have to pass hist=False as a parameter in the distplot()
function.
● For creating Density Plot individually we have to pass kde=False as a parameter in the distplot()
function.
● Now after making the plot we have to visualize that, so for visualization, we have to use show()
function provided by matplotlib.pyplot library.

# importing seaborn library


import seaborn as sns

# importing dataset from the library


df = sns.load_dataset('diamonds')

# printing the dataset


df
Example 2: Plotting the Histogram using seaborn library on the default setting.
# importing necessary libraries
import seaborn as sns
import matplotlib.pyplot as plt

# importing diamond dataset from the library


df = sns.load_dataset('diamonds')

# plotting histogram for carat using distplot()


sns.distplot(a=df.carat, kde=False)

# visualizing plot using matplotlib.pyplot library


plt.show()

Example 3: Plotting the Density using seaborn library on the default setting.

# importing libraries
import seaborn as sns
import matplotlib.pyplot as plt

# importing diamond dataset from the library


df = sns.load_dataset('diamonds')

# plotting density plot for carat using distplot()


sns.distplot(a=df.carat, hist=False)

# visualizing plot using matplotlib.pyplot library


plt.show()
Example 4: Plotting Histogram and Density Plot together on default settings.

# importing libraries
import seaborn as sns
import matplotlib.pyplot as plt

# importing diamond dataset from the library


df = sns.load_dataset('diamonds')

# plotting histogram and density


# plot for carat using distplot()
sns.distplot(a=df.carat)

# visualizing plot using matplotlib.pyplot library


plt.show()

Example 5: Plotting Histogram and Density Plot together by setting bins and color.

# importing libraries
import seaborn as sns
import matplotlib.pyplot as plt

# importing diamond dataset from the library


df = sns.load_dataset('diamonds')

# plotting histogram and density plot


# for carat using distplot() by setting color
sns.distplot(a=df.carat, bins=40, color='purple',
hist_kws={"edgecolor": 'black'})

# visualizing plot using matplotlib.pyplot library


plt.show()
Configurations & Stylesheets

Style Plots using Matplotlib


With matplotlib, we can style the plots like, an HTML webpage is styled by using CSS styles. We
just need to import style package of matplotlib library.

There are various built-in styles in style package, and we can also write customized style files and,
then, to use those styles all you need to import them and apply on the graphs and plots. In this way,
we need not write various lines of code for each plot individually again and again i.e. the code is
reusable whenever required.
To list all the available styles:

from matplotlib import style

print(style.available)

Output:

[‘Solarize_Light2’, ‘_classic_test_patch’, ‘bmh’, ‘classic’, ‘dark_background’, ‘fast’,


‘fivethirtyeight’, ‘ggplot’,’grayscale’,’seaborn’,’seaborn-bright’,’seaborn-colorblind’,
‘seaborn-dark’, ‘seaborn-dark-palette’, ‘seaborn-darkgrid’, ‘seaborn-deep’,
‘seaborn-muted’, ‘seaborn-notebook’, ‘seaborn-paper’, ‘seaborn-pastel’,
‘seaborn-poster’,’seaborn-talk’,’seaborn-ticks’,’seaborn-white’,’seaborn-whitegrid’,’tablea
u-colorblind10′]

Applying a particular style to the plot

Syntax: plt.style.use(‘style_name”)

Where style_name is the name of the style which we want to use.


Approach:
● Import module.
● Create data for plot.
● Use the style want to add in plot.
● Create a plot.
● Show the plot.
Example
# importing all the necessary packages
import numpy as np
import matplotlib.pyplot as plt

# importing the style package


from matplotlib import style

# creating an array of data for plot


data = np.random.randn(50)

# using the style for the plot


plt.style.use('Solarize_Light2')

# creating a plot
plt.plot(data)

# show plot
plt.show()

Example
# importing all the necessary packages
import numpy as np
import matplotlib.pyplot as plt

# importing the style package


from matplotlib import style

# creating an array of data for plot


data = np.random.randn(50)

# using the style for the plot


plt.style.use('dark_background')

# creating a plot
plt.plot(data)

# show plot
plt.show()
Note : But keep in mind that this will change the style for the rest of the session! Alternatively, you can use the
style context manager, which sets a style temporarily:
with plt.style.context('stylename'):
make_a_plot()
Customizing matplotlib

The matplotlibrc file


matplotlib uses matplotlibrc configuration files to customize all kinds of properties, which we call rc settings or rc
parameters. You can control the defaults of almost every property in matplotlib: figure size and dpi, line width, color
and style, axes, axis and grid properties, text and font properties and so on. matplotlib looks for matplotlibrc in three
locations, in the following order:

1. matplotlibrc in the current working directory, usually used for specific customizations that you do not want to
apply elsewhere.
2. It next looks in a user-specific place, depending on your platform:
○ On Linux, it looks in .config/matplotlib/matplotlibrc (or $XDG_CONFIG_HOME/matplotlib/matplotlibrc) if
you’ve customized your environment.
○ On other platforms, it looks in .matplotlib/matplotlibrc.
3. See .matplotlib directory location.

Dynamic rc settings
You can also dynamically change the default rc settings in a python script or interactively from
the python shell. All of the rc settings are stored in a dictionary-like variable called
matplotlib.rcParams , which is global to the matplotlib package. rcParams can be modified
directly, for example:
import matplotlib as mpl
mpl.rcParams['lines.linewidth'] = 2
mpl.rcParams['lines.color'] = 'r'

Matplotlib also provides a couple of convenience functions for modifying rc settings. The
matplotlib.rc() command can be used to modify multiple settings in a single group at once,
using keyword arguments:
import matplotlib as mpl
mpl.rc('lines', linewidth=2, color='r')

The matplotlib.rcdefaults() command will restore the standard matplotlib default settings.
Example
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from cycler import cycler
mpl.rcParams['lines.linewidth'] = 2
mpl.rcParams['lines.linestyle'] = '--'
data = np.random.randn(50)
plt.plot(data)

To create your own style sheet create a file with extension .mpltstyle

Save it any of the folder

And include it in plt.use.style() method to apply it to any plot

plt.use.style(‘my_awesome_style_sheet.mpltstyle')

Example: save the file by name mystyle.mplstyle


axes.titlesize : 24
axes.labelsize : large
axes.facecolor:"pink"
lines.linewidth : 3
lines.markersize : 10
lines.linestyle:"--"
xtick.labelsize : 16
ytick.labelsize : 16
Using the style created for plotting a plot
import matplotlib.pyplot as plt
import numpy as np
x=[3,4,6,7,9]
y=[5,6,7,2,1]
plt.style.use("mystyle.mplstyle")
plt.plot(x,y)
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.title("Custome Style Example")
plt.show()

Three-Dimensional Plotting in Matplotlib


Matplotlib was initially designed with only two-dimensional plotting in mind, some three-dimensional plotting utilities
were built on top of Matplotlib's two-dimensional display in later versions, to provide a set of tools for
three-dimensional data visualization. Three-dimensional plots are enabled by importing the mplot3d toolkit, included
with the Matplotlib package.

A three-dimensional axes can be created by passing the keyword projection='3d' to any of the normal axes creation
routines.

Example: drawing 3d scatter plot with one point

import numpy as np

import matplotlib.pyplot as plt

from mpl_toolkits import mplot3d

ax=plt.axes(projection="3d")

ax.scatter(3,5,7)

plt.show()

Generate a Blank 3D Plot


An empty 3D plot can be created by passing the keyword projection='3D' to the axis creation function:

Example:
import matplotlib.pyplot as pyplot
import numpy as np
from mpl_toolkits import mplot3d

fig = pyplot.figure(figsize = (6, 6))


ax = pyplot.axes(projection = '3d')

# Print the chart


pyplot.show()
3D Line using plot3D and matplotlib
To create 3D lines, you must use the plot3D() function, wherein you need to place the three
parameters of the three axes.
Example
import matplotlib.pyplot as pyplot
import numpy as np
from mpl_toolkits import mplot3d
ax = pyplot.axes(projection = '3d')
#Mentioning all the three different axes.
z = np.linspace(0, 2, 1000)
x = z * np.sin(40 * z)
y = z * np.cos(40 * z)
ax.plot3D(x, y, z, 'blue')
ax.set_title('3D plotting of line chart')
# Print the chart
pyplot.show()

Plotting 3D Surface Plot


The surface graph helps to illustrate a set of 3-dimensional data spread over surfaces as a filled mesh. This graph
becomes useful when there is a need to show the optimal combination or transformation between two data sets.
Professionals use it to see changes in the climate or ecosystem. The ax.plot_surface() function generates Plotting
surface graph.

Example:
import matplotlib.pyplot as pyplot
import numpy as np
from mpl_toolkits import mplot3d
x = np.outer(np.linspace(-2, 4, 8), np.ones(8))
y = x.copy().T
z = np.cos(x ** 3 + y ** 4)
fig = pyplot.figure(figsize = (6, 6))
ax = pyplot.axes(projection = '3d')
ax.plot_surface(x, y, z, cmap ='viridis', edgecolor ='orange')
ax.set_title('PLOT with Yellow as least dense altitude and Black as denser altitude')
# Print the chart
pyplot.show()
Plotting 3D Wireframe plot

These are 3D plots that take a grid of values and project it onto the three-dimensional surface. The resulting generated
graphs become three-dimensional, which is easy to visualize. In the wireframe plot, the plotted surface does not remain
filled. They are simply wavey lines that form the grid-like structure showing the ups and downs of data. Professionals also
use such graphs to see changes in climate or ecosystem. The ax.plot_wireframe() function generates wireframe graph.

import matplotlib.pyplot as pyplot


import numpy as np
from mpl_toolkits import mplot3d
# function to calculate z-axis
def wavey(x, y):
return np.sin(np.sqrt(x ** 2 + y ** 2))
# creating the values for x and y axis
x = np.linspace(-1, 2, 10)
y = np.linspace(-1, 2, 10)
x, y = np.meshgrid(x, y)
z = wavey(x, y)
ax = pyplot.axes(projection = '3d')
ax.plot_wireframe(x, y, z, color = 'red')
ax.set_title('Matplotlib 3D Wireframe Plot Example');
ax.view_init(50, 60)
# Print the chart
pyplot.show()

view_init()
view_init() can be used to rotate the axes programmatically.
Syntax: view_init(elev, azim)

Parameters:

● ‘elev’ stores the elevation angle in the z plane.


● ‘azim’ stores the azimuth angle in the x,y plane.D constructor.

In the above example if we set view_init()


elev=150 and azim=90 we get the plot as shown

You might also like