[Go to site: main page, start]

0% found this document useful (0 votes)
17 views22 pages

Data Visualization with Matplotlib

The document provides an overview of data visualization using the Matplotlib library in Python, detailing various types of plots such as line charts, bar charts, histograms, scatter plots, pie charts, box plots, and heatmaps. It also covers customization techniques for enhancing visualizations and explains the core components of Matplotlib, including the Figure and Axes classes. Additionally, it discusses advanced techniques for creating subplots and managing multiple graphs within a single figure.

Uploaded by

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

Data Visualization with Matplotlib

The document provides an overview of data visualization using the Matplotlib library in Python, detailing various types of plots such as line charts, bar charts, histograms, scatter plots, pie charts, box plots, and heatmaps. It also covers customization techniques for enhancing visualizations and explains the core components of Matplotlib, including the Figure and Axes classes. Additionally, it discusses advanced techniques for creating subplots and managing multiple graphs within a single figure.

Uploaded by

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

Data Visualization using Matplotlib in Python

Matplotlib is a widely-used Python library used for creating static,


animated and interactive data visualizations. It is built on the top
of NumPy and it can easily handles large datasets for creating
various types of plots such as line charts, bar charts, scatter plots,
etc.

Visualizing Data with Pyplot using


Matplotlib
Pyplot is a module in Matplotlib that provides a simple interface
for creating plots. It allows users to generate charts like line
graphs, bar charts and histograms with minimal code. Let’s
explore some examples with simple code to understand how to
use it effectively.
1. Line Chart
Line chart is one of the basic plots and can be created
using plot() function. It is used to represent a relationship
between two data X and Y on a different axis.
Syntax:
[Link](x, y)
Parameter: x, y Coordinates for data points.
Example: This code plots a simple line chart with labeled axes
and a title using Matplotlib.
import [Link] as plt

x = [10, 20, 30, 40]


y = [20, 25, 35, 55]

[Link](x, y)
[Link]("Line Chart")
[Link]('Y-Axis')
[Link]('X-Axis')
[Link]()
Output

2. Bar Chart
Bar chart displays categorical data using rectangular bars whose
lengths are proportional to the values they represent. It can be
plotted vertically or horizontally to compare different categories.
Syntax:
[Link](x, height)
Parameter:
 x: Categories or positions on x-axis.
 height: Heights of the bars (y-axis values).
Example: This code creates a simple bar chart to show total bills
for different days. X-axis represents the days and Y-axis shows
total bill amount.
import [Link] as plt

x = ['Thur', 'Fri', 'Sat', 'Sun']


y = [170, 120, 250, 190]

[Link](x, y)
[Link]("Bar Chart")
[Link]("Day")
[Link]("Total Bill")
[Link]()
Output

3. Histogram
Histogram shows the distribution of data by grouping values into
bins. The hist() function is used to create it, with X-axis showing
bins and Y-axis showing frequencies.
Syntax:
[Link](x, bins=None)
Parameter:
 x: Input data.
 bins: Number of bins (intervals) to group data.
Example: This code plots a histogram to show frequency
distribution of total bill values from the list x. It uses 10 bins and
adds axis labels and a title for clarity.
import [Link] as plt

x = [7, 8, 9, 10, 10, 12, 12, 12, 13, 14, 14, 15, 16, 16, 17, 18,
18, 19, 20, 20,
21, 22, 23, 24, 25, 25, 26, 28, 30, 32, 35, 36, 38, 40, 42, 44,
48, 50]

[Link](x, bins=10, color='steelblue')


[Link]("Histogram")
[Link]("Total Bill")
[Link]("Frequency")
[Link]()
Output
4. Scatter Plot
Scatter plots are used to observe relationships between variables.
The scatter() method in the matplotlib library is used to draw a
scatter plot.
Syntax:
[Link](x, y)
Parameter: x, y Coordinates of the points.
Example: This code creates a scatter plot to visualize the
relationship between days and total bill amounts using scatter().
import [Link] as plt

x = ['Thur', 'Fri', 'Sat', 'Sun', 'Thur', 'Fri', 'Sat', 'Sun']


