0% found this document useful (0 votes)
5 views55 pages

Data Visualization Techniques with Matplotlib

Chapter 3 focuses on data visualization using Matplotlib in Python, covering various types of plots such as line plots, bar charts, scatter plots, box plots, and density plots. It provides practical examples and code snippets for creating these visualizations, as well as tips for customizing plots and visualizing errors. The chapter emphasizes the importance of visual representation in understanding complex data relationships.

Uploaded by

Leonard Victoria
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)
5 views55 pages

Data Visualization Techniques with Matplotlib

Chapter 3 focuses on data visualization using Matplotlib in Python, covering various types of plots such as line plots, bar charts, scatter plots, box plots, and density plots. It provides practical examples and code snippets for creating these visualizations, as well as tips for customizing plots and visualizing errors. The chapter emphasizes the importance of visual representation in understanding complex data relationships.

Uploaded by

Leonard Victoria
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 3:

Data Visualization

1
Data visualization
● The representation of data through use of common graphics, such as charts, plots,
infographics, and even animations.
● These visual displays of information communicate complex data relationships and
data-driven insights in a way that is easy to understand.

2
Outlines
● General Matplotlib Tips
● Simple Line Plots
● Simple Scatter Plots
● Box plot
● Visualizing Errors
● Density and Contour Plots
● Histograms, Binnings, and Density

3
General Matplotlib Tips

4
General Matplotlib Tips
● A fundamental part of the data scientist’s toolkit is data visualization.
● Matplotlib tool for visualization in Python
● Importing matplotlib
import [Link] as plt

[Link]

5
General Matplotlib Tips
show() or No show()? How to Display Your Plots
How you view your Matplotlib plots depends on the context

Plotting from a script


# ------- file: [Link] ------
import [Link] as plt
import numpy as np
x = [Link](0, 10, 100)
[Link](x, [Link](x))
[Link](x, [Link](x))
[Link]()

6
General Matplotlib Tips
show() or No show()? How to Display Your Plots
How you view your Matplotlib plots depends on the context

Plotting from an IPython notebook


# ------- file: [Link] ------
%matplotlib inline
import numpy as np
x = [Link](0, 10, 100)
fig = [Link]()
[Link](x, [Link](x), '-')
[Link](x, [Link](x), '--');

7
Simple Line Plots

Line charts are a good choice for showing trend.

8
Simple Line Plots
Creating a simple plot of a single function y = f(x)

import matplotlib .pyplot as plt


import numpy as np
fig = [Link]()
x = [Link](0, 10, 1000)
[Link](x, [Link](x))
[Link]()

9
Simple Line Plots
Adjusting the Plot: Line Colors and Styles

import numpy as np
import matplotlib .pyplot as plt
fig = [Link]()
x = [Link](0, 10, 1000)
[Link](x, [Link](x),
color="red", linestyle='solid')
[Link](x, [Link](x),
color="blue", linestyle='dashed')
[Link]()

10
Simple Line Plots
Adjusting the Plot: Axes Limits

import numpy as np
import [Link] as plt
fig = [Link]()
x = [Link](0, 10, 1000)
[Link](x, [Link](x),
color="red", linestyle='solid')
[Link](x, [Link](x),
color="blue", linestyle='dashed')
[Link](0, 15)
[Link](-1, 1)
[Link]()

11
Simple Line Plots
Labeling Plots

import numpy as np
import [Link] as plt
fig = [Link]()
x = [Link](0, 10, 1000)
[Link](x, [Link](x), '-g',
label='sin(x)')
[Link](x, [Link](x), ':b',
label='cos(x)')
[Link]("A Sine Cosine Curve")
[Link]("x")
[Link]("y")
[Link]()
[Link]()
12
Bar Charts

A bar chart is a good choice when you want to show how some quantity varies among
some discrete set of items.

13
Bar Charts

