Prerequisites: Basic Python, pandas basics and
DataFrameconcepts
Table of Contents
- Course Overview
- The Python Visualization Ecosystem
- Creating Charts with pandas
- Reference Diagrams
- Reference Tables
- Datasets Used in the Course
1. Course Overview
This course introduces matplotlib, the most widely used visualization framework for Python, through the built-in visualization capabilities of pandas. Data visualization is essential at two moments in analytical work:
- During analysis — to explore and understand data.
- For communication — to share results with other stakeholders.
Topics Covered
| Module | Content |
|---|---|
| 1 | The Python visualization ecosystem, introduction to matplotlib |
| 2 | Data selection, chart types (line, scatter, bar, hist, area), formatting |
2. The Python Visualization Ecosystem
Available Visualization Tools
There are four main packages for visualizing data with Python/pandas:
| Package | Description | Base |
|---|---|---|
| matplotlib | Foundational library, default object used by pandas | — |
| Seaborn | Oriented toward statistical visualization | matplotlib |
| Bokeh | Interactive visualizations for the web | own |
| Plotly | Interactive and embeddable visualizations | own |
Key rule: All
plotobjects created by pandas are matplotlib objects. Calling.plot()on aDataFrameis equivalent to making a matplotlib call.
matplotlib and pyplot
pyplot is a matplotlib submodule that exposes simple functions to manipulate chart elements (lines, legends, axes). Its syntax is deliberately similar to MATLAB.
import matplotlib.pyplot as plt
%matplotlib inline is a Jupyter Notebook magic command that requests charts to be displayed directly inline in the notebook, alongside the code.
%matplotlib inline
Three-Step Framework for Creating a Plot
┌─────────────────────────────────────────────────────┐
│ Step 1: Import the necessary packages │
│ Step 2: Prepare / import data │
│ Step 3: Call the visualization function │
└─────────────────────────────────────────────────────┘
Demo: First Plot in Jupyter Notebook
# Step 1 — Imports
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
# Step 2 — Data
x = [2, 3, 4]
y = [4, 3, 2]
# Step 3 — Visualization
plt.plot(x, y)
Result: a descending line plot connecting points (2,4), (3,3), (4,2).
3. Creating Charts with pandas
Line Plot
By default, the .plot() method creates a line plot that connects each data point with a line.
With a simple array
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
# Daily temperatures (°F) in Seattle over 5 days
y = [54, 58, 60, 57, 55]
pd.Series(y).plot()
Matplotlib assigns a default integer index (0, 1, 2…) on the X axis.
With an explicit X axis
x = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
y = [54, 58, 60, 57, 55]
plt.plot(x, y)
plt.title('Seattle High Temp (5-day)')
plt.xlabel('Day')
plt.ylabel('Temperature (°F)')
plt.show()
Loading and Selecting Data
read_csv
The read_csv function loads a CSV file into a DataFrame:
df = pd.read_csv('homes.csv')
df.head()
Common read_csv options:
| Parameter | Role |
|---|---|
names | Specifies column names if no header is present |
index_col | Designates the column(s) to use as the index |
usecols | Imports only the specified columns |
Example from homes.csv:
Sell,List,Living,Rooms,Beds,Baths,Age,Acres,Taxes
142,160,28,10,5,3,60,0.28,3167
175,180,18,8,4,1,12,0.43,4033
129,132,13,6,3,1,41,0.33,1471
...
Selecting columns for a plot
# Plot the relationship between two columns
df.plot(x='List', y='Rooms')
By default, pandas plots each column as a line on the Y axis with an automatic X index. To isolate the relationship between two specific variables, explicitly specify x= and y=.
Scatter Plot
A scatter plot is ideal for visualizing the relationship between two numerical variables. Use the kind='scatter' parameter.
df.plot(kind='scatter', x='Age', y='List')
Filtering data before plotting
# Filter homes 50 years old or less
house_plot_data = df[df['Age'] <= 50]
house_plot_data = house_plot_data[house_plot_data['List'] < 600000]
house_plot_data.plot(kind='scatter', x='Age', y='List',
title='List Price vs. Age of Home (≤50 yrs)')
Best practice: Filter outliers into a new
DataFramebefore creating the chart to keep the code clear.
Bar Chart
A bar chart is suitable for comparing categories or data segments. File: cities.csv.
cities_df = pd.read_csv('cities.csv')
# Filter year 2019 only
cities_2019 = cities_df[cities_df['Year'] == 2019]
# Vertical bars
cities_2019.plot(kind='bar', x='City', y='Population',
title='2019 Population', legend=None)
Horizontal bars
# Horizontal bars — better rendering for long city names
cities_2019.plot(kind='barh', x='City', y='Population',
title='2019 Population', legend=None)
Notable parameters
| Parameter | Value | Effect |
|---|---|---|
kind | 'bar' | Vertical bars |
kind | 'barh' | Horizontal bars |
title | str | Chart title |
legend | None / False | Remove the legend |
x | column name | X axis |
y | column name | Y axis |
Histogram
A histogram represents the frequency distribution of a numerical variable. Values are grouped into bins (intervals).
# Distribution of acreage for homes sold
house_plot_data['Acres'].plot(kind='hist',
title='Acreage Distribution')
Interpretation: The majority of home sales have an acreage below 0.5, and nearly all are below 1.5 acres.
Customizing bins
house_plot_data['Acres'].plot(kind='hist', bins=20,
title='Acreage Distribution',
xlabel='Acres',
ylabel='Count')
Area Chart
An area chart is useful when the data represents a total with components over a time dimension. File: enrollment.csv.
Raw data
Year,Class,Enrollment
2018,Freshman,1500
2018,Sophomore,1400
2018,Junior,1300
2018,Senior,1200
...
Step 1 — Load and explore
enrolled_df = pd.read_csv('enrollment.csv')
enrolled_df.head()
Step 2 — Pivot the DataFrame (long → wide format)
# pivot: one row per year, one column per class level
pivot_enrolled = enrolled_df.pivot(index='Year',
columns='Class',
values='Enrollment')
pivot_enrolled.head()
Result of the pivot:
| Year | Freshman | Junior | Senior | Sophomore |
|---|---|---|---|---|
| 2018 | 1500 | 1300 | 1200 | 1400 |
| 2019 | 1600 | 1200 | 1100 | 1500 |
| 2020 | 1650 | … | … | … |
Step 3 — Create the stacked area chart
pivot_enrolled.plot(kind='area',
title='College Enrollment by Class Level')
Important: Without the
pivot, the area chart will not be properly stacked. Thepivot()method reorganizes the data so that each column corresponds to a distinct series.
4. Reference Diagrams
Hierarchy of pandas Chart Types
graph TD
A["df.plot()"] --> B["kind='line'\nLine Plot"]
A --> C["kind='scatter'\nScatter Plot"]
A --> D["kind='bar'\nBar Chart vertical"]
A --> E["kind='barh'\nBar Chart horizontal"]
A --> F["kind='hist'\nHistogram"]
A --> G["kind='area'\nArea Chart"]
A --> H["kind='box'\nBox Plot"]
A --> I["kind='pie'\nPie Chart"]
A --> J["kind='kde'\nKDE / Density"]
A --> K["kind='hexbin'\nHexbin Plot"]
B --> L[("Time trends\nContinuous relationships")]
C --> M[("Relationships between\n2 variables")]
D --> N[("Categorical\ncomparison")]
E --> N
F --> O[("Frequency\ndistribution")]
G --> P[("Total evolution\nover time")]
H --> Q[("Advanced statistical\ndistribution")]
I --> R[("Parts of a whole")]
Flow: df.plot() → matplotlib Backend
flowchart LR
A["DataFrame\n(pandas)"] -->|".plot(kind=...)"\nor direct call| B["pandas Plot API"]
B -->|"internal call"| C["matplotlib Figure\n& Axes"]
C -->|"rendered via"| D{"Backend"}
D -->|"Jupyter Notebook"| E["%matplotlib inline\nInline display"]
D -->|"Python Script"| F["plt.show()\nNative window"]
D -->|"Save"| G["plt.savefig()\n.png / .svg / .pdf"]
style A fill:#4CAF50,color:#fff
style B fill:#2196F3,color:#fff
style C fill:#FF9800,color:#fff
style D fill:#9C27B0,color:#fff
5. Reference Tables
Main df.plot() Parameters
| Parameter | Type | Description | Example |
|---|---|---|---|
kind | str | Chart type | 'bar', 'scatter' |
x | str | Column for X axis | x='City' |
y | str / list | Column(s) for Y axis | y='Population' |
title | str | Chart title | title='My chart' |
xlabel | str | X axis label | xlabel='Year' |
ylabel | str | Y axis label | ylabel='Value' |
legend | bool / None | Show/hide legend | legend=False |
color | str / list | Series color(s) | color='blue' |
figsize | tuple | Figure size (inches) | figsize=(10, 6) |
bins | int | Number of bins (histogram) | bins=20 |
alpha | float | Transparency (0 to 1) | alpha=0.7 |
grid | bool | Show grid | grid=True |
fontsize | int | Axis font size | fontsize=12 |
rot | int | X label rotation (degrees) | rot=45 |
subplots | bool | Separate subplots per series | subplots=True |
stacked | bool | Stack series (bar/area) | stacked=True |
kind Parameter Values
kind Value | Chart Type | Use Cases |
|---|---|---|
'line' | Line plot | Time trends, continuous data |
'bar' | Bar chart (vertical) | Categorical comparison |
'barh' | Bar chart (horizontal) | Same + long labels |
'hist' | Histogram | Frequency distribution |
'scatter' | Scatter plot | Correlation between 2 variables |
'area' | Area chart | Parts of a total over time |
'pie' | Pie chart | Proportions of a whole |
'box' | Box plot | Statistical distribution (median, Q1, Q3, outliers) |
'kde' | KDE / Density plot | Smoothed distribution |
'hexbin' | Hexbin plot | Density for large point clouds |
'density' | Same as 'kde' | Smoothed distribution |
6. Datasets Used in the Course
homes.csv — Real Estate Sales
| Column | Description |
|---|---|
Sell | Sale price |
List | Listing price |
Living | Living area |
Rooms | Number of rooms |
Beds | Bedrooms |
Baths | Bathrooms |
Age | House age (years) |
Acres | Acreage |
Taxes | Property taxes |
Usage: scatter plot (Age vs List), histogram (Acres).
cities.csv — US City Populations
| Column | Description |
|---|---|
City | City name |
Year | Year (2015–2019) |
Population | Population estimate |
Usage: bar chart and barh chart (2019 population by city).
enrollment.csv — University Enrollments
| Column | Description |
|---|---|
Year | Academic year |
Class | Level (Freshman, Sophomore, Junior, Senior) |
Enrollment | Number of enrolled students |
Usage: stacked area chart (enrollment evolution by class level).
Essential Commands Summary
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
# --- Load data ---
df = pd.read_csv('file.csv')
# --- Line plot (default) ---
df['column'].plot(title='My title')
# --- Scatter plot ---
df.plot(kind='scatter', x='col_x', y='col_y')
# --- Vertical bar chart ---
df.plot(kind='bar', x='category', y='value', legend=False)
# --- Horizontal bar chart ---
df.plot(kind='barh', x='category', y='value', legend=False)
# --- Histogram ---
df['column'].plot(kind='hist', bins=20, title='Distribution')
# --- Area chart (with prior pivot) ---
pivot_df = df.pivot(index='year', columns='category', values='value')
pivot_df.plot(kind='area', title='Evolution by category')
# --- Save ---
plt.savefig('my_chart.png', dpi=150, bbox_inches='tight')
plt.show()
Search Terms
plotting · data · pandas · python · foundations · analysis · engineering · analytics · plot · chart · area · df.plot · matplotlib · parameters · reference · selecting · visualization