y = [170, 120, 250, 190, 160, 130, 240, 200]

[Link](x, y)
[Link]("Scatter Plot")
[Link]("Day")
[Link]("Total Bill")
[Link]()
Output

5. Pie Chart
Pie chart is a circular chart used to show data as proportions or
percentages. It is created using the pie(), where each slice
(wedge) represents a part of the whole.
Syntax:
[Link](x, labels=None, autopct=None)
Parameter:
 x: Data values for pie slices.
 labels: Names for each slice.
 autopct: Format to display percentage (e.g., '%1.1f%%').
Example: This code creates a simple pie chart to visualize
distribution of different car brands. Each slice of pie represents
the proportion of cars for each brand in the dataset.
import [Link] as plt
import pandas as pd

cars = ['AUDI', 'BMW', 'FORD','TESLA', 'JAGUAR',]


data = [23, 10, 35, 15, 12]

[Link](data, labels=cars)
[Link](" Pie Chart")
[Link]()
Output
Pie
Chart
6. Box Plot
Box plot is a simple graph that shows how data is spread out. It
displays the minimum, maximum, median and quartiles and also
helps to spot outliers easily.
Syntax:
[Link](x, notch=False, vert=True)
Parameter:
 x: Data for which box plot is to be drawn (usually a list or
array).
 notch: If True, draws a notch to show the confidence
interval around the median.
 vert: If True, boxes are vertical. If False, they are
horizontal.
Example: This code creates a box plot to show the data
distribution and compare three groups using matplotlib
import [Link] as plt
data = [ [10, 12, 14, 15, 18, 20, 22],
[8, 9, 11, 13, 17, 19, 21],
[14, 16, 18, 20, 23, 25, 27] ]

[Link](data)
[Link]("Groups")
[Link]("Values")
[Link]("Box Plot")
[Link]()
Output

7. Heatmap
Heatmap is a graphical representation of data where values are
shown as colors. It helps visualize patterns, correlations or
intensity in a matrix-like format. It is created
using imshow() method in Matplotlib.
Syntax:
[Link](X, cmap='viridis')
Parameter:
 X: 2D array (data to display as an image or heatmap).
 cmap: Sets the color map.
Example: This code creates a heatmap of random 10×10 data
using imshow(). It uses 'viridis' color map and colorbar() adds
a color scale.
import [Link] as plt
import numpy as np

[Link](0)
data = [Link](10, 10)

[Link](data, cmap='viridis', interpolation='nearest')

[Link]()
[Link]('X-axis Label')
[Link]('Y-axis Label')
[Link]('Heatmap')
[Link]()
Output

Heatmap
Explanation:
 [Link](0): Ensures same random values every
time (reproducibility).
 [Link](10, 10): Generates a 10×10 array of
random numbers between 0 and 1.
How to Customize Matplotlib Visualizations?
Customization in Matplotlib allows you to improve look and clarity
of plots by adjusting elements like colors, styles, labels, titles and
gridlines. It helps make visualizations more informative and
visually appealing for better data communication. Let’s explore
different ways to customize visualizations:
1. Customizing Line Chart
Line charts can be customized using various properties:
1. Color: Change the color of the line
2. Linewidth: Adjust the width of the line
3. Marker: Change the style of plotted points
4. Markersize: Change the size of the markers
5. Linestyle: Define the style of the line like solid, dashed,
etc.
Example: This code creates a customized line chart with a green
dashed line, thicker width, large circular markers and labeled
axes and title.
import [Link] as plt

x = [10, 20, 30, 40]


y = [20, 25, 35, 55]

[Link](x, y, color='green', linewidth=3, marker='o', markersize=15,


linestyle='--')

[Link]("Customizing Line Chart")


[Link]('Y-Axis')
[Link]('X-Axis')
[Link]()
Output
Customizing Line Chart
2. Customizing Bar Chart
Bar charts can be made more informative and visually appealing
by customizing:
 Color: Fill color of the bars
 Edgecolor: Color of the bar edges
 Linewidth: Thickness of the edges
 Width: Width of each bar
Example: This code creates a customized bar chart with green
bars, blue edges, thicker border lines and labeled axes and title.
import [Link] as plt

