Beginner

Plotting Data with Pandas

The Python visualization ecosystem and creating charts directly from pandas.

Prerequisites: Basic Python, pandas basics and DataFrame concepts


Table of Contents

  1. Course Overview
  2. The Python Visualization Ecosystem
  3. Creating Charts with pandas
  4. Reference Diagrams
  5. Reference Tables
  6. 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

ModuleContent
1The Python visualization ecosystem, introduction to matplotlib
2Data 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:

PackageDescriptionBase
matplotlibFoundational library, default object used by pandas
SeabornOriented toward statistical visualizationmatplotlib
BokehInteractive visualizations for the webown
PlotlyInteractive and embeddable visualizationsown

Key rule: All plot objects created by pandas are matplotlib objects. Calling .plot() on a DataFrame is 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:

ParameterRole
namesSpecifies column names if no header is present
index_colDesignates the column(s) to use as the index
usecolsImports 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 DataFrame before 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

ParameterValueEffect
kind'bar'Vertical bars
kind'barh'Horizontal bars
titlestrChart title
legendNone / FalseRemove the legend
xcolumn nameX axis
ycolumn nameY 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:

YearFreshmanJuniorSeniorSophomore
20181500130012001400
20191600120011001500
20201650

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. The pivot() 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

ParameterTypeDescriptionExample
kindstrChart type'bar', 'scatter'
xstrColumn for X axisx='City'
ystr / listColumn(s) for Y axisy='Population'
titlestrChart titletitle='My chart'
xlabelstrX axis labelxlabel='Year'
ylabelstrY axis labelylabel='Value'
legendbool / NoneShow/hide legendlegend=False
colorstr / listSeries color(s)color='blue'
figsizetupleFigure size (inches)figsize=(10, 6)
binsintNumber of bins (histogram)bins=20
alphafloatTransparency (0 to 1)alpha=0.7
gridboolShow gridgrid=True
fontsizeintAxis font sizefontsize=12
rotintX label rotation (degrees)rot=45
subplotsboolSeparate subplots per seriessubplots=True
stackedboolStack series (bar/area)stacked=True

kind Parameter Values

kind ValueChart TypeUse Cases
'line'Line plotTime trends, continuous data
'bar'Bar chart (vertical)Categorical comparison
'barh'Bar chart (horizontal)Same + long labels
'hist'HistogramFrequency distribution
'scatter'Scatter plotCorrelation between 2 variables
'area'Area chartParts of a total over time
'pie'Pie chartProportions of a whole
'box'Box plotStatistical distribution (median, Q1, Q3, outliers)
'kde'KDE / Density plotSmoothed distribution
'hexbin'Hexbin plotDensity for large point clouds
'density'Same as 'kde'Smoothed distribution

6. Datasets Used in the Course

homes.csv — Real Estate Sales

ColumnDescription
SellSale price
ListListing price
LivingLiving area
RoomsNumber of rooms
BedsBedrooms
BathsBathrooms
AgeHouse age (years)
AcresAcreage
TaxesProperty taxes

Usage: scatter plot (Age vs List), histogram (Acres).

cities.csv — US City Populations

ColumnDescription
CityCity name
YearYear (2015–2019)
PopulationPopulation estimate

Usage: bar chart and barh chart (2019 population by city).

enrollment.csv — University Enrollments

ColumnDescription
YearAcademic year
ClassLevel (Freshman, Sophomore, Junior, Senior)
EnrollmentNumber 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

Interested in this course?

Contact us to book it or get a custom training plan for your team.