Matplotlib
Data Visualization Using 2D and 3D Plots
Comprehensive Guide to Data Visualization in Python Versatile
2D & 3D Plots bar_chart
Static Plots Interactive Animated
High Quality
code Mr. Tapan Kumar Dey verified
What is Matplotlib?
Key Features
info Python Data Visualization Library
Versatile
Python's most popular plotting library for widgets
Supports 2D and 3D plots including line, bar,
creating static, animated, and interactive scatter, histogram, pie charts and more
visualizations
Highly Customizable
tune
Created By Control every aspect of your plots - colors, fonts,
person John D. Hunter styles, and layout
in 2003
Publication Quality
verified
ad Generate high-resolution, professional-grade
visualizations for research and presentations
Installation and Setup
Basic Import & Setup
Installation Methods
code Standard Import
terminal pip install matplotlib import [Link] as plt
Using Python package installer
# Check version
print(plt.__version__)
science conda install matplotlib
Using Anaconda package manager
notebook Jupyter Notebook Setup
check_circle Verify Installation %matplotlib inline
import matplotlib # Display plots inline
print(matplotlib.__version__) [Link]()
lightbulb Restart Python environment after installation if needed
Basic Plotting Concepts
Basic Plotting Workflow
1 Import pyplot
2 Create figure
Matplotlib Architecture
3 Create axes
Figure
4 Plot data
crop_square
The overall canvas container for all plots 5 Display plot
Axes code Code Example
grid_on
Individual plot area with x/y axes
import [Link] as plt
# Create figure and axes
Three-Layer Architecture
fig, ax = [Link]()
Backend arrow_forward Artist arrow_forward Pyplot
# Plot data
[Link]([1, 2, 3, 4], [1, 4, 2, 3])
# Display
[Link]()
Line Plots
Creating Line Plots
Line Plot Visualization
code Basic Line Plot
import [Link] as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
[Link](x, y)
[Link]('X Axis')
[Link]('Y Axis')
[Link]('Line Plot Example')
[Link]()
show_chart Multiple Lines
[Link](x, y, color='red') linewidth=2.5
Line Color Line Width [Link](x, y1, 'r--', label='Line 1')
[Link](x, y2, 'b-', label='Line 2')
linestyle='--' marker='o' [Link]()
Line Style Data Points
Bar Charts
Bar Chart Visualization
Creating Bar Charts
code Basic Bar Chart
import [Link] as plt
categories = ['A', 'B', 'C', 'D']
values = [23, 45, 56, 78]
[Link](categories, values)
[Link]('Categories')
[Link]('Values')
[Link]('Bar Chart Example')
[Link]()
bar_chart Grouped & Stacked Bars
# Grouped bars
[Link]() [Link]() [Link](x1, y1, width=0.4, label='Group 1')
Vertical Bars Horizontal Bars [Link](x2, y2, width=0.4, label='Group 2')
width=0.8 color='blue' # Stacked bars
Bar Width Bar Color [Link](x, y1, label='Layer 1')
[Link](x, y2, bottom=y1, label='Layer 2')
Scatter Plots
Creating Scatter Plots Scatter Plot Visualization
code Basic Scatter Plot
import [Link] as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
[Link](x, y)
[Link]('X Axis')
[Link]('Y Axis')
[Link]('Scatter Plot Example')
[Link]()
scatter_plot Customized Scatter Plot
s=100 c='red'
[Link](x, y, s=200, c='purple',
Marker Size Marker Color
marker='s', alpha=0.7,
label='Data Points')
marker='o' alpha=0.6 [Link]()
Marker Shape Transparency
Histograms
Creating Histograms
bar_chart Understanding Bins
code Basic Histogram
Bins divide the range of values into intervals. Each
import [Link] as plt bin counts how many data points fall within that
import numpy as np
range.
data = [Link](1000)
[Link](data, bins=30) analytics Customized Histogram
[Link]('Value')
[Link]('Frequency') [Link](data, bins=20,
[Link]('Histogram Example') color='steelblue',
[Link]() edgecolor='black',
alpha=0.7,
density=True)
bins=30 density=True
Number of Bins Normalize
Distribution Analysis Frequency Counting
color='blue' edgecolor='black' Understand data spread Count occurrences
Bar Color Bin Edges
Pie Charts
Advanced Features
Creating Pie Charts
pie_chart Exploded Pie Chart
code Basic Pie Chart
explode = (0.1, 0, 0, 0, 0)
import [Link] as plt colors = ['#ff9999', '#66b3ff',
'#99ff99', '#ffcc99', '#c2c2f0']
sizes = [30, 20, 25, 15, 10]
labels = ['A', 'B', 'C', 'D', 'E']
[Link](sizes, explode=explode,
labels=labels, colors=colors,
[Link](sizes, labels=labels)
autopct='%1.1f%%',
[Link]('Pie Chart Example') shadow=True, startangle=90)
[Link]()
explode=(0.1, 0, 0, 0, 0) autopct='%1.1f%%' legend_toggle Adding Legend
Explode Effect Percentages
[Link](sizes, labels=labels,
autopct='%1.1f%%')
shadow=True colors=['red', 'blue',
'green']
[Link](title='Categories',
Add Shadow
Custom Colors
loc='upper right')
Subplots and Figure Management
grid_on 2x2 Grid Layout
Creating Multiple Plots
code
1 2
2x2 Subplots
fig, axes = [Link](2, 2,
figsize=(12, 8))
axes[0, 0].plot(x1, y1)
axes[0, 1].bar(x2, y2)
axes[1, 0].scatter(x3, y3)
axes[1, 1].hist(data)
plt.tight_layout() 3 4
figsize=(12, 8) sharex=True
Figure Size Share X Axis
sharey=True tight_layout()
dashboard Common Grid Arrangements
Share Y Axis Adjust Spacing
subplots(1, 2) subplots(2, 1) subplots(2, 2)
1×2 Grid 2×1 Grid 2×2 Grid
Customizing Plots
Customization Elements
Complete Customization Example
label [Link]() label [Link]()
X-axis Label Y-axis Label
code Fully Customized Plot
[Link](figsize=(10, 6)) title [Link]() legend_toggle [Link]()
[Link](x, y1, 'b-', label='Line 1', Plot Title Legend
linewidth=2)
[Link](x, y2, 'r--', label='Line 2')
grid_on [Link]() crop_landscape [Link]()
Grid Lines X-axis Limits
[Link]('Time (seconds)',
fontsize=12)
[Link]('Value', fontsize=12)
crop_portrait [Link]() text_fields [Link]()
[Link]('Customized Plot',
Y-axis Limits Tick Labels
fontsize=16, fontweight='bold')
[Link](fontsize=10,
loc='upper right') add_comment Annotations
[Link](True, alpha=0.3)
[Link](0, 100) [Link]('Peak', xy=(50, 40),
[Link](0, 50) xytext=(60, 45),
arrowprops=dict(
facecolor='red'))
Styling and Themes
Applying Styles
palette Using Style Sheets
Built-in Themes
import [Link] as plt
auto_awesome seaborn assessment ggplot
# Apply a style Modern & Clean R-like Style
[Link]('seaborn')
trending_up fivethirtyeight grid_on dark_background
# Create plot with style
Data Journalism Dark Theme
[Link](x, y)
[Link]('Styled Plot')
[Link]()
more_horiz More Available Styles
bmh classic fast
settings Custom rcParams
grayscale Solarize_Light2 tableau-colorblind10
from matplotlib import rcParams
rcParams['[Link]'] = (12, 6) Tip: Use [Link] to list all available styles
tips_and_updates
rcParams['[Link]'] = 14
rcParams['[Link]'] = 12
rcParams['[Link]'] = 0.3
Working with Dates and Time Series
Time Series Plotting
Time Series Components
calendar_today Creating Time Series Plot
access_time [Link]() schedule [Link]()
import [Link] as plt
Date Objects DateTime Objects
import datetime
dates = [[Link](2024, 1, i)
text_fields DateFormatter view_week DateLocator
for i in range(1, 8)]
Format Dates Locate Dates
values = [10, 15, 12, 18, 14, 20, 16]
[Link](dates, values)
[Link]('Weekly Data') auto_awesome Date Format Codes
[Link]()
%Y %m
Year (2024) Month (01-12)
%d %H:%M:%S
date_range Date Formatting Day (01-31) Time
from [Link] import DateFormatter
tips_and_updates Tip: Use pd.to_datetime() for Pandas dataframes
formatter = DateFormatter('%Y-%m-%d')
[Link].set_major_formatter(formatter)
3D Plotting
Creating 3D Plots
view_in_ar 3D Scatter Plot 3D Plot Components
from mpl_toolkits.mplot3d import Axes3D
widgets Axes3D bubble_chart scatter()
import [Link] as plt
3D Axes Object 3D Scatter Points
fig = [Link]()
ax = fig.add_subplot(111, projection='3d')
landscape plot_surface() waves plot_wireframe()
Surface Plots Wireframe Plots
[Link](x, y, z, c='blue',
marker='o', s=100)
ax.set_xlabel('X')
ax.set_ylabel('Y') 3d_rotation View Control
ax.set_zlabel('Z')
[Link]() view_init(elev=30, azim=45) set_xlim3d()
Set View Angle X Axis Limits
set_ylim3d() set_zlim3d()
Y Axis Limits Z Axis Limits
terrain 3D Surface Plot
X, Y = [Link](x, y)
tips_and_updates Tip: Use projection='3d' to enable 3D plotting
Z = [Link]([Link](X**2 + Y**2))
ax.plot_surface(X, Y, Z, cmap='viridis')
Saving and Exporting / Best Practices
Saving Plots
Best Practices
save Using savefig()
Keep It Simple
check_circle
import [Link] as plt Avoid clutter, focus on key insights
# Basic save
Choose Appropriate Chart Types
[Link]('[Link]') check_circle
Match visualization to data type
# With DPI and format
[Link]('high_quality.png', check_circle Label Clearly
dpi=300, Add titles, axis labels, and legends
format='png',
bbox_inches='tight')
Use Consistent Colors
check_circle
Maintain visual consistency across plots
image Supported Formats
check_circle High Resolution for Publication
Use DPI 300+ for print quality
.png .pdf .svg
Raster Vector Vector
tips_and_updates Tip: Use bbox_inches='tight' to prevent cropping
.jpg .eps .tiff
Raster Vector Lossless
Matplotlib Visualization
Examples
Code Examples & Plot Results
Line Plot Pie Chart Histogram Scatter Plot Box Plot
show_chart Line Plot - Code Example
import [Link] as plt
import numpy as np
# Generate data
x = [Link](0, 10, 100)
y = [Link](x)
# Create figure and plot
[Link](figsize=(8, 4))
[Link](x, y, 'b-', linewidth=2)
# Add labels and title
[Link]('Line Plot Example')
[Link]('X Axis')
[Link]('Y Axis')
[Link](True, alpha=0.3)
# Display the plot
[Link]()
show_chart Line Plot - Result
pie_chart Pie Chart - Code Example
import [Link] as plt
# Define data
labels = ['Apple', 'Banana', 'Orange', 'Mango']
sizes = [30, 25, 25, 20]
colors = ['#ff9999', '#66b3ff', '#99ff99', '#ffcc99']
explode = (0.1, 0, 0, 0)
# Create figure and plot
[Link](figsize=(8, 6))
[Link](sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90)
# Add title and show
[Link]('Fruit Distribution')
[Link]('equal')
[Link]()
pie_chart Pie Chart - Result
bar_chart Histogram - Code Example
import [Link] as plt
import numpy as np
# Generate random data
data = [Link](1000)
# Create figure and plot
[Link](figsize=(8, 5))
[Link](data, bins=30, color='skyblue', edgecolor='black')
# Add labels and title
[Link]('Distribution of Data')
[Link]('Value')
[Link]('Frequency')
[Link](True, alpha=0.3)
# Display the plot
[Link]()
bar_chart Histogram - Result
scatter_plot Scatter Plot - Code Example
import [Link] as plt
import numpy as np
# Generate random data
x = [Link](100)
y = x + [Link](100) * 0.5
# Create figure and plot
[Link](figsize=(8, 6))
[Link](x, y, alpha=0.6, c='blue',
edgecolors='w', s=80)
# Add labels and title
[Link]('Scatter Plot Example')
[Link]('X Values')
[Link]('Y Values')
[Link](True, alpha=0.3)
# Display the plot
[Link]()
scatter_plot Scatter Plot - Result
view_week Box Plot - Code and Result
import [Link] as plt
import numpy as np
# Generate data for 3 groups
data = [[Link](0, std, 100)
for std in range(1, 4)]
# Create figure and plot
[Link](figsize=(8, 6))
[Link](data, patch_artist=True)
# Add labels and title
[Link]('Box Plot Example')
[Link]('Groups')
[Link]('Values')
[Link]([1, 2, 3],
['Group 1', 'Group 2', 'Group 3'])
[Link](True, alpha=0.3)
# Display the plot
[Link]()
show_chart Line Plot - When to Use
schedule Time Series Data compare_arrows Compare Multiple Series
Track changes over chronological time periods Overlay several data series on same axes
trending_up Trend Analysis hub Relationship Detection
Identify upward, downward or cyclical patterns Discover correlations between variables
timeline Continuous Data analytics Prediction Modeling
Visualize smooth, uninterrupted data streams Support forecasting and trend projections
show_chart Line Plot - Case Study
assessment Stock Price Tracking
Monitoring technology company stock performance over 6-month period insights
to guide investment decisions.
Key Insights
• 15% growth in Q1-Q2 period
trending_up Trend Identification pattern Pattern Recognition
Spot upward/downward movements Detect cyclical behavior • Peak at $175 in May
• Stabilized around $160-165
compare_arrows Benchmarking analytics Risk Assessment
• Moderate volatility
Compare with market indices Evaluate volatility levels
bar_chart Bar Plot - When to Use
category Categorical Data leaderboard Ranking Items
Compare distinct groups or categories Display ordered data by performance
grid_on Discrete Values analytics Group Analysis
Represent non-continuous data points Compare multiple groups side by side
compare Value Comparison track_changes Magnitude Differences
Show magnitude differences clearly Visualize gaps between values
bar_chart Bar Plot - Case Study
assessment Sales Performance Analysis
Comparing quarterly revenue across 5 product categories to identify top
insights
performers and optimize inventory allocation. Key Findings
• Electronics: $850K (35%)
emoji_events Identify Leaders trending_down Detect Underperformers
• Apparel: $650K (27%)
Spot top-performing products Find categories needing attention
• Home & Garden: $480K (20%)
• Sports: $280K (12%)
inventory Inventory Planning analytics Performance Gaps
Optimize stock levels Measure category differences • Books: $160K (6%)
pie_chart Pie Chart - When to Use
percent Proportions & Percentages layers Simple Composition
Show relative sizes as percentages Straightforward data breakdowns
donut_large Part-to-Whole Relationships circle 100% Total
Display how parts make up a whole When values sum to complete whole
filter_7 Limited Categories visibility Quick Overview
Best for 3-7 categories maximum Instant visual of dominant segments
pie_chart Pie Chart - Case Study
assessment Market Share Analysis
Visualizing smartphone market distribution across 5 major competitors to
insights
identify market leaders and assess competitive positioning. Market Distribution
• Brand A: 35% (Leader)
military_tech Market Leaders compare_arrows Competitive Gap
• Brand B: 25% (Challenger)
Identify dominant players Measure market differences
• Brand C: 20% (Established)
• Brand D: 12% (Emerging)
account_balance Market Composition lightbulb Strategic Insights
Understand total structure Guide business decisions • Brand E: 8% (Niche)
bar_chart Histogram - When to Use
show_chart Distribution Analysis warning Identify Outliers
Visualize continuous data spread Spot extreme values easily
analytics Frequency Distribution waves Pattern Recognition
Count occurrences in intervals Detect bell curves & patterns
open_in_full Data Spread & Range query_stats Statistical Insights
Understand data variability Assess normality & skewness
bar_chart Histogram - Case Study
assessment Customer Age Analysis
Analyzing age distribution of 10,000 e-commerce customers to understand insights
demographics, identify target segments, and optimize marketing
Key Findings
strategies.
• Peak: 25-34 age group (32%)
groups Target Identification campaign Marketing Focus • Secondary: 35-44 group (28%)
Pinpoint key age groups Tailor campaigns effectively
• Growing: 18-24 segment (18%)
• Stable: 45-54 demographic (14%)
trending_up Peak Detection report_problem Anomaly Spotting
• Minor: 55+ population (8%)
Find highest concentration Detect unusual patterns
view_week Box Plot - When to Use
compare Compare Distributions balance Detect Skewness
Side-by-side group comparison Visualize data asymmetry
report Identify Outliers dashboard Multiple Groups
Spot extreme data points easily Compare several distributions
format_list_numbered Five-Number Summary insights Statistical Summary
Min, Q1, Median, Q3, Max Comprehensive data overview
view_week Box Plot - Case Study
assessment Exam Performance Analysis
Comparing test scores across 3 different class sections to identify
insights
performance disparities, outliers, and grade distribution patterns. Key Findings
• Class A: 68-92 (Median 80)
school Performance Comparison star Exception Detection
• Class B: 55-85 (Median 72)
Compare class averages Spot top performers
• Class C: 72-95 (Median 84)
• Outliers: Classes B & C
warning Identify Struggles balance Grade Distribution
Find at-risk students Analyze spread patterns • Best consistency: Class A