x = ['Thur', 'Fri', 'Sat', 'Sun']


y = [170, 120, 250, 190]

[Link](x, y, color='green', edgecolor='black', linewidth=2)

[Link]("Customizing Bar Chart")


[Link]("Day")
[Link]("Total Bill")
[Link]()
Output
Customizing Bar plot
3. Customizing Histogram Plot
To make histogram plots more effective various customizations
can be applied:
 Bins: Number of groups (bins) to divide data into
 Color: Bar fill color
 Edgecolor: Bar edge color
 Linestyle: Style of the edges like solid, dashed, etc.
 Alpha: Transparency level (0 = transparent, 1 = opaque)
Example: This code creates a customized histogram with green
bars, blue edges, dashed border lines, semi-transparent fill and
labeled axes and title.
import [Link] as plt

x = [7, 8, 9, 10, 10, 12, 12, 12, 13, 14, 14, 15, 16, 16, 17,
18, 18, 19, 20, 20, 21, 22, 23, 24, 25, 25, 26, 28, 30,
32, 35, 36, 38, 40, 42, 44, 48, 50]

[Link](x, bins=10, color='green', edgecolor='blue',linestyle='--',


alpha=0.5)

[Link]("Customizing Histogram Plot")


[Link]("Total Bill")
[Link]("Frequency")
[Link]()
Output

Customizing Histogram
4. Customizing Scatter Plot
Scatter plots can be enhanced with:
 S: Marker size (single value or array)
 C: Color of markers or sequence of colors
 Marker: Marker style like circle, diamond, etc.
 Linewidths: Width of marker borders
 Edgecolor: Color of marker borders
 Alpha: Blending value, between 0 (transparent) and 1
(opaque)
Example: This code creates a customized scatter plot using
diamond-shaped markers, where color represents size, marker
size reflects the total bill and transparency is added for better
visualization. It includes labeled axes and a title.
import [Link] as plt

x = ['Thur', 'Fri', 'Sat', 'Sun', 'Thur', 'Fri', 'Sat', 'Sun']


y = [170, 120, 250, 190, 180, 130, 260, 200]
size = [2, 3, 4, 2, 3, 2, 4, 3]
bill = [170, 120, 250, 190, 180, 130, 260, 200]

[Link](x, y, c=size, s=bill, marker='D', alpha=0.5)


[Link]("Customizing Scatter Plot")
[Link]("Day")
[Link]("Total Bill")
[Link]()
Output

Customizing Scatter Plot


5. Customizing Pie Chart
To make pie charts more effective and visually appealing use:
 Explode: Moving the wedges of the plot
 Autopct: Label the wedge with their numerical value.
 Color: Colors of the slices
 Sadow: Used to create a shadow effect
Example: This code creates a customized pie chart with colored
slices, exploded segments for emphasis, percentage labels with
two decimal places and a shadow effect for better visual appeal.
import [Link] as plt
import pandas as pd

cars = ['AUDI', 'BMW', 'FORD','TESLA', 'JAGUAR',]


