0% found this document useful (0 votes)
2 views19 pages

Python Chapter 7

Uploaded by

swathic850
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views19 pages

Python Chapter 7

Uploaded by

swathic850
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter-7

Data Visualization
INTRODUCTION

 Data visualiza on is concerned with the presenta on of data in a pictorial or graphical

form.

 It is one of the most important tasks in data analysis, since it enables us to see

analy cal results, detect outliers, and make decisions for model building.

 Popular Python libraries for data visualiza on


a) Matplotlib
b) Seaborn
c) Bokeh
d) ggplot
 Here we focus more on matplotlib

The matplotlib API primer

 The Matplotlib API, o en referred to as the MATLAB-like API, is one of the main interfaces
for crea ng visualiza ons in Python using the Matplotlib library.
 It provides a high-level, MATLAB-inspired approach to plo ng, making it easy for beginners
to create a wide range of plots.
 This interface centers around the pyplot module in Matplotlib, which offers a collec on of
func ons that make Matplotlib work like MATLAB.

Here’s an overview of some frequently used functions in the pyplot module:

Func on Descrip on
plot() Creates a line plot.
sca er() Creates a sca er plot.
bar() Creates a bar chart.
hist() Creates a histogram.
imshow() Displays image data.
xlabel() Sets the x-axis label.
ylabel() Sets the y-axis label.
tle() Sets the plot tle.
legend() Adds a legend to the plot.
grid() Adds a grid to the plot.
show() Displays the current figure.
How to install (in windows) and import:

In terminal:

In jupyter notebook

Import it:

Example program:

Output:
Line proper es:
Property Name Default Value Syntax Example Descrip on

color or c 'b' (blue) color='r' Sets the line color. Can use named colors ('r', 'g',
'blue'), hex codes, or RGB tuples.

linestyle or ls '-' (solid) linestyle='--' Sets the line style: '-' (solid), '--' (dashed), '-.'
(dash-dot), ':' (do ed).

linewidth or lw 1.5 linewidth=2 Sets the line width in points.

marker None marker='o' Sets the marker style: 'o' (circle), 's' (square), '^'
(triangle), etc.

markersize or ms 6 markersize=8 Sets the size of markers in points.

markerfacecolor or None (same as markerfacecolor='blue' Sets the fill color of markers.


mfc color)

markeredgecolor or None (same as markeredgecolor='k' Sets the edge color of markers.


mec color)

markeredgewidth or 1 markeredgewidth=2 Sets the width of the marker edge.


mew

alpha 1 (opaque) alpha=0.5 Sets the transparency level (0 is fully transparent,


1 is fully opaque).

label None label='My Line' Assigns a label to the line for use in the legend.

zorder 2 zorder=3 Sets the drawing order of the line (higher values
are drawn on top).

drawstyle 'default' drawstyle='steps-mid' Changes how lines are drawn: 'default', 'steps-
mid', 'steps-pre', etc.

Example program with default values:


Output:

Figures and sub-plots

 By default, all plo ng commands apply to the current figure and axes.
 In some situa ons, we want to visualize data in mul ple figures and axes to compare
different plots or to use the space on a page more efficiently.
 There are two steps required before we can plot the data:
(1) we have to define which figure we want to plot.
(2) we need to figure out the posi on of our subplot

Figures:
A Figure object is the overall container for all your plots. By default, [Link]() creates a figure.
However, you can explicitly create a figure using plt.figure(). Example:
Output:

Subplots:
Subplots are a way of organizing mul ple axes (plots) within a single figure.

Syntax:

 nrows: Number of rows of subplots.


 ncols: Number of columns of subplots.
 index: The posi on of the subplot (star ng from 1, le -to-right, top-to-bo om).

Example:
Output:

We can use [Link]() instead of [Link]()


Syntax:

Parameters:

Returns:

 fig: The figure object.


 ax: An array of axes objects (if you have more than one subplot, ax will be an array;
otherwise, it will be a single axes object).
We can also create the axes manually:
Syntax:

[Link]([le , bo om, width, height])

 le : The posi on of the le edge of the axes (rela ve to the figure's width, between 0 and 1).
 bo om: The posi on of the bo om edge of the axes (rela ve to the figure's height, between
0 and 1).
 width: The width of the axes (rela ve to the figure's width, between 0 and 1).
 height: The height of the axes (rela ve to the figure's height, between 0 and 1).

Example:

Output:
Exploring plot types:
Sca er plots:
A sca er plot is used to visualize the rela onship between variables measured in

the same dataset. It is easy to plot a simple sca er plot, using the [Link] er()

func on, that requires numeric columns for both the x and y axis:

syntax:

EXAMPLE:

OUTPUT:
Bar plot:

Parameters:
Example:

Histogram plots:
Parameters:

EXAMPLE:
OUTPUT:

Legends and annota ons

 Legends are an important element that is used to iden fy the plot elements in a

figure.

 The easiest way to show a legend inside a figure is to use the label argument

of the plot func on, and show the labels by calling the [Link]() method

syntax:

Parameters:
Example:

Output:

 If we want to split the legend into mul ple boxes in a figure, we can manually set it.
Output:
Annota ons in a plot can include text, arrows, or shapes to highlight specific parts of the figure or
emphasize important data points. Different methods are available for adding annota ons:

1) Text Method

The text method places text at specified coordinates on the plot, with op onal customiza on for
font-related proper es.

Syntax:

Parameters:

2) Annotate Method

The annotate method combines text and arrows for detailed labeling, allowing precise posi oning
and customiza on of annota ons.

Syntax:

Parameters:

 s: str
The annota on text.
 xy: tuple of floats
The (x, y) coordinates of the data point to annotate.
 xytext: tuple of floats, op onal
The (x, y) coordinates where the annota on text should be placed. If not specified, defaults
to xy.
 xycoords: str or Ar st coordinate system, op onal
Indicates the coordinate system for xy. Common values: 'data', 'axes frac on', 'figure
frac on'.
 arrowprops: dict, op onal
A dic onary defining proper es of the arrow, such as color, arrowstyle, linewidth. Example:
{'arrowstyle': '->', 'color': 'blue', 'lw': 1.5}.
 **kwargs: Addi onal text proper es like fontsize, color, rota on.

Example:

Output:
Plo ng func ons with Pandas

 Pandas offers a powerful method for directly crea ng standard visualiza ons from its data
objects, such as Series and DataFrame, which are commonly used for data manipula on.
 These data structures support a variety of plot types, including line plots, bar plots, box
plots, histograms, sca er plots, and pie charts.
 To select a specific plot type, you can use the kind argument in the plot() func on.
 If no plot type is specified, the plot() func on will default to genera ng a line plot. This
makes it easy to visualize data quickly and effec vely using Pandas.

Syntax:

Parameters:

1. kind: {‘line’, ‘bar’, ‘barh’, ‘hist’, ‘box’, ‘kde’, ‘density’, ‘area’, ‘pie’, ‘sca er’}

o Specifies the type of plot. Defaults to 'line'.

o Examples: 'bar', 'sca er', 'pie', etc.

2. ax: [Link], op onal

o If passed, it will use the specified axes to plot the data.

3. subplots: bool, default False

o If True, each column in the DataFrame will be plo ed as a separate subplot.

4. sharex: bool, default False

o If True, the x-axis will be shared among subplots.

5. sharey: bool, default False

o If True, the y-axis will be shared among subplots.

6. layout: tuple, default None

o Specifies the layout of subplots (rows, columns).

7. figsize: tuple of (width, height), op onal

o The size of the plot in inches.

8. use_index: bool, default True

o If True, it will use the index for plo ng. If False, it will ignore the index and use the
range of numbers.

9. kwds: other keyword arguments


o Addi onal arguments that are passed to the matplotlib plo ng func on. Examples
include color, label, linewidth, etc.

Example:

Output:
Output:

You might also like