14
Bar Charts
import matplotlib .pyplot as plt
movies = ["Annie Hall" , "Ben-Hur", "Casablanca" , "Gandhi", "West Side
Story"]
num_oscars = [5, 11, 3, 8, 10]
[Link](movies, num_oscars )
[Link]("# of Academy Awards" )
[Link]("My Favorite Movies" )
[Link]()

15
Bar Charts - Iris dataset sklearn

16
Bar Charts - Iris dataset sklearn
import [Link] as plt # Plot bar chart
from [Link] import [Link](figsize=(6, 4))
load_iris [Link](target_names , counts,
import numpy as np color=['lightcoral' ,
'lightyellow' , 'lightblue' ])
# Load Iris dataset
[Link]("Iris Species" )
iris = load_iris()
[Link]("Number of Samples" )
y = [Link]
[Link]("Bar Chart of Iris
target_names = iris.target_names
Species Counts" )

# Count samples per species # [Link](axis='y', alpha=0.7)

counts = [Link](y) [Link]()

17
Simple Scatter Plots

A scatterplot is the right choice for visualizing the relationship


between two variables, detecting trends, clusters, or outliers.

18
Scatter Plots
● The x-axis represents the independent variable.
● The y-axis represents the dependent variable.
● Each point on the chart corresponds to a pair of values (x,y)

19
Scatter Plots with [Link]
import matplotlib .pyplot as plt
import numpy as np

x = [Link](0, 10, 30)


y = [Link](x)
[Link](x, y, 'o', color='black')
[Link]()

20
Scatter Plots with [Link]
import matplotlib .pyplot as plt
import numpy as np

x = [Link](0, 10, 30)


y = [Link](x)
[Link](x, y, marker='o')
[Link]()

21
Scatter Plots with [Link]
import matplotlib .pyplot as plt
from [Link] import load_iris
Explore 4 dimensions of the Iris data:
● (x, y) corresponds to the sepal length and width,
# Load Iris dataset
iris = load_iris () ● the color is related to the particular species of flower.
X = [Link][:, : 2] # only sepal length and sepal width
y = [Link]
target_names = iris.target_names
[Link]("Sepal length (cm)" )

# Create scatter plot [Link]("Sepal width (cm)" )

[Link](figsize=(7, 5)) [Link]("Scatter Plot of Iris Sepal Length vs

for i, target_name in enumerate (target_names ): Width")

[Link]( [Link]()

X[y == i, 0], # sepal length [Link](True)

X[y == i, 1], # sepal width [Link]()

label=target_name ,
alpha=0.7 22
)
Scatter Plots with [Link]
Sepal length + width is
enough to perfectly separate
Setosa from the other two.

However, Versicolor and


Virginica overlap heavily →
these two species cannot be
separated well using only
sepal dimensions.

23
Scatter Plots with [Link]

24
Box Plot

Box Plot displays distribution of a dataset

25
Box Plot
A typical boxplot comes with several components:
● Median (Q2): the line inside the box
● Quartiles (Q1 & Q3): the edges of the box
● Interquartile Range (IQR = Q3 − Q1):
box height/width
● Whiskers → data within 1.5 × IQR
● Outliers → points beyond the whiskers

26
27
Box Plot
import [Link] as plt # Replace numeric target with species name
from [Link] import load_iris [Link]([1, 2, 3], iris.target_names)
import pandas as pd
[Link]("Iris Species")
# Load Iris dataset into a DataFrame [Link]("Sepal Length (cm)")
iris = load_iris(as_frame=True) [Link]("Box Plot of Sepal Length by Iri
df = [Link] # pandas DataFrame Species")
[Link]()
# Create box plot for Sepal Length by Species
[Link](figsize=(7, 5))
[Link](column="sepal length (cm)",
by="target", grid=False)

28
Visualizing Errors

29
Error bars
● Error bars show the uncertainty or variability in data.
● Commonly represent standard deviation, standard error, or confidence intervals.
● They are small vertical/horizontal lines extending from a plotted data point.

30
Basic Error bars

import [Link] as plt


import numpy as np
x = [Link](0, 10, 50)
y = [Link](x)
errors = [Link](0.05, 0.2, 50)
[Link](x, y, yerr=error, fmt='o',
capsize=5, ecolor='red')
[Link]("X-axis")
[Link]("Y-axis")
[Link]("Error Visualization")
[Link](True, linestyle="--", alpha=0.6)
[Link]() 31
Basic Error bars
Instead of separate error bars, we use a
shaded region (as confidence interval) that
covers all x-values.

32
Basic Error bars
import [Link] as plt # Fill between lower and upper

import numpy as np (continuous error)


plt.fill_between(x, y_lower, y_upper,
color="blue", alpha=0.2,
x = [Link](0, 10, 50)
label="Uncertainty")
y = [Link](x)
error = [Link](0.05, 0.2, 50)
[Link]("X-axis")
[Link]("Y-axis")
# Upper and lower bounds
[Link]("Error Visualization")
y_upper = y + error [Link]()
y_lower = y - error [Link](True, linestyle="--",
alpha=0.6)
# Plot mean line [Link]()
[Link](x, y, label="Prediction",
33
color="blue")
Density and Contour Plots

Display three-dimensional data in two dimensions using contours or color-coded regions

34
Density Plot
● Shows the probability density of data in 2D.
● Darker (or more intense) regions = higher concentration of points.

35
Density Plot
import [Link] as plt # Density plot (2D KDE)
import seaborn as sns [Link](figsize=(7, 5))

from [Link] import load_iris [Link](

import pandas as pd data=df, x="petal length (cm)",


y="petal width (cm)",
fill=True, cmap="Blues",
# Load Iris dataset into a DataFrame
thresh=0.05, levels=20
iris = load_iris(as_frame=True)
)
df = [Link]

[Link]("2D Density Plot of Iris


Petal Length vs Width")
[Link]("Petal length (cm)")
[Link]("Petal width (cm)")
[Link]()
36
Contour Plot
● Similar to a density plot but uses contour lines instead of filled colors.
● Each contour line connects points of equal density (or value).

[Link](data=df, x="petal length (cm)",


y="petal width (cm)",
levels=10, color="blue" # contour lines
)

37
Histograms, Binnings, and Density

38
Histograms
● A histogram divides the data into intervals (bins) and counts how many observations
fall into each bin.
● X-axis: the value ranges (bins).
● Y-axis: the count (frequency) or probability.

39
Histograms
import [Link] as plt
from [Link] import load_iris

iris = load_iris()
X = [Link][:, 2] # petal length

[Link](X, bins=20, color="skyblue", edgecolor="black")


[Link]("Petal Length (cm)")
[Link]("Frequency")
[Link]("Histogram of Iris Petal Length")
[Link]()

40
Binning
● Binning is the process of splitting continuous data into discrete intervals (bins).
● A histogram is essentially a visualization of binning.
● The number of bins affects the visualization:
○ Too few bins → oversimplified, loss of detail.
○ Too many bins → too noisy, hard to see the trend.

41
Density
● Density is a smoothed version of a histogram.
● Instead of counting frequencies per bin, density estimates a continuous probability
density function.

42
Density
import [Link] as plt
import seaborn as sns
import pandas as pd
from [Link] import load_iris

iris = load_iris()
df = [Link]([Link], columns=iris.feature_names)

[Link](df["petal length (cm)"], fill=True, color="skyblue")


[Link]("Petal Length (cm)")
[Link]("Density")
[Link]("Density Plot of Iris Petal Length")
[Link]()
43
Multiple Subplots

44
Multiple Subplots
● It is helpful to compare different views of data side by side.
● [Link](), which creates a single subplot within a grid

import numpy as np
import [Link] as plt
for i in range(1, 7):
[Link](2, 3, i)
[Link](0.5, 0.5, str((2, 3, i)),
fontsize=18, ha='center')
[Link]()

45
Multiple Subplots

46
Multiple Subplots
import [Link] as plt
from [Link] import load_iris # Loop through features and draw
histogram
# Load Iris dataset for i, feature in enumerate(features):
iris = load_iris(as_frame=True) print(i)
df = [Link] axes[i].hist(df[feature], bins=20,
features = [Link][:4] # 4 features color="skyblue", edgecolor="black")
print(features) axes[i].set_title(feature)
axes[i].set_xlabel("Value")
# Create a 2x2 grid of subplots axes[i].set_ylabel("Frequency")
fig, axes = [Link](2, 2,
figsize=(10, 8)) plt.tight_layout()
axes = [Link]() # flatten 2D array [Link]()
of axes to 1D for easy iteration

47
Text and Annotation

48
Text and Annotation
● [Link](x, y, "label") → writes text directly at coordinates (x, y)
● [Link]("text", xy=(..), xytext=(..), arrowprops=...) → adds text with an arrow
pointing to a chosen data point.

49
Text and Annotation
import [Link] as plt # Add simple text near a point
[Link](3, 6, "This is (3,6)", fontsize=10,
# Sample data color="red")
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10] # Add annotation with an arrow pointing to the
highest point
[Link](figsize=(7,5)) [Link]("Highest Point",

[Link](x, y, color="blue") xy=(1, 2), xycoords="data", #


arrow points to this point
xytext=(2, 2.5), textcoords="data",
# Add title and axis labels
# text placed here
[Link]("Text and Annotation in
arrowprops=dict(arrowstyle="->",
Pyplot")
color="green"),
[Link]("X values") fontsize=10, color="green")
[Link]("Y values")
50
[Link]()
51
Three-dimensional plotting

52
Three-dimensional plotting
Three-Dimensional Points and Lines
import numpy as np
import [Link] as plt
fig = [Link]()
ax = [Link](projection='3d')

zline = [Link](0, 15, 1000)


xline = [Link](zline)
yline = [Link](zline)
ax.plot3D(xline, yline, zline, 'gray')
xdata = [Link](zline) + 0.1 * [Link](1000)
ydata = [Link](zline) + 0.1 * [Link](1000)
ax.scatter3D(xdata, ydata, zline, c=zline)
[Link]() 53
Three-dimensional plotting

54
Three-dimensional plotting
# Plot each species in different colors
from [Link] import load_iris
colors = ['red', 'green', 'blue']
import [Link] as plt for target, color in zip(range(3), colors):
ax.scatter3D( X[y==target, 2], # Petal length
# Load iris dataset X[y==target, 3], # Petal width
iris = load_iris() X[y==target, 0], # Sepal length
X = [Link] label=target_names [target], c=color)

y = [Link]
target_names = iris.target_names # Axis labels
ax.set_xlabel ("Petal length (cm)" )
ax.set_ylabel ("Petal width (cm)" )
# Create 3D scatter plot
ax.set_zlabel( "Sepal length (cm)" )
fig = [Link](figsize=(8,6))
ax.set_title ("3D Scatter Plot of Iris Dataset (Petal +
ax = [Link](projection='3d')
Sepal)")

[Link]()
55
[Link]()

You might also like