data = [23, 13, 35, 15, 12]
explode = [0.1, 0.5, 0, 0, 0]
colors = ( "orange", "cyan", "yellow","grey", "green",)
[Link](data, labels=cars, explode=explode, autopct='%1.2f%
%',colors=colors, shadow=True)
[Link]()
Output

Matplotlib’s Core Components: Figures and


Axes
Before we proceed let’s understand two classes which are
important for working with Matplotlib.
1. Figure class
The Figure class represents the full drawing area or canvas that
can hold one or more plots. It is created using
the figure() function and lets user control the overall size, layout
and background of the plot window.
Syntax:
[Link](figsize=None, facecolor=None)
Parameter:
 figsize: Sets size of the figure (width, height) in inches.
 facecolor: Sets background color of the figure.
Example:
This code demonstrates how to use Figure class to create a
simple line plot. It sets figure size and background color, adds
custom axes, plots data and labels the axes and title.
import [Link] as plt

# Create a Figure with basic size and background color


fig = [Link](figsize=(6, 4), facecolor='lightblue')

# Add Axes to the Figure


ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
x = [1, 2, 3, 4]
y = [10, 20, 15, 25]
[Link](x, y)

[Link]("Simple Line Plot")


[Link]("X-Axis")
[Link]("Y-Axis")
[Link]()
Output

Figure class Representation


Explanation:
 fig.add_axes() adds an Axes object to the figure.
 [0.1, 0.1, 0.8, 0.8] defines the position left, bottom,
width and height as a fraction of figure size.
2. Axes Class
Axes class represents actual plotting area where data is drawn. It
is the most basic and flexible for creating plots or subplots within
a figure. A single figure can contain multiple axes but each Axes
object belongs to only one figure. It can create an Axes object
using axes() function.
Syntax:
axes([left, bottom, width, height])
Example:
This code creates a figure using Figure class and adds a custom
axes area to it. It then plots two line graphs one for x vs y and
another for y vs x. The graph includes axis labels, a title and a
legend for better clarity and presentation.
import [Link] as plt
from [Link] import Figure

x = [10, 20, 30, 40]


y = [20, 25, 35, 55]

fig = [Link](figsize=(5, 4))


ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])

[Link](x, y)
[Link](y, x)

ax.set_title("Linear Graph")
ax.set_xlabel("X-Axis")
ax.set_ylabel("Y-Axis")
[Link](labels=('line 1', 'line 2'))
[Link]()
Output

Advanced Techniques for Visualizing


Subplots
We have learned how to add basic parts to a graph to show more
information. One method can be by calling the plot function again
and again with a different set of values as shown in the above
example. Now let’s see how to draw multiple graphs in one figure
using some Matplotlib functions and how to create subplots.
1. Using add_axes()
add_axes() method allows us to manually add axes to a figure in
Matplotlib. It takes a list of four values [left, bottom, width,
height] to specify the position and size of the axes.
Example:
This code creates two side-by-side plots using add_axes() one for
x vs y and another for y vs x all in a single figure.
import [Link] as plt
from [Link] import Figure

x = [10, 20, 30, 40]


y = [20, 25, 35, 55]

fig = [Link](figsize=(10, 4))


ax1 = fig.add_axes([0.1, 0.1, 0.35, 0.8])
ax2 = fig.add_axes([0.55, 0.1, 0.35, 0.8])

[Link](x, y)
[Link](y, x)
[Link]()
Output

2. Using subplot()
The subplot() method adds a plot to a specified grid position
within the current figure. It takes three arguments: the number
of rows, columns and plot index.
Example:
This code uses subplot() to create two plots side by side one for
x vs y and the other for y vs x within same figure.
import [Link] as plt
x = [10, 20, 30, 40]
y = [20, 25, 35, 55]
[Link]()

[Link](121)
[Link](x, y)

[Link](122)
[Link](y, x)
[Link]()
Output

3. Using subplot2grid()
The subplot2grid() creates axes object at a specified location
inside a grid and also helps in spanning the axes object across
multiple rows or columns.
Example:
This code uses subplot2grid() to place two stacked plots in a
single figure one on top of the other by defining their positions in
a 7-row grid layout.
import [Link] as plt

x = [10, 20, 30, 40]


y = [20, 25, 35, 55]

axes1 = plt.subplot2grid (
(7, 1), (0, 0), rowspan = 2, colspan = 1)

axes2 = plt.subplot2grid (
(7, 1), (2, 0), rowspan = 2, colspan = 1)
[Link](x, y)
[Link](y, x)
[Link]()
Output

Saving Plots Using savefig()


When plots are created using Matplotlib, users may want to save
them as image files for use in reports, presentations or sharing.
Matplotlib offers savefig() function to save the current plot to a
file. By changing file extension, users can store the plot in
different formats such as .png, .jpg, .pdf or .svg.
Example:
import [Link] as plt

year = ['2010', '2002', '2004', '2006', '2008']


production = [25, 15, 35, 30, 10]

[Link](year, production)

[Link]("[Link]")
[Link]("output1", facecolor='y',
bbox_inches="tight",pad_inches=0.3, transparent=True)
Output

You might also like