PRIMER ON ARTIFICIAL INTELLIGENCE
4. Data Visualization
Learning Objectives:
By the end of this module, students should be able to:
• Create and customize statistical graphs using Matplotlib, Seaborn, and Excel.
• Clean datasets by handling missing values and outliers in Python and Excel.
• Select appropriate graph types based on data characteristics and analytical goals.
• Visualize multi-dimensional data using pair plots, heatmaps, and parallel coordinates.
• Critically evaluate visualization effectiveness (e.g., misleading pie charts).
4.1 Data Visualization using Python Programming
Data visualization is the graphical representation of data to help people understand trends, patterns,
and insights in a dataset. In Python, data visualization is primarily done using libraries such as
Matplotlib and Seaborn. Matplotlib is a foundational plotting library, offering flexibility to create a
wide variety of graphs, while Seaborn builds on Matplotlib with more advanced features and better
aesthetics. These libraries allow you to create line plots, bar charts, histograms, scatter plots, and
more, making it easier to analyze and present data effectively.
Python’s visualization tools integrate seamlessly with Pandas Data Frames, making it simple to
visualize data directly from your data analysis workflows. For example, you can quickly plot a
column from a Data Frame using a single line of code. Seaborn also comes with built-in datasets for
practice, making it ideal for beginners to learn and experiment.
import [Link] as plt
import seaborn as sns
import pandas as pd
# Sample data
data = {'Year': [2020, 2021, 2022],
'Sales': [100, 150, 200]}
df = [Link](data)
# Line plot using Matplotlib
[Link](df['Year'], df['Sales'])
[Link]('Year')
[Link]('Sales')
[Link]('Sales Over Years')
[Link]()
# Bar plot using Seaborn
[Link](x='Year', y='Sales',
data=df) Figure 39: Sales Over Years
[Link]('Sales by Year')
[Link]()
54
PRIMER ON ARTIFICIAL INTELLIGENCE
4.1.1 Using Matplotlib and Seaborn in Python and Excel Charts
Matplotlib is the most widely used Python library for creating static, animated, and interactive
visualizations. It provides a comprehensive set of plotting functions, allowing users to create almost
any type of chart.
Seaborn, built on top of Matplotlib, simplifies the creation of attractive statistical graphics and offers
high-level functions for complex visualizations with minimal code.
To use Matplotlib, you typically import it as import [Link] as plt. For Seaborn, you
use import seaborn as sns. Both libraries can visualize data directly from Pandas DataFrames, making
them ideal for data analysis tasks.
import [Link] as plt
import seaborn as sns
import pandas as pd
# Sample data
df = [Link]({'Category': ['A', 'B', 'C'], 'Values':
[10, 20, 15]})
# Bar chart with Matplotlib
[Link](df['Category'], df['Values'])
[Link]('Bar Chart with Matplotlib')
[Link]()
# Bar chart with Seaborn
[Link](x='Category', y='Values', data=df)
[Link]('Bar Chart with Seaborn')
[Link]()
Figure 40: Bar Chart with Matplotlib and Seaborn
55
PRIMER ON ARTIFICIAL INTELLIGENCE
Microsoft Excel provides a comprehensive
suite of data visualization tools that
transform raw numbers into meaningful
visual insights. Excel's chart creation
process begins with selecting your data
range and navigating to the Insert tab,
where you'll find various chart options,
including column charts, line graphs, pie
charts, bar charts, and more sophisticated
visualizations, such as pivot charts. The
software automatically detects data patterns
and suggests appropriate chart types
through the Recommended
Charts feature, which analyzes your
dataset and proposes the most suitable Figure 41: Microsoft Excel worksheet showing
visualization methods. Excel's strength lies examples of column chart, pie chart, and line chart
in its user-friendly interface, which allows visualizations using company and revenue data
students to create professional-looking
charts with just a few clicks, while still providing advanced customization options for those who need
them. The Chart Tools section appears automatically when you select a chart, offering design and
formatting tabs that enable extensive customization of colours, styles, labels, and layout options.
Excel supports multiple chart categories, each serving specific analytical purposes:
Column Charts excel at comparing
categorical data across different groups, Line
Charts effectively show trends and changes
over time, Pie Charts illustrate proportions
and percentages within a whole, and Bar
Charts work well when category labels are
lengthy. Advanced visualization techniques
include Pivot Charts, which combine the
analytical power of PivotTables with visual
representation, allowing students to create
interactive dashboards that can be filtered and
manipulated in real-time. Conditional
Formatting serves as another powerful
visualization tool, using colours, data bars, and
icon sets to highlight patterns, trends, and
outliers directly within the spreadsheet cells.
Excel's Sparklines feature creates miniature
charts within individual cells, providing quick
visual summaries of data trends without taking Figure 42: Excel Chart Types Comparison
up significant screen space.
56
PRIMER ON ARTIFICIAL INTELLIGENCE
4.1.2 Handling Missing Values, Outliers, and Inconsistencies in Data
Data cleaning is a crucial step before visualization. Missing values, outliers, and inconsistencies can
distort your analysis and visualizations. In Python, the Pandas library provides powerful tools to
handle such issues. You can detect missing values using is null(), remove them with dropna(), or
replace them with a specific value using fillna(). Outliers can be identified using statistical methods
such as the Z-score, and handled by removing or replacing them with the median or mean.
import pandas as pd
import numpy as np
# Sample data with missing values and outlier
data = {'A': [1, 2, [Link], 4, 100], 'B': [5, [Link], 7,
8, 9]}
df = [Link](data)
# Fill missing values with the mean
[Link]([Link](), inplace=True)
# Detect outliers (values greater than 3 standard
deviations)
z_scores = (df - [Link]()) / [Link]()
df_no_outliers = df[(z_scores < 3).all(axis=1)]
print(df_no_outliers)
Output:
A B
0 1.00 5.00
1 2.00 7.25
2 26.75 7.00
3 4.00 8.00
4 100.00 9.00
4.2 Data Visualization using Statistical Graphs
Statistical graphs help summarize and visualize data distributions, relationships, and proportions. The
most common types include bar graphs, histograms, scatter plots, and pie charts. Each graph type is
suited for specific data and analysis needs. For example, bar graphs compare categories, histograms
show distributions, scatter plots reveal relationships between variables, and pie charts illustrate
proportions.
57
PRIMER ON ARTIFICIAL INTELLIGENCE
4.2.1 Types of Graphs
Table 2: Types of Graphs
Graph Type Best For Example Use Case
Bar Graph Comparing categories Sales by product category
Histogram Showing distributions Exam score distribution
Scatter Plot Visualizing relationships Height vs. weight correlation
Pie Graph Showing proportions Market share by company
[Link] Bar Graph
A bar graph is a chart that represents categorical data with rectangular bars, where the length of each
bar is proportional to the value it represents. Bar graphs are ideal for comparing quantities across
different categories, such as sales by region or number of students in different classes. Bars can be
vertical or horizontal, and the spacing between bars helps distinguish different categories.
Bar graphs are widely used in business, education, and research for their simplicity and clarity. They
can also display grouped or stacked data for more detailed comparisons.
[Link] Histogram
A histogram is a type of bar chart that shows the
frequency distribution of a continuous variable. The
data is divided into intervals(bins), and each bar
represents the frequency of data within each bin.
Unlike bar graphs, histograms have adjacent bars
with no gaps, as they represent continuous data.
Histograms are useful for understanding the
distribution, spread, and skewness of data, such as
exam scores or ages in a population.
import [Link] as plt
import numpy as np
data = [Link](0, 1,
1000) Figure 43: Example of Histogram
[Link](data, bins=20,
color='skyblue', edgecolor='black')
[Link]('Value')
[Link]('Frequency')
[Link]('Histogram Example')
[Link]()
58
PRIMER ON ARTIFICIAL INTELLIGENCE
[Link] Scatter Plot
A scatter plot displays individual data points on a two-
dimensional plane, showing the relationship between
two numerical variables. Each point represents a pair
of values. Scatter plots are excellent for identifying
trends, clusters, and outliers, and for visualizing
correlations between variables. They are widely used
in scientific research, economics, and social sciences.
import [Link] as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [2, 3, 5, 7, 11, 8, 4, 15, 12] Figure 44: Example of Scatter
[Link](x, y) Plot
[Link]('X Value')
[Link]('Y Value')
[Link]('Scatter Plot Example')
[Link]()
[Link] Pie Graph
A pie graph (or pie chart) is a circular chart divided into slices, where each slice represents a part of
the whole. Pie charts are best for showing proportions or percentages, such as market share or budget
allocation. Each slice’s angle corresponds to its
proportion of the total.
Pie charts should be used when you have a small
number of categories, as they become hard to
interpret with many slices.
import [Link] as plt
labels = ['A', 'B', 'C', 'D']
sizes = [30, 20, 25, 25]
[Link](sizes, labels=labels,
autopct='%1.1f%%')
[Link]('Pie Chart Example')
[Link]() Figure 45: Example of Pie Graph
4.3 Introduction to Dimensionality of Data
Dimensionality refers to the number of attributes or features in a dataset. Most basic graphs visualize
two dimensions (x and y axes), but real-world data often has many more features, leading to multi-
dimensional data. Understanding and visualizing high-dimensional data is essential for advanced data
analysis, as it can reveal deeper patterns and relationships.
4.3.1 Multi-dimensional Data Representation
Multi-dimensional data representation involves organizing and visualizing data with more than two
or three variables. This is common in datasets with many features, such as demographic data (age,
income, education, etc.). Techniques for representing multi-dimensional data include 3D plots,
parallel coordinates, heatmaps, and pair plots.
59
PRIMER ON ARTIFICIAL INTELLIGENCE
For example, a 3D scatter plot can show three variables at once, while a pair plot displays all pairwise
relationships in a matrix of scatter plots.
import seaborn as sns
import [Link] as plt
# Load example dataset
iris = sns.load_dataset('iris')
# Pair plot to show relationships between all features
[Link](iris, hue='species')
[Link]()
Figure 46: 3D Scatter Plot
60
PRIMER ON ARTIFICIAL INTELLIGENCE
4.3.2 Visualization using Graphs
Visualizing multi-dimensional data requires
special techniques. Common methods include:
(a) Pair plots: Show all pairwise relationships in
a dataset.
(b) Heatmaps: Represent data values as colors in
a matrix.
(c) Parallel coordinates: Each variable is a
vertical axis, and each observation is a line
crossing all axes.
(d) 3D scatter plots: Show three variables at
once, though interpretation can be
challenging.
Figure 47: Heatmap
These visualizations help uncover patterns,
clusters, and outliers in complex datasets.
import seaborn as sns
import [Link] as plt
# Heatmap of correlations in the iris dataset
iris = sns.load_dataset('iris')
corr = [Link](numeric_only=True)
[Link](corr, annot=True, cmap='coolwarm')
[Link]('Feature Correlation Heatmap')
[Link]()
Sample Questions:
Question 1.
Assertion (A): Seaborn is preferred over Matplotlib for statistical visualizations.
Reason (R): Seaborn has built-in functions for heatmaps and violin plots.
A. Both A and R are true, and R explains A
B. Both are true, but R doesn’t explain A
C. A is true, R is false
D. A is false, R is true
Question 2.
Assertion (A): Pie charts are unsuitable for comparing 10 product categories.
Reason (R): Small slices in pie charts make proportions hard to interpret.
A. Both A and R are true, and R explains A
B. Both are true, but R doesn’t explain A
C. A is true, R is false
D. A is false, R is true
61