UNIT 2-VISUALIZING USING
MATPLOTLIB
Syllabus
Importing Matplotlib – Simple line plots – Simple scatter
plots – visualizing errors – density and contour plots –
Histograms – legends – colors – subplots – text and
annotation – customization – three dimensional plotting -
Geographic Data with Basemap - Visualization with
Seaborn
Matplotlib
Matplotlib is a comprehensive library for creating static, animated, and interactive
visualizations in Python.
It is able to create different types of visualization reports like line plots, scatter
plots, histograms, bar charts, pie charts, box plots, and many more different plots
Importing matplotlib
● import matplotlib as plt
● import [Link] as plt
To list all the available styles:
from matplotlib import style
print([Link])
Setting Styles
● use the [Link] directive to choose appropriate aesthetic styles for our figures
● [Link]('classic')
How to Display Your Plots
● The [Link]() command should be used only once per Python session, and
is most often seen at the very end of the script.
● Example
import [Link] as plt
import numpy as np
x = [Link](0, 10, 100)
[Link](x, [Link](x))
[Link](x, [Link](x))
[Link]()
Plotting from an IPython shell
● %matplotlib This command enables interactive plots within the notebook. It
allows you to zoom and resize the figure.
● %matplotlib inline turns on “inline plotting”, where plot graphics will appear in
your notebook.
● Import [Link] as plt
● [Link] is a collection of functions that make matplotlib work like
MATLAB.
● Each pyplot function makes some change to a figure: e.g., creates a figure,
creates a plotting area in a figure, plots some lines in a plotting area,
decorates the plot with labels
Plotting from an IPython notebook
The IPython notebook is a browser-based interactive data analysis tool that can
combine narrative, code, graphics, HTML elements, and much more into a single
executable document.
The %matplotlib inline command tells the IPython environment to draw the plots
immediately after the current cell.
Syntax: %matplotlib inline
Saving Figures to File
Matplotlib is the ability to save figures in a wide variety of formats.
To save image following command is used
[Link]('my_figure.png')
To display the saved image
from [Link] import Image
Image('my_figure.png')
● In savefig(), the file format is inferred from the extension of the given filename.
● list of supported file types for your system can be identified using the following
command
Dual interface of Matplotlib
● MATLAB-style interface
● Object-oriented interface
MATLAB-style interface
● The MATLAB-style tools are contained in the pyplot (plt) interface.
● While this stateful interface is fast and convenient for simple plots(stateful
interface-stores the state of our Figure and Axes objects)
● It keeps track of the “current” figure and axes
● [Link]() (get current figure)
● [Link]() (get current axes)
[Link]()
● subplot() function you can draw multiple plots in one figure
● The subplot() function takes three arguments that describes the layout of the
figure.
● 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.
Eg:
[Link](1, 2, 1)
#the figure has 1 row, 2 columns, and this plot is the first plot.
Example
Object-oriented interface
In object-oriented interface, Pyplot is used only for a few functions such as figure
creation, and the user explicitly creates and keeps track of the figure and axes
objects.
At this level, the user uses Pyplot to create figures, and through those figures, one
or more axes objects can be created. These axes objects are then used for most
plotting actions.
Create a figure:fig = [Link]()
The add_axes() method requires a list object of 4 elements
corresponding to left, bottom, width and height of the figure. Each
number must be between 0 and 1 −
ax=fig.add_axes([0,0,1,1])
Example
Simple Line Plots
Line Plot is one of the easiest and most basic graphical analysis techniques.
They are used to express a relationship between two variables.
A line plot visualizes information as a series of data points called markers
connected by straight line segments. These are also used to express trends in
data over intervals of time
Setting up the notebook for plotting and importing the functions
A figure and axes can be created as follows
In Matplotlib, the figure (an instance of the class [Link]) can be thought of as a
single container that contains all the objects representing axes, graphics, text, and
labels.
The axes (an instance of the class [Link]) is a bounding box with ticks and
labels, which will eventually contain the plot elements that make up our
visualization. Example
Ticks and labels
Multiple lines in single plot
Adjusting the Plot: Line Colors and Styles
The first adjustment you might wish to make to a plot is to control the line colors
and styles.
The [Link]() function takes additional arguments that can be used to specify
these.
To adjust the color, you can use the color keyword, which accepts a string
argument representing virtually any imaginable color.
Line style
If no color is specified, Matplotlib will automatically cycle through a set of default
colors for multiple lines.
Similarly, you can adjust the line style using the linestyle keyword.
Adjusting the Plot: Axes Limits
Adjust axis limits is to use the [Link]() and [Link]() methods
Reverse the chart
To be displayed in reverse, you can simply reverse the order of the arguments
Setting limit using [Link]()
The [Link]() method allows you to set the x and y limits with a single call, by
passing a list that specifies [xmin, xmax, ymin, ymax]
Tight
The [Link]() method tighten the bounds around the current plot.
Equal
It allows even higher-level specifications, such as ensuring an equal aspect ratio
so that on your screen, one unit in x is equal to one unit in y.
Aspect ratio is the ratio of height to width of the image we want to display
Labeling Plots
Titles and axis label
Methods for setting the title and axis label are
[Link]()
[Link]()
[Link]()
[Link]()
When multiple lines are being shown within a single axes, it can be useful to
create a plot legend that labels each line type.
Simple Scatter Plots
A scatter plot is a diagram where each value in the data set is represented by a
dot.
It represents data points on a two-dimensional plane
A scatter plot is a chart type that is normally used to observe and visually display
the relationship between variables. It is also known as a scattergram, scatter
graph, or scatter chart
Scatter Plots with [Link]
Markers
character codes can be used together with line and color codes to plot points
along with a line connecting them .
Marker
Properties of the lines and markers
Scatter Plots with [Link]
Creating a random scatter plot with points of many
colors and sizes.
Colorbars are a visualization of the mapping from scalar values to colors
Visualizing Errors
● Basic Error bars
● Continuous Errors
Basic Error bars
● Error bars function used as graphical enhancement that visualizes the
variability of the plotted data on a graph. Error bars can be applied to
graphs to provide an additional layer of detail on the presented data
● Error bars help you indicate estimated error or uncertainty to give a general
sense of how precise a measurement is this is done through the use of
markers drawn over the original graph and its data points
● To visualize this information error bars work by drawing lines that extend
from the center of the plotted data point or edge with bar charts the length of
an error bar helps to reveal uncertainty of a data point as shown in the below
graph.
● A short error bar shows that values are concentrated signaling that the plotted
averaged 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 tends
to be of equal length on both sides, however, if the data is skewed then the
lengths on each side would be unbalanced.
Continuous Errors
● Continuous error bands are a graphical representation of error or
uncertainty as a shaded region around a main trace, rather than as discrete
whisker-like error bars.
● [Link] and plt.fill_between
● The fill_between function: we pass an x value, then the lower y-bound, then
the upper y-bound, and the result is that the area between these regions is
filled.
Density and Contour Plots
● Sometimes it is useful to display three-dimensional data in two dimensions
using contours or color-coded regions.
● 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.
There are three Matplotlib functions
● [Link]() for contour plots,
● [Link]()for filled contour plots,
● [Link]() for showing images
Visualizing a Three-Dimensional Function
● A contour plot can be created with the [Link] function. It takes three
arguments: a grid of x values, a grid of y values, and a grid of z values.
● The x and y values represent positions on the plot, and the z values will be
represented by the contour levels.
[Link](X, Y, Z,20,cmap='RdGy')
[Link](X, Y, Z, 20, cmap='RdGy')
[Link]();
[Link]()
● The matplotlib function imshow() creates an image from a
2-dimensional numpy array.
● The image will have one square for each element of the array.
● The color of each square is determined by the value of the
corresponding array element and the color map used by imshow().
● The matplotlib “imshow()” method can be used for creating an
image from a 2-D numpy array.
● The generated image will contain one square for each element of
the array and each square color is determined by the value of the
provided array items by using the “imshow()” method
[Link]()
• [Link]() doesn’t accept an x and y grid, so you must manually specify the
extent [xmin, xmax, ymin, ymax] of the image on the plot.
• [Link]() by default follows the standard image array definition where the
origin is in the upper left, not in the lower left as in most contour plots. This must
be changed when showing gridded data.
• [Link]() will automatically adjust the axis aspect ratio to match the input
data; you can change this by setting, for example, [Link](aspect='image') to
make x and y units match.
Histograms, Binnings, and Density
The hist() function has many options to tune both the calculation and the display;
[Link](x, bins=None, range=None, density=False,
weights=None, cumulative=False, bottom=None, histtype='bar', align='mid',
orientation='vertical', rwidth=None, log=False, color=None, label=None,
stacked=False)
● X- Input values, this takes either a single array or a sequence of arrays
● bins-If bins is an integer, it defines the number of equal-width bins in the
range.
● range-The lower and upper range of the bins.
histtype{'bar', 'bar stacked', 'step', 'stepfilled'}, default: 'bar'
The type of histogram to draw.
● 'bar' is a traditional bar-type histogram. If multiple data are given the bars are
arranged side by side.
● 'bar stacked' is a bar-type histogram where multiple data are stacked on top of
each other.
● 'step' generates a line plot that is by default unfilled.
● 'stepfilled' generates a line plot that is by default filled.
align{'left', 'mid', 'right'}, default: 'mid'
The horizontal alignment of the histogram bars.
'left': bars are centered on the left bin edges.
'mid': bars are centered between the bin edges.
'right': bars are centered on the right bin edges.
orientation{'vertical', 'horizontal'}, default: 'vertical'
If 'horizontal', barh will be used for bar-type histograms and the bottom kwarg will
be the left edges.
Two-Dimensional Histograms and Binnings
Histograms in one dimension by dividing the number line into bins,we can also
create histograms in two dimensions by dividing points among two dimensional
bins.
plt.hist2d: Two-dimensional histogram
[Link]: Hexagonal binnings
Kernel density estimation
● Kernel density estimation is the process of estimating an unknown probability
density function using a kernel function.
● Evaluating densities in multiple dimensions is kernel density estimation (KDE)
Xj- kernel function
Xi-Observed Data points
h-Bandwidth(A low value of bandwidth estimates density with lot of variance
whereas high value of h produces large bias.)it should be optimal value
n-No of data points
Customizing Plot Legends
● Plot legend assigning labels to the various plot elements.
● [Link]() command, which automatically creates a legend for any labeled
plot elements
●
[Link](loc='upper left', frameon=False)
[Link](frameon=True, loc='lower center', ncol=2)
Choosing Elements for the Legend
Legend for Size of Points
Multiple Legends
To create a second legend using [Link]() or [Link](), it will simply override
the first one.
creating a new legend artist from scratch, and then using the lower-level
ax.add_artist() method to manually add the second artist to the plot.
Customizing Colorbars
[Link](I, cmap='gray');
Choosing the colormap
Classes of colormaps
● Sequential colormaps
These consist of one continuous sequence of colors (e.g., binary or viridis)
● Divergent colormaps
These usually contain two distinct colors, which show positive and negative
deviations from a mean (e.g., RdBu or PuOr).
● Qualitative colormaps
These mix colors with no particular sequence (e.g., rainbow or jet).
Color limits and extensions
Extend-Make pointed end(s) for out-of-range values
Discrete colorbars
● Colormaps are by default continuous, but sometimes you’d like to represent
discrete values.
● [Link].get_cmap() function, and pass the name of a suitable colormap along
with the number of desired bins.
Multiple Subplots
● Subplots groups of smaller axes that can exist together within a single figure.
● These subplots might be insets, grids of plots, or other more complicated
layouts
● [Link] also takes an optional argument that is a list of four numbers in the
figure coordinate system.
● These numbers represent [left,bottom, width, height] in the figure coordinate
system, which ranges from 0 at the bottom left of the figure to 1 at the top
right of the figure.
[Link]: Subplots by Hand
fig.add_axes()
[Link]: Simple Grids of Subplots
plt.subplots_adjust()
plt.subplots_adjust can be used to adjust the spacing
between these plots
[Link]: The Whole Grid in One Go
● Rather than creating a single subplot, this function creates a full grid of
subplots in a single line, returning them in a NumPy array.
● The arguments are the number of rows and number of columns, along with
optional keywords sharex and sharey, which allow you to specify the
relationships between different axes.
[Link]
The [Link]() object does not create a plot by itself it is simply a convenient
interface that is recognized by the [Link]() [Link]
[Link] class is used to specify the geometry of the grid to
place a subplot. For this, to work the number of rows and columns must be set.
Text and Annotation
● It is possible to add texts over matplotlib charts by using the text and figtext
functions.
● Adding a basic text
[Link](20, 0.5, 'Text') # Coordinates and text
● Position based on the axes
[Link](0.5, 0.5, 'Center', transform = [Link])
● Text alignment
[Link](20, 0.5, 'Text', verticalalignment = 'bottom',horizontalalignment = 'right')
Predefined Transforms
[Link]
Transform associated with data coordinates
[Link]
Transform associated with the axes (in units of axes dimensions)
[Link]
Transform associated with the figure (in units of figure dimensions)
Annotation
Annotations are similar to basic texts, but the annotate function provides further
parameters to annotate specific parts of the plot with arrows.