Skip to main content
Data Visualization and Interpretation

Matplotlib and Python for Data Visualization

Published: 2026-08-11
Level: postgraduate
Audience: Postgraduate students in Data Visualization and Interpretation

12.1 Last Session Recap: Dashboards and Stories

12.1.1 From Worksheets to Dashboards to Stories

Why does every chart you build need to live inside two bigger containers before it reaches an audience? Because a single view answers one question, while a dashboard answers several related questions at a glance, and a story walks the audience through the answers in a deliberate order.

The mental model that ties the whole tool phase together is a three-level pipeline. Think of it as building a presentation out of one picture each:

  • A worksheet is a single view — one chart, one table, one map. It is the smallest self-contained unit of visualization.
  • A dashboard places several worksheets (and other objects) on one screen, so several views share space and work together.
  • A story sequences dashboards into a narrative: the audience moves from one dashboard to the next, and the order tells the message.

The direction of the pipeline is one-way in spirit: content flows up from worksheets into dashboards, and dashboards flow up into stories. If you keep this staircase in mind, every tool-based task in the course maps to exactly one of the three levels. The course handout marks the tool phase complete — the sessions that follow move into raw technologies where more coding is required, so this three-level model is the bridge you carry over.

Intuition: a worksheet is a single photograph, a dashboard is a gallery wall where several photographs hang together, and a story is the guided tour that decides which wall you look at first, second, and last. The tour does not change the photographs; it changes what the audience attends to, and in what order.

12.1.2 Dashboard Objects and Actions

Dashboards are built from objects, and every object has a behavior. A tile is a fixed position where a worksheet sits evenly on the screen — the worksheet snaps into the grid, and the space is shared in an ordered way. A floating object is the opposite: it moves freely and can be dragged anywhere on the canvas, on top of other objects if you want. The practical rule of thumb: use tiles when you want the layout to stay neat and predictable, floating when you want an object to sit in a specific spot regardless of the grid.

Besides worksheets, an image object (found at the bottom of the left-hand panel) lets you place a picture on the dashboard — you click it, choose the image, and it appears. Logos, screenshots, and reference images are the typical uses. Containers resize dynamically: when automatic resize is on, the dashboard takes the available space on its own and fills it. That is the dynamic-resizing behavior behind responsive layouts — the same dashboard reshapes itself for a wide monitor and a narrow one without you rebuilding it.

Interactivity comes from actions, and there are three kinds:

Action What it does
Highlight The user clicks or hovers on the source, and matching values light up on the destination worksheet
Filter The user's selection on the source limits which rows appear on the destination
URL The user's selection builds a web link and opens a page

Each action pairs a source with a destination: you say what happens on the destination worksheet when the user interacts with the source. Titles, actions, and URLs are flexible — they can carry fields, so the title of a dashboard can change on the fly depending on the parameter the user selects. These small touches are what make a dashboard feel interactive rather than static.

Scope: actions need a defined source and destination to be meaningful. A filter action with no destination changes nothing; a URL action whose link is hard-coded ignores the user's selection. The interactivity lives in the pairing, not in the action type alone.

12.1.3 Best Practices, Story Types and Characteristics

The session ended with dashboard best practices, the seven typical story types, and the characteristics of a good dashboard. The seven story types (a slide borrowed from Tableau) include the time series story and the zoom-out and zoom-in variants — they are narrative templates, like essay structures: time series tells "how things changed over time," zoom-in starts wide and tightens onto one detail, zoom-out starts on the detail and broadens to the context.

The characteristics of a good dashboard are the same design habits you already learned: clear purpose, minimal clutter, consistent coloring, and a layout that leads the eye from the most important number to the supporting detail.

Pitfalls from the tool phase:

  • Treating the dashboard as a dumping ground — more worksheets does not mean more insight; each tile should earn its place.
  • Mixing story types inside one story without a reason; pick the narrative arc before arranging the dashboards.
  • Forgetting that automatic resize changes spacing, so check the dashboard at the size your audience will actually see.

The practical message was simple: keep practicing. The drag-and-drop mechanics — where to drag what — take a little practice at first, but they are simple, and experienced industry people pick them up quickly.

Recap + bridge: the pipeline is worksheet → dashboard → story, interactivity comes from paired actions, and good dashboards follow the design principles you already know. That whole stack now steps aside: the next sessions leave the drag-and-drop canvas and start writing code in Python. The design eye stays exactly the same — only the hands change.

Exam note: Practice is the real requirement for the tool phase. The mechanics of dragging fields, building dashboards, and assembling stories come from hands-on repetition, not from reading.

Real-world: the worksheet → dashboard → story pipeline is not a classroom invention — it is how enterprise analytics is delivered. Analysts build worksheets from data sources, operations teams watch live dashboards, and executives receive a story of screenshots or live pages that walks them through the quarter. The three levels map to three audiences: the analyst, the operator, and the decision-maker.

12.2 Calculated Fields

12.2.1 What a Calculated Field Is

What do you do when the data source gives you profit and sales, but the report you are building needs a number that is not in the field list — say, the difference between the two? The answer is a calculated field: a field you create yourself on top of the fields that already exist in the data source.

Every field that comes with the data source appears in the field list automatically, but sometimes the number you need is not there — you need your own computation. That is what the calculated field feature is for. You never leave the tool, you never export the data to Excel, and you never ask someone in IT to rebuild the extract. You write one small formula, and the tool hands you a brand-new field that behaves exactly like the imported ones. This section was a quick brush-up because a student had asked about it earlier; the walkthrough below is the full version.

Intuition: a calculated field is like a recipe card you add to the kitchen. The pantry (data source) holds the ingredients (fields) — flour, sugar, eggs. When a recipe needs "dough," which no single ingredient provides, you do not buy a new pantry; you write down the combination (flour + sugar + eggs) once, and from then on "dough" is a standard ingredient you can reach for in any recipe. The analogy breaks where the tool does the cooking per row: your formula runs automatically for every row of data, not just once.

12.2.2 Creating a Calculated Field

You can open the calculated field dialog two ways: from the top menu (Create Calculated Field) or from the Analysis menu — both lead to the same place. The dialog asks you for a name and then lets you build a formula. The field list and the function list on the side are exactly like the functions you have seen in Excel: sum, average, and the rest. You can also use string functions, date functions, date differences, and logical constructs — if-then-else ("if this is greater than this, multiply this by this") and case statements. In effect you can write a small piece of code inside the calculated field, and the tool runs it for every row.

The recipe in five steps:

  1. Name the field — the dialog asks for a name first, so the field has an identity in the field list.
  2. Pick the ingredients — double-click any field from the field list to drop it into the formula; double-click again to wrap it in a number format when you want it treated as a number.
  3. Apply the functions — combine fields with the functions from the side list (sum, average, string, date, if-then-else, case).
  4. Validate — the dialog checks the formula before you commit.
  5. Use it — the new field appears in the field list and behaves like any built-in field.

Worked example — the cost price field:

The demo created a field called cost price. The setup: subcategory on the rows; discount, profit, and sales brought in as numbers (double-click a field to get the number format). The formula was simply sales minus profit:

cost price = [sales] - [profit]

with the working assumption that sales minus profit equals cost price (a made-up assumption — the point is the mechanics, not the accounting). Walk it through with real numbers:

Row Sales Profit Cost price = sales − profit
1 120 25 95
2 90 10 80
3 150 40 110
4 200 55 145

On clicking OK, the new field appeared in the field list, computed the difference for every row, and could then be used exactly like any built-in field: dropped on rows, swapped in sequence with other fields, placed anywhere in the layout.

Sense-check: row 1 says the store took in 120, kept 25 as profit, so it spent 95 buying the goods — the field always satisfies cost = sales − profit, and a quick look at row 4 (200 − 55 = 145) confirms the arithmetic. The formula, not a static number, is what travels with the field.

12.2.3 Validation, Icons and Managing Fields

Two things make calculated fields easy to manage. First, validation happens before you use the field: if the formula is correct, the dialog says the calculation is valid; if you type something wrong, it says the formula contains errors and will not work. So syntax errors are caught up front, not when you try to build the view — you cannot create a broken field and only discover it mid-report. Second, the icon distinguishes the field type: every numeric field shows a hash symbol, while a calculated field shows a hash plus an equals sign — that combination is the signal that this field is user-created.

Pitfalls:

  • Ignoring the validation message — "the formula contains errors" means the field will not be created or will not compute; fix the formula in the dialog, do not click through it.
  • Confusing the icons — a plain hash field comes from the data source; a hash-plus-equals field is yours. If a view is showing something unexpected, the calculated field is the first place to look.
  • Forgetting the assumption — a formula like sales minus profit embeds a business assumption; if the business definition changes, the field keeps silently using the old one until you edit it.

Calculated fields persist with the workbook — they stay with you when you save, you can edit them later (Edit Calculated Field), you can delete them, and you can create as many as you need and use each one wherever you want, on any individual sheet.

Q: A student had asked: what if the data source does not have the field I need — can I build my own calculation without leaving the tool? A: Yes. Create a calculated field from the top menu or the Analysis menu, give it a name, and combine the existing fields with functions (numerical, string, date, if-then-else, case). The dialog validates the formula before you use it, and the field shows the equals-plus-hash icon. Once created, the field behaves like any other field — you can drag it, reorder it, edit it, or delete it, and it is saved with the workbook. The point is that the data source limits which imported fields you have, not which fields you can compute.

Recap: a calculated field is a user-written formula that the tool evaluates per row and promotes to a first-class field — create it from the menu, validate it in the dialog, spot it by the equals-plus-hash icon, and reuse it anywhere. Keep this feature in mind: the next sections trade drag-and-drop for code, and a calculated field is the closest thing the tool phase had to writing a formula in a programming language.

Exam note: Know how to create a calculated field, how the dialog validates the formula, and how to identify one by the equals-plus-hash icon.

Real-world: calculated fields are the standard way analysts keep a single source of truth for business math — gross margin, customer lifetime value, discount tiers, day-of-week flags — inside the dashboard tool. When the same definition appears in every dashboard of an organization, it is usually a calculated field, not a repeated hand computation.

12.3 The Shift from Tools to Python

12.3.1 Why the Change of Pace

Why leave tools that already build charts with a drag and a drop? Because the tools give you speed and polish inside their boundaries, and the next phase of the course steps outside those boundaries: the course has finished the table and BI tools — the drag-and-drop products with ready-made templates where you get output instantly — and moves into raw technology: Python.

This is class 12 of 16; the next two sessions are dedicated to matplotlib, and the three sessions after that cover other libraries. So the shift is not a detour — roughly a third of the remaining course happens in Python.

Intuition: the tool phase is like driving a car with an automatic gearbox: you point and press, and the car decides the rest. Python is like driving the same car in manual mode: every gear change is your decision, which is more work at first — but it is also how you get the exact engine behavior you want. The road (the data and the design rules) does not change; the control you have over the vehicle does.

The instructor warned that these classes are heavier than the tool phase: instead of a user interface and drag-and-drop, you work with code, and a bit of programming is required. To keep the class engaging rather than overwhelming, the first half was conceptual — where Python stands compared to the BI tools — and the second half was live demos: code executed line by line, with the resulting charts shown together.

12.3.2 Python Exposure and the Syntax Advice

The instructor first checked the class's Python background:

Q: Any exposure to Python so far? On a scale of zero to ten, where are you? A: Minimal — no experience at all, and not from a coding background. That is completely fine. The warning not to get worried was direct: the syntax is not the end of the world. These are just alternative packages and software; not knowing them does not mean you cannot understand data visualization. The standing advice: syntax will come and go — do not get emotional about syntax. Be conceptually clear, because syntax keeps changing every few years, and you can pick up whatever syntax your career demands.

The standing warning — do not get emotional about syntax. The exact spelling of a command in 2026 will look dated within a few years, and the next language or library you meet will spell it differently anyway. What transfers between tools, languages, and versions is the concept: what a chart needs (data, marks, scales, labels), what a loop does, what an array holds. Treat syntax as the accent, not the language. If a command refuses to run, the error message is information, not a verdict on you.

Everything you already learned about visualization design applies here too: less clutter, coloring, pre-attentive attributes, making something immediately bigger so it draws attention. Those concepts stay with you whether you work in a data visualization tool or in Python — only the syntax and the libraries change.

Recap + bridge: the course turns from drag-and-drop to code, the classes get heavier, and the survival rule is simple — keep the concepts, stay calm about syntax. The design principles from the tool phase (clutter, color, pre-attentive attributes, emphasis) ride along into every Python chart you will build. Next: a direct comparison of the two worlds, so you can see exactly what each side gives up and gains.

Real-world: this is the same fork working analysts meet in the field: a business intelligence stack (Power BI, Tableau) for routine reporting, and Python for the charts and analyses that no tool template covers. Careers rarely choose one side forever — the people who move between them smoothly are the ones who held on to the concepts and learned each syntax when the job demanded it.

12.4 Data Visualization Tools vs. Python

12.4.1 Technical Skills and Learning Curve

How do you choose between a BI tool and Python when the same chart is reachable from both sides? The honest answer starts with eight dimensions, and no single one decides the case. When choosing between a BI tool (Power BI, Tableau) and Python, eight dimensions matter: technical skills, learning curve, customization, interactivity, data source connectivity, deployment and sharing, cost, and team collaboration.

On technical skills: Power BI and Tableau need no coding experience — you drag and drop, arrange screens and layouts, and at most use the same if-then-else fundamentals that exist in Excel. Python, in contrast, requires programming knowledge: you must know the syntax, and you must be able to debug your own errors. On learning curve: Python is easy once you are familiar, but reaching that point is a steep climb — there are tons of libraries and methods to absorb, and it does not come in a week or even a few months; it needs practice. The tools are much faster to learn: a beginner who knows how to drag a field, drag another field, and connect to a database can build a screen in under a minute.

12.4.2 Customization and Interactivity

On customization, Python has the upper hand. Because it is a lower-level programming environment, it lets you change pixel-level details — sizes, colors, every element of a chart. The tools do offer customization (custom fonts and so on, and Power BI ships with six or seven template categories), but there is a limit; Python libraries give you absolute control.

On interactivity, the balance flips. Python libraries are indeed interactive — there are libraries you can zoom and drag in, and they are used on web pages and in applications — but the tools provide far more out of the box: one click adds filters on the right, check boxes can be toggled, and the filter type can be switched between drop-down and check box. The tools are designed for interactive exploration and analysis, so they have an edge here — though that does not mean Python cannot do it.

12.4.3 Data Connectivity and Sharing

On data source connectivity, the tools win on breadth: Power BI and Tableau ship with 50-plus (up to 70-plus) data sources and adapters — ODBC, JDBC, and more — so connecting to databases and various sources is much easier in Tableau. Python also imports from many sources, but compared with the tools it has limitations.

On deployment and sharing, the tools are designed for easy sharing: you can publish online, embed in a portal, drop a link, and put it in web pages; Tableau Public gives you a URL others can view in real time. Python output is typically a static image, or an exported image that can be embedded in an application — workable, but the tools have richer layouts across tablet and mobile, and sharing is their native use case.

12.4.4 Cost, Collaboration and How to Choose

On cost: Python libraries are free and open source, while Power BI and Tableau come with a price tag. On team collaboration: the tools have built-in collaboration — you can put work on a server, let multiple people work on the same files, save, and run from the server — which suits a big program where teams in different locations work together.

The comparison at a glance:

Dimension BI tools (Power BI, Tableau) Python libraries
Technical skills No coding needed; drag-and-drop, Excel-style logic Programming knowledge: syntax + debugging
Learning curve Fast — a beginner builds a screen in under a minute Steep — lots of libraries and methods; months of practice
Customization Good, but bounded (custom fonts, template categories) Absolute, down to pixel-level control
Interactivity Rich out of the box: one-click filters, check boxes, drop-downs Possible (zoom, drag in some libraries) but more setup
Data connectivity 50–70+ built-in connectors: ODBC, JDBC, and more Broad imports, but with more limitations
Sharing Publish online, embed, real-time URLs (Tableau Public) Static images or exported images embedded in apps
Cost Paid licenses Free and open source
Collaboration Built-in: server-based shared work Team-managed via code and repositories

The two rows that decide most real projects are the ones in the middle: tools win when interactivity and speed matter most, Python wins when control matters most.

So how do you choose? There is no single right answer; it depends on your situation.

  • Choose Python libraries when your user base is good at programming and you need highly customized visuals — you get much more control, but only if your team has the skill set, and it comes with a lot of learning.
  • Choose the tools when you need something quick and easy, when you do not want to teach everyone the syntax, and when you have many different data sources (one in SQL, another in Oracle, another in SAP) that you need to connect fast.

Pitfalls when choosing:

  • Deciding on customization alone — pixel control is worthless if the team cannot write or debug code.
  • Deciding on cost alone — free software still costs the team's time to learn and maintain.
  • Ignoring the data sources — a 70-connector tool may be the only practical option when six databases and two legacy systems feed one report.
  • Treating it as permanent — many teams run both: tools for operations, Python for the bespoke analyses.

Keep these comparison points in mind before selecting a stack.

Real-world: Power BI ships ready-made template categories (about six or seven), while Tableau Public provides shareable real-time URLs — both are examples of how tools optimize for speed-to-output, which is why organizations with mixed data sources often standardize on them.

Exam note: The comparison table (skills, learning curve, customization, interactivity, connectivity, sharing, cost, collaboration) is the kind of material to remember as a framework for justifying a tool choice.

Recap + bridge: the tools win on learning speed, interactivity, connectivity, sharing, and collaboration; Python wins on customization and cost. Choose tools for quick, shared, mixed-source reporting, Python for highly customized visuals where the team can code. That framework is the context for what comes next: matplotlib — the Python side of the comparison, seen from the inside.

12.5 What Is Matplotlib

12.5.1 Definition and Ecosystem Position

What is the single most used chart library in the Python world — the one that seaborn and bokeh quietly build on top of? Matplotlib, the subject of this and the next session.

Matplotlib is a powerful Python library designed specifically for creating visualizations. It can produce static, animated, and interactive visualizations, and it is the foundational library of the Python visualization ecosystem: many other libraries — seaborn and bokeh among them — are built on top of it. Those will be covered in the next classes; today the focus is the foundation itself.

Matplotlib has been in the industry for a long time and is mature and well established. It is a high-level library: with a small amount of code you get publication-quality, neat, clean graphics. The reference book describes the same promise in different words: a versatile and dependable Python plotting package that offers clean, easy ways to produce quality data graphics with huge flexibility for customization.

Intuition — the foundation, not the top floor: if the Python visualization world were a building, matplotlib is the concrete slab. Seaborn gives you prettier defaults with less typing, bokeh gives you web interactivity — but both stand on matplotlib and hand their drawing work down to it. Learn the slab once, and every higher floor becomes an accent rather than a new language.

12.5.2 Prerequisites

Three prerequisites matter before starting.

  1. A basic understanding of Python — the demo examples are small and simple, but larger projects need a decent command of the language.
  2. The ability to set up a Python environment — it is not double-click-and-go; you must be able to install and configure Python yourself.
  3. Working knowledge of NumPy and Pandas, the two fundamental Python data-structure libraries. Graphics are generated from numbers, so you must be able to process the numbers first — if those data-structure concepts are missing, you will struggle.

NumPy and Pandas are not just for visualization; they are the two key concepts everybody should know in Python, and the demos use NumPy in almost every example.

Why NumPy first: matplotlib does not draw text you type — it draws numbers. The x-axis positions, the y-axis values, the sizes, the colors all arrive as arrays of numbers. NumPy is the library that makes arrays cheap and easy (a list of daily temperatures becomes a numpy.ndarray), and pandas organizes those numbers into labeled tables. The plotting call is the last step of a longer chain: load → clean → compute → plot. The reference book puts the same idea in its own terms: NumPy lies at the core of the calculations that computationally enable matplotlib, which is why it comes bundled with most Python distributions.

12.5.3 Facts and History

A few facts put matplotlib in context.

  • Open source and free — no cost, and a rich user community that develops and supports it.
  • Inspired by MATLAB — you can hear it in the name — and the similarity shows in the style of working.
  • A long history — development started around 2002, which means 20-plus years in the industry, which is why it is mature and well proven.
  • Inside a large data science ecosystem (standard deviation and friends), which is why data scientists love it — and Python itself is the preferred language for that community.
  • A large, loyal community — some users practically sleep, eat, and breathe these libraries, and big companies rely heavily on them too, even as those companies move into AI.
  • Many output formats — on-screen, in a notebook (the demos run in a Jupyter notebook), as images, as PDFs, and more — so the same code can feed reports and publications.

On the output formats, the reference book draws the line that matters: raster images (PNG, JPG, BMP) store a dense grid of color dots, where resolution is measured in dots per inch (DPI) and stretching loses sharpness; vector images (SVG, PDF, PS) store paths — lines joining points — and scale to any size without losing detail. That is why a scientific paper takes a PDF while a web thumbnail takes a PNG.

Real-world: Matplotlib is not a toy for single users — large companies depend on it for their standard charts, and its PDF and image outputs are why it appears so often in scientific publications. When a paper, a report, and a dashboard all need the same figure, the figure is usually made once in matplotlib and exported in the format each destination needs.

Recap + bridge: matplotlib is the free, MATLAB-inspired, 20-plus-year-old foundation library of Python visualization — high-level enough for publication-quality charts from small amounts of code, deep enough that seaborn and bokeh are built on it. It needs three things before you touch it: basic Python, a working environment, and NumPy/Pandas. Next: getting that environment up and checking that matplotlib is installed.

12.6 Setting Up the Python Environment

12.6.1 Three Ways to Get Started

How do you get from "I have no Python" to "my first chart" in one afternoon? You pick one of three practical routes — all of them free — and follow it to the end.

Route 1 — plain Python. Download and install the latest Python from the official Python website and follow the installation instructions — a standalone install, after which you can start coding. This is the lightest setup, but you then install each library yourself.

Route 2 — Anaconda. A distribution that installs a complete editor setup in one go: once installed it offers several launch options, the most important being the Jupyter notebook. Anaconda comes with the packages preinstalled — you can see NumPy and Matplotlib in its package list — so you can start using it straight away. This is the option the instructor uses.

Route 3 — Google Colab. A free browser-based notebook you open by logging in with a Gmail account. You create a new notebook, write code, and see visualizations immediately, and all your files are saved in your Google Drive. Colab is an alternative to the Anaconda/Jupyter setup and is also free, so you can use it for practice projects.

How to pick: Anaconda when you want everything local and preinstalled (the instructor's choice, and the default for most data work); plain Python when you want a minimal install and do not mind running pip yourself; Colab when you want zero installation, a free machine in the cloud, and your notebooks saved to Google Drive. All three end at the same place: a notebook with cells where code runs and charts appear.

12.6.2 Installing and Checking the Version

After setup, the first step is installing the package. If you used the plain Python install, you run:

pip install matplotlib

That is how any Python package gets installed; once it finishes, the machine is configured for matplotlib. With Anaconda or Colab you usually skip this step because the libraries come preinstalled. To verify the installation and find the version, you import matplotlib and read its version attribute:

import matplotlib
print(matplotlib.__version__)

Worked example — the version check:

Running the two lines in the live Jupyter notebook printed version 3.4.3 — that was the version on the demo machine.

>>> import matplotlib
>>> print(matplotlib.__version__)
3.4.3

What just happened, step by step: the import line loads the matplotlib library into the notebook's memory (a package manager like pip had already put the files on disk), and matplotlib.__version__ reads the version string the library stores about itself. A version number printing without an error is the whole installation check in one line: if matplotlib were missing or broken, the import itself would raise an error before the print line ever ran.

Sense-check: the version is a date-like pattern (3.4.3 = major 3, minor 4, patch 3), so "3.4.3" means the demo machine ran a matplotlib from the 3.x generation — recent enough that every command in this lecture behaves exactly as described.

The first line of every program should be the matplotlib import, and both lines execute together when the cell runs. The notebook interface lets you run, add, cut, and clear cells, and clear the output; Colab has the same features.

Pitfalls when setting up:

  • Installing matplotlib before Python itself — pip needs a working Python to run at all.
  • Forgetting the import — a notebook cell that calls plt.plot without ever importing matplotlib fails with a name error, because the plotting tools are not loaded into memory by themselves.
  • Skipping the version check — a successful install is not proven until the import and print run without errors.
  • Mixing environments — installing into one Python while the notebook kernel runs another leads to "module not found" puzzles; keep one environment per project.

Real-world: in practice, teams standardize the environment so charts reproduce anywhere. A company may pin the matplotlib version in a requirements file (matplotlib==3.4.3) so that a figure rendered today looks the same on every machine and in every report archive — the version check from this section is the first command of that reproducibility story. Jupyter notebooks themselves host the plots as cell output, which is why matplotlib integrates with them natively.

12.7 Pyplot — the Plotting Interface

12.7.1 The Import Line and Aliases

You have matplotlib installed. What do you type to start drawing? The second thing to import is Pyplot, the submodule of matplotlib where all the plotting capabilities live. The standard import line is:

from matplotlib import pyplot as plt

This line appears in every plotting example. Read it as: "bring my submodule pyplot from the matplotlib library, and call it plt." If this line runs without error, your matplotlib installation is fine and you are ready to make graphs.

plt is the conventional alias — you could pick any name, but once chosen you must use it consistently throughout the program. The same convention applies elsewhere: numpy is imported as np and pandas as pd, so wherever you see np it means numpy, and plt is just shorthand for matplotlib.pyplot. Two lines — the matplotlib import and the pyplot import — precede every plot you build.

Intuition — the alias is a nickname, not a copy: importing pyplot as plt is like introducing your friend as "Pat." You still mean the same person; the short name just saves you from spelling the full name a hundred times a day. If you introduce them as "Pat," you cannot call them "Patrick" in the middle of the same conversation — the code is the same way: pick one alias and keep it for the whole program.

Two equivalent spellings of the import appear in the wild — from matplotlib import pyplot as plt (the form in this lecture) and import matplotlib.pyplot as plt. They load the same submodule and the same plt name; you will meet both in tutorials and books, and either one works.

12.7.2 Matplotlib vs Pyplot

Matplotlib and Pyplot are not competitors; they are different levels of the same stack.

  • Matplotlib is the bigger umbrella: a powerful Python library and an API offering fine-grained control and a wide range of functionality — line plots, bar graphs, 3D plots, and more.
  • Pyplot is a submodule, an interface within matplotlib that holds the functions you actually call to draw. Pyplot is designed to streamline creating common plots: its syntax is much easier, it behaves a lot like MATLAB, and its functions use matplotlib's core functionality under the hood.

So for making visuals, Pyplot is the preferred entry point, while matplotlib proper is the deeper API for fine-grained control.

The two-door building: think of matplotlib as a building with two doors. The front door is pyplot — it has a receptionist who handles the common requests ("line plot, please," "bar chart, please") with short commands. The service entrance is the raw matplotlib API — you walk in, take the stairs, and adjust the plumbing yourself. Both doors lead to the same building, and the same charts come out; the front door is faster for everyday work, the service entrance is where you go when you need something the receptionist does not offer.

12.7.3 Key Features

Pyplot's features map directly to what you can do with a chart.

  • Very simple plotting interface — one function call, plt.bar(...) or plt.pie(...), creates a whole chart type.
  • Interactive plotting — the plt.ion() call turns on interactive behavior for every plot: zoom in, zoom out, move the graph, and modify the plot in real time. (This is an advanced feature covered in the next class.)
  • Full customization — color, marker, line style — so a graph can be styled to your exact requirements.
  • Stateful interface — titles, labels, and other settings can be changed in one line; the figure remembers its state between calls.
  • Multiple plots and subplots — five or six small graphs next to each other in a grid, which makes comparisons easy.
  • Interactive tools — zoom, moving, and saving (save as image, save as PDF), which enhance the user experience.

Each of these was shown live in the second half of the class.

Pitfalls:

  • Typing plt before the import — the name plt exists only after the import line runs; calling plt.plot in a cell that never imported pyplot raises a name error.
  • Mixing aliases — writing plt.plot in one cell and matplotlib.pyplot.plot in another works but invites typos; the convention is one alias, used consistently.
  • Confusing the two imports — import matplotlib alone does not give you plt; the pyplot submodule is a separate import line and appears in every plotting example.

Each import has a job: the matplotlib import brings in the library for version and configuration checks, and the pyplot import brings in the drawing functions themselves.

Recap + bridge: pyplot is the submodule that actually draws, imported as plt by convention; it is the friendly front door to the deep matplotlib API, and its features (one-call chart types, interactivity, customization, stateful settings, subplots, saving) are exactly the buttons of a charting tool. Next: what happens inside the library when you call those functions — the three-layer architecture that makes the front door possible.

Real-world: the import matplotlib.pyplot as plt line is so universal that it appears at the top of millions of analysis notebooks and scripts — financial reports, weather models, medical dashboards. Spotting plt in someone else's code immediately tells a reader which drawing library is in play, the same way pd announces pandas.

12.8 The Layered Architecture of Matplotlib

12.8.1 The Three Layers

What happens between the moment you call plt.plot(x, y) and the moment a chart appears? Matplotlib has a layered architecture with three components, and each one does a separate job.

  • Scripting layer (top) — this is where Pyplot starts. When you call the matplotlib pyplot functions, the scripting layer gives you all the common plots ready-made; it is the simplest layer, very easy for beginners, and you can build visuals quickly through it.
  • Artist layer (middle) — one level down, this is where you work with the objects that make up a figure — the figure itself, axes, ticks, labels, lines, legends.
  • Backend (bottom) — where the actual rendering happens — the drawing onto the screen or into a file.

Intuition — a restaurant kitchen: the scripting layer is the waiter who takes your order in plain words ("a line plot with red markers"). The artist layer is the kitchen where each dish — the figure, the axes, the ticks, the labels — is prepared as a real, touchable object. The backend is the delivery: it plates the dish on the screen or packs it into a file. You normally only ever talk to the waiter, but if you want the fries extra crispy, someone in the kitchen has to know which fryer — that someone is the artist layer. The analogy breaks in one place: in matplotlib you can reach past the waiter at any time and talk to the kitchen directly, which is exactly what the layered design allows.

12.8.2 The Overall Flow and Benefits

The flow through the architecture is straightforward: user interaction goes through the scripting layer, which drives artist creation — lines, axes, and labels — and the backend rendering finally puts it on the screen or saves it to a file.

The benefit of this design is a clear separation of concerns: every layer has a well-defined purpose.

  • Flexibility and customization — because it is layered, you can reach in and change a pixel size, thicken a line, adjust any element. The scripting layer hands you the ready-made plot; the artist layer hands you every object inside it, so nothing is out of reach.
  • Extensibility — you can stretch the library to very specific use cases by replacing or combining pieces at any level.

That is the structural reason matplotlib gives pixel-level control that template-based tools cannot match: the tool gives you a finished picture and a few sliders; matplotlib gives you the picture, the canvas, and the paint.

Visual intuition: picture the flow as a three-floor diagram. Top floor, a person types plt.plot(x, y) — one line, one label on the arrow down. Middle floor, four labeled boxes appear: Figure, Axes, Ticks, Labels — the objects of the chart. Bottom floor, a monitor icon and a file icon — the screen and the file. The arrows all run top to bottom: command → objects → rendered output. The landmark of the diagram is the middle floor: that is where every customization you will ever make is decided, and it is why a one-line pyplot call can still be tuned pixel by pixel.

Recap + bridge: matplotlib is three layers — scripting (easy commands), artist (the objects: figure, axes, ticks, labels, lines, legends), and backend (rendering) — and the separation between them is what makes pixel-level control and extensibility possible. Remember the middle layer: when the next sections add markers, grids, and fonts with one-line parameters, each parameter is quietly turning a knob on an artist object.

Real-world: the layered design is what lets matplotlib power both quick exploratory charts and production pipelines. A data scientist uses the scripting layer for a morning sketch; a product team hooks the artist layer to embed customized figures inside an application — the same library serving two very different depths of use. Interactive tools built on matplotlib also live in the backend layer, which is why zoom and pan behave the same across screens and files.

12.9 Plotting with plt.plot

12.9.1 The Basic Plot

The very first thing in matplotlib is the plot function. plt.plot(x, y) draws points or markers in the diagram; by default it draws a line connecting the points, from point to point. You pass two parameters — your x-axis values and your y-axis values — and you get a line. The minimal demo:

import matplotlib.pyplot as plt
import numpy as np

x_points = np.array([1, 8])
y_points = np.array([3, 10])
plt.plot(x_points, y_points)
plt.show()

Worked example — the two-point line:

The two arrays are stored in the two variables, and plt.plot pairs them position by position:

Position x value y value Point on the chart
0 1 3 (1, 3)
1 8 10 (8, 10)

The first entries of the two arrays form the first point, (1, 3); the second entries form the second point, (8, 10). plt.plot draws the line between the two points, and plt.show() displays the plot. The hash symbol in the demo file marks a comment (lines starting with # are notes for humans, not code).

Sense-check: the line runs diagonally up and to the right, because both coordinates grow from the first point to the second — and that is exactly what the pairing says: as x goes 1 → 8, y goes 3 → 10.

The line chart you saw in the tools is built exactly this way — arrays in, line out.

12.9.2 Plotting Many Points

Plotting more than two points is the same call with longer arrays.

Worked example — four points, one call:

With x = [1, 2, 6, 8] and y = [3, 8, 1, 10], the plot connects the four points:

Position x value y value Point on the chart
0 1 3 (1, 3)
1 2 8 (2, 8)
2 6 1 (6, 1)
3 8 10 (8, 10)

The line goes from point to point in array order: (1, 3) → (2, 8) → (6, 1) → (8, 10). Notice that the x values are not evenly spaced (2 to 6 is a gap), so the segments have different slopes — the chart is faithful to the numbers, not to a nice-looking curve.

Sense-check: y rises from 3 to 8, drops to 1, then climbs to 10 — the line visibly zigzags, which matches the pattern of the y array (3, 8, 1, 10).

You can pass as many points as you like. In real work the x-axis can be dates: feed one year of data from a CSV file or a data file with dates as x and sales as y, and matplotlib draws a multi-year graph for you just by changing the variables. The plotting mechanics do not change — only the data does.

12.9.3 One Array Means y

An important behavior: if you pass only one set of parameters, matplotlib assumes it is the y-axis and supplies the x-axis automatically as the sequence 0, 1, 2, 3, 4, ...

Worked example — one array, auto x:

With y = [3, 8, 1, 10, 5, 7], the plotted points are:

Index Auto x y value Point on the chart
0 0 3 (0, 3)
1 1 8 (1, 8)
2 2 1 (2, 1)
3 3 10 (3, 10)
4 4 5 (4, 5)
5 5 7 (5, 7)

The x positions are never written down — matplotlib fills them in as the array positions 0, 1, 2, 3, 4, 5, so the first y value sits at x = 0, the second at x = 1, and so on.

Sense-check: six values in, six points out, and the x coordinates always match the index of the value — a one-line check for any single-argument plot.

The variable name does not matter — even if the variable were called z_points instead of y_points, the output would be identical, because matplotlib assumes it is the y values. The one-array form is a shorthand; pass both arrays when you want explicit control over the x positions. The reference book confirms the same rule: when a single parameter is parsed, the data values are assumed to be on the y axis, with the indices on the x axis.

12.9.4 Why This Matters

The deeper point the demo made: every example in the class starts with the same two imports, and everything else is one function call with parameters. plt.plot, plt.title, plt.xlabel, plt.grid — by attaching a dot to plt you inherit the potential of the whole library. Changing the type of graph, the grid, the labels is a matter of one line plus parameters. That is the power of Pyplot: complete control of what kind of plot you get, through plain function calls.

Pitfalls:

  • Two arrays of different lengthsplt.plot(x, y) pairs values position by position, so an x array with four values and a y array with five values has no partner for the fifth y; keep the arrays the same length.
  • Forgetting plt.show() — without it, the plot may never be displayed; the demo pattern is always plot, then show.
  • Assuming the one-array form is smarter than it is — a single argument is always treated as y with auto x = 0, 1, 2, ...; if your real x positions are different, you must pass both arrays.
  • Thinking the variable name matters — it does not; z_points plots identically to y_points, because only the argument position (the single array = y) decides the behavior.

The class also cautioned that these demos are only scratching the surface — matplotlib has many more capabilities, and the next class covers more advanced features like loading data from CSV.

Recap + bridge: plt.plot(x, y) draws a line through the paired points; with one array it assumes y and auto-fills x = 0, 1, 2, ...; and every knob from here on — markers, line styles, labels, grids, subplots — is the same pattern: one function call plus parameters. The next sections turn each knob, one parameter at a time.

Exam note: Understand what plt.plot(x, y) does, and what happens with a single argument (auto x = 0, 1, 2, ...) — this kind of detail is easy to test.

12.10 Markers

12.10.1 Marker Shapes

A marker (the symbol drawn at each data point) is what turns a bare line into a chart that shows where the data actually sits. Passing the marker parameter changes the plot: with marker='o' the plot draws a circle at every point; in the demo it also removed the line, leaving only the rings.

Matplotlib has a marker sheet of options: capital D creates a diamond, lowercase s creates a square, an asterisk creates a star, and there are many more — crosses, plus signs, triangles, and dozens beyond those. The reference book lists the common ones: 'o' circle, 'x' cross, '+' plus sign, 'P' filled plus, 'D' filled diamond, 's' square, '^' triangle — and notes that the full set is available under mpl.lines.Line2D.markers.

Worked example — marker shapes in the demo:

The demo showed 'o' (circles) and then '*' — the star markers appeared at every point.

Call Marker drawn at each point
plt.plot(y, marker='o') a circle at every point
plt.plot(y, marker='*') a star at every point
plt.plot(y, marker='d') a diamond at every point

Passing 'd' rendered a diamond. One word of caution from the demo itself: the audio makes it sound like the letter "b" was passed, but single letters in matplotlib double as color shortcuts — 'b' is the color blue, not a marker. The diamond markers are 'd' (thin diamond) and 'D' (filled diamond, the form listed in the reference), and one of those two is what actually appeared on the chart.

Sense-check: every point, and only the points, carries the same symbol — count the symbols and you get the number of data points; that is the whole job of a marker.

Pitfall — the letter trap: single letters are a shortcut language in matplotlib, and the same letter can mean different things in different parameters. marker='b' is not a thing (there is no b-shaped marker), but color='b' is blue. When a chart looks wrong, check which parameter the letter is inside — a marker letter and a color letter are easy to mix up, exactly as the diamond demo highlighted.

12.10.2 Marker Size, Edge and Face

Markers are fully controllable. markersize=20 makes the marker much bigger. The marker edge color is set with mec='r' — mec is short for marker edge color: m for marker, e for edge, c for color. That turns the boundary of each circle red while the inside stays its default color. The face color is set with mfc='r', turning the inside red while the edge keeps its color. Passing both mec and mfc as red gives a solid red marker — boundary and fill in one color.

Intuition — a marker is a two-part object: every marker has a boundary (edge) and a fill (face), and the two are painted separately. That is why two parameters exist instead of one: mec colors the outline, mfc colors the interior. Set only the edge and you get an outline ring; set only the face and you get a filled disc with the default edge; set both the same and the marker turns solid.

Worked example — one parameter at a time:

Each of the demos changed only one parameter at a time, which is exactly the point: the variables stay the same, and one keyword argument restyles the plot.

Change Effect
markersize=20 the same circle, much bigger
mec='r' red boundary, default-colored inside
mfc='r' red inside, edge keeps its color
mec='r', mfc='r' solid red marker — boundary and fill in one color

Sense-check: each step alters exactly one visible feature — size, then edge, then fill, then both — so the demo doubles as a recipe for testing your own changes: change one thing, look, change the next.

12.10.3 The Three Ways to Specify Color

There are three ways to give a color, and all three work wherever a color is accepted — markers, lines, or other elements:

  1. A single letter — r for red, b for blue, and so on. The reference book lists the full set: 'b' blue, 'g' green, 'r' red, 'c' cyan, 'm' magenta, 'y' yellow, 'k' black, 'w' white.
  2. A hexadecimal color code — the same style of code used on the web, like '#00ff00' for green; the hash-prefixed six digits pack red, green, and blue amounts into one string.
  3. A named color — one of about 140 named colors already defined in Python — hot pink, dark blue, light green, and many more; you can pass the name directly as the color argument.

Worked example — the color demo:

Way to specify Example Result
Single letter color='r' red
Hex code color='#00ff00' green
Named color color='hotpink' hot pink (one of about 140 named colors)

Sense-check: all three produce the same kind of value — a color — and matplotlib resolves any of them to the same internal representation, so they can be swapped freely in any parameter that takes a color.

Real-world: marker shapes and colors are how charts stay readable when several data series share one plot — a sales line with circles, a forecast line with diamonds, a target line with stars — the pattern behind every legend you have seen in a BI tool, now expressed as two parameters. Design guidance from the tool phase still applies: distinct shapes and colors for distinct series, and restraint — every extra marker style must earn its place.

12.11 Controlling Lines

12.11.1 Line Style, Color and Width

Plotting connects the points with a line, and the line itself is customizable. The linestyle parameter changes how the line is drawn: linestyle='dotted' produces a dotted line; linestyle='dashed' produces a dashed line.

Worked example — styling one line:

The demo connected the same points — (0, 3), (1, 8), (2, 1), (3, 10) — with a dotted line first, then a dashed line.

Parameter Value Effect on the line
linestyle 'dotted' dots along the path
linestyle 'dashed' dashes along the path
color 'r' the whole line red
linewidth 20.5 a very thick line

The color parameter works the same way it does for markers: color='r' turns the whole line red. The linewidth parameter controls thickness; the demo set it to 20.5, which made a very thick line. The reference book adds the full style vocabulary: 'solid' or '-' (the default), 'dashed' or '--', 'dashdot' or '-.', and ':' for a packed dotted line — with linewidth (or its short form lw) available across most matplotlib elements.

Sense-check: with the same four points and the same axes, only the line's appearance changes between the two plots — the data is untouched, and that is the whole point of styling parameters.

Because every characteristic is a parameter, you can also set styles programmatically: inside your code, check the data — "if this value is greater than that, change my line style to this" — and the chart adapts. This is the customization freedom the comparison section promised: in the tools, setting a font applies to the whole sheet or text box, and you cannot play with per-element commands like this; in Python you can.

Intuition — per-element vs whole-sheet control: in a BI tool, styling is set on containers — change the font once and every chart on the sheet follows. In Python, each element is styled individually because each element is its own object in the artist layer: the line has its own width, the title its own font, the grid its own color. And because the styling is just code, it can react to the data — an alert chart that turns red when a threshold is crossed is a plain if-statement away, not a manual edit.

12.11.2 Multiple Lines on One Plot

One plot can carry several lines. Pass two y arrays and matplotlib draws two lines, choosing colors automatically when you do not specify them — the default color cycle assigns the first line one color, the second another. You can also pass complete x-y pairs for each line.

Worked example — two lines with explicit x-y pairs:

The demo plotted a blue line through (0, 3) and (1, 8), and a purple line through (0, 6) and (1, 2), using two explicit x-y pairs:

x1 = np.array([0, 1]); y1 = np.array([3, 8])
x2 = np.array([0, 1]); y2 = np.array([6, 2])
plt.plot(x1, y1)
plt.plot(x2, y2)

Line 1 walks through (0, 3) → (1, 8): a steep upward line. Line 2 walks through (0, 6) → (1, 2): a steep downward line. The first pair is the blue line, the second pair the purple line — when no color is given, matplotlib hands each new plot call the next color from its default cycle automatically, which is why two lines on one plot are distinguishable without any styling work.

Sense-check: both lines share the same x positions (0 and 1) but cross between y = 3/8 and y = 6/2 — the plot shows a rising series meeting a falling one, exactly as the two arrays say.

Whether you pass one set (auto x) or explicit x-y pairs for every line, the plot builds each line from point to point.

Pitfalls:

  • Confusing linestyle with linewidth — one chooses how the line is drawn (dots, dashes), the other how thick it is; both take numbers or names but in different units (style names vs width in points).
  • Overriding the automatic colors unnecessarily — matplotlib picks distinct default colors per line; hard-coding every color adds maintenance with no readability gain for a two-line plot.
  • Making lines so thick they swallow the data — a width of 20.5 was a demo exaggeration; at that thickness the points and grid disappear under the stroke.
  • Forgetting that styling is per call — styles set in one plt.plot call do not leak into the next; each line carries its own parameters.

Real-world: line styling is the vocabulary of comparison charts — dashed for forecast, solid for actual, thick for the headline series, thin for context — the pattern used in dashboards for sales versus plan, spend versus budget, and modeled versus observed data. Because the styling is programmatic, a reporting pipeline can re-style one figure for the morning briefing (thick, red, annotated) and another for the archive (thin, gray) without changing the data code at all.

12.12 Labels, Titles and Fonts

12.12.1 Setting Labels and Titles

Up to this point the charts had no text. A chart without labels is a drawing; labels and titles are what turn it into a message — the reader needs to know what the axes measure and what the chart claims. Labels and titles are set with three calls:

plt.xlabel("average pulse")
plt.ylabel("calories burnage")
plt.title("Title of the plot")
plt.plot(x, y)
plt.show()

Worked example — labels and title:

The demo data were two points, (80, 240) and (85, 250), and the line between them.

Point x value y value Meaning
1 80 240 pulse 80, calories 240
2 85 250 pulse 85, calories 250

The x label "average pulse" appeared along the x-axis, the y label "calories burnage" along the y-axis, and the title above the chart. The plotting line itself is unchanged — the labels are extra lines before it. (The slightly unusual spelling "burnage" is the label text exactly as used in the demo, so the chart axis prints it as shown.)

Sense-check: the chart now answers "calories burned versus pulse" at a glance — 80 beats per minute maps to 240 calories, 85 to 250 — which the bare line could never say on its own.

The order of the calls does not matter for the text itself — plt.xlabel, plt.ylabel, and plt.title each write into the current figure's state — but the common habit is to set the text before plt.show(), so the figure renders complete.

12.12.2 Fonts and Positioning

Fonts are customizable through font dictionaries. A font dictionary (a set of properties — family, color, size — that you build once and assign) is how Python packs several font settings into one object and hands it to a text element. The demo defined two:

  • font one with family serif, color blue, and size 20, assigned to the title;
  • font two with color dark red and size 15, assigned to both the x and y labels.

The result was a blue serif title at size 20 and dark red labels at size 15. The reference book matches this pattern: font properties such as size, weight, style, family, and rotation are adjustable on text elements, often inline with the label call (for example, plt.xlabel('Date', size=12)).

Worked example — the font demo:

Element Font dictionary Result
Title family serif, color blue, size 20 blue serif title at size 20
x label color dark red, size 15 dark red x label at size 15
y label color dark red, size 15 dark red y label at size 15

This shows the per-element control Python gives you: the title and the labels carry different fonts in the same chart. Title position is also a parameter: loc='left' aligns the title to the left instead of the default center.

Sense-check: the title and the labels read as different visual levels — big blue serif on top, smaller dark red on each axis — a hierarchy built with two dictionaries, no styling panel needed.

The complete recipe for any chart: create the data → build the arrays → use pyplot → then decide the labels, the title, the fonts, the line type, and the markers — all in code. Every one of those decisions is a parameter or a call, and none of them touch the data itself, which is why the same arrays can be restyled endlessly.

Pitfalls:

  • Missing labels on comparison charts — without x and y labels, the reader cannot know the units or the meaning; the demo's "average pulse" and "calories burnage" exist precisely to avoid that ambiguity.
  • One font rule applied blindly to the whole chart — the whole point of font dictionaries is per-element control; reusing the same dictionary for title and labels flattens the hierarchy.
  • Overwriting the title position without checkingloc='left' moves the title over the plot area, so verify the chart layout after changing it.
  • Forgetting that the title and labels are stateful text — calling plt.title twice replaces the previous title rather than stacking two; only the last call is rendered.

Real-world: labels, titles, and fonts are the difference between a chart a reader can trust and one they must guess at — in published figures the axis labels carry the units, the title carries the claim, and the font hierarchy carries the reading order. Scientific papers, financial reports, and dashboards all follow the same recipe from this section: title at the top, labeled axes, and restrained font choices (the reference book suggests at most three levels of font family, weight, and size).

12.13 Grids

12.13.1 Adding a Grid

A grid is one extra line: plt.grid(). The demo started from the same labeled plot — same data, same title, same labels — and added only that line; the chart immediately showed grid lines on both the x and y axes, automatically spaced based on the data.

Worked example — the one-line grid:

Starting from the labeled plot from the previous section (same data, same title, same labels), one new line changed everything:

plt.grid()

The chart immediately showed grid lines on both the x and y axes, automatically spaced based on the data: if the values run 0–100, the grid lands on round intervals like 10, 20, 30; if they run 0–8, on 1, 2, 3. Matplotlib chooses the spacing by dividing the axis range into readable steps.

Sense-check: nothing else moved — same points, same line, same labels — so the grid is confirmed as a pure addition, not a re-layout.

12.13.2 Grid Options

The grid can be controlled like any other element. plt.grid(axis='x') draws grid lines only on the x-axis (the default is both axes). You can also style the grid in the same call: the demo used color='green', a dashed line style, and a reduced width, and the grid changed to thin green dashes. One line plus parameters — the same pattern as everything else in pyplot.

Worked example — grid options:

Call Result
plt.grid() grid lines on both axes, default style
plt.grid(axis='x') grid lines on the x-axis only
plt.grid(color='green', linestyle='dashed', linewidth=0.5) thin green dashed grid

Sense-check: each option touches one visible property — which axis, which color, which style, which thickness — so a heavy default grid can be dialed down to a faint reference the same way a heavy line was thinned earlier.

12.13.3 When to Skip the Grid

The demo came with an honest caveat: grids are generally not one of the advisable things to have. The instructor personally avoids grids unless absolutely required — for example, very small data with values in decimal fractions where the eye needs help reading precise positions. For most charts the grid adds complexity rather than clarity. The demo exists to show the capability, not to recommend the default; apply the same judgment you were taught about clutter in the tool phase.

When the grid helps and when it hurts:

  • Helps: small data sets with decimal-fraction values where the reader must read precise positions off the axes — the grid acts as a ruler.
  • Hurts: most other cases — on dense or large data, the grid lines compete with the data line for attention, and the chart reads as noise.
  • Judge like the tool phase: the clutter rules transfer directly — every grid line that does not earn its place is decoration, and decoration is the enemy of reading. The reference book shows the same caution with an example where the default grid stands out too much and interferes with interpreting the lines — subtle grid settings (lighter color, thinner line) are the compromise when a grid is genuinely wanted.

Exam note: Be able to justify whether a grid helps or hurts a chart. The guidance is: avoid unless the data is small and precise reading matters.

Recap + bridge: plt.grid() adds reference lines with automatic spacing; axis='x', color, style, and width tune them; and the design rule is to leave them off by default, switching them on only when precise reading of small decimal data demands it. The pattern stays the same as every section before it — one call, parameters, judgment. Next: splitting one frame into several charts with subplots.

Real-world: grid policy is a visible difference between chart styles in industry — scientific plots often keep a light grid as a measurement aid, while dashboards and business reports strip it to let the data and the labels carry the message. Knowing the rule of thumb (small, precise data → grid; everything else → no grid) is exactly the kind of justification a chart review or an exam question will probe.

12.14 Subplots

12.14.1 The subplot Function

Sometimes one frame must hold several charts side by side — a comparison needs both views in the same eye span. That is what subplots are for, and the tool is plt.subplot(rows, columns, plot_number). The three arguments matter: the first is the row position, the second the column position, and the third the numbering of the plot — which position in the grid this chart occupies. Everything else is ordinary plotting: you create the subplot, then plot into it as usual.

How to read plt.subplot(r, c, n): the first argument, r, is how many rows of charts the grid has; the second, c, how many columns; the third, n, which cell the current chart occupies, counted left to right, top to bottom. So subplot(2, 3, 4) means "a grid with two rows and three columns; I am drawing into cell 4" — which is the first cell of the second row, because cells 1, 2, 3 fill the top row first.

12.14.2 Worked Layouts

Worked example — three layouts from the demo:

Layout 1 — side by side: subplot(1, 2, 1) and subplot(1, 2, 2): one row, two columns, plots in positions one and two — the two charts appeared side by side.

Call Grid Position
plt.subplot(1, 2, 1) 1 row × 2 columns cell 1 (left)
plt.subplot(1, 2, 2) 1 row × 2 columns cell 2 (right)

Layout 2 — stacked: subplot(2, 1, 1) and subplot(2, 1, 2): two rows, one column — the charts stacked one above the other.

Call Grid Position
plt.subplot(2, 1, 1) 2 rows × 1 column cell 1 (top)
plt.subplot(2, 1, 2) 2 rows × 1 column cell 2 (bottom)

Layout 3 — six-pack: a two-by-three matrix with subplot(2, 3, 1) through subplot(2, 3, 6): six plots arranged in two rows of three, filled in the sequence you numbered them — row 1: cells 1, 2, 3; row 2: cells 4, 5, 6.

Call Grid Position
plt.subplot(2, 3, 1) 2 × 3 cell 1
plt.subplot(2, 3, 2) 2 × 3 cell 2
plt.subplot(2, 3, 3) 2 × 3 cell 3
plt.subplot(2, 3, 4) 2 × 3 cell 4
plt.subplot(2, 3, 5) 2 × 3 cell 5
plt.subplot(2, 3, 6) 2 × 3 cell 6

Sense-check: in every layout, rows × columns equals the number of cells, and each call selects exactly one cell — if the product and the largest cell number disagree, the grid was declared wrong.

The data for each plot is the data you passed when you created that subplot, so position and content are controlled independently. One extra line in the demo, plt.ioff(), turns off interactivity (the interactive side is covered next class).

12.14.3 Titles, Super Titles and the Dashboard Analogy

Each subplot can carry its own title.

Worked example — subplot titles and the super title:

The demo built a two-chart frame with subplot(1, 2, 1) titled "sales" and subplot(1, 2, 2) titled "income" — a sales-versus-income comparison where the data and title were attached to the correct subplot automatically: whichever subplot was active when plt.title("sales") ran is the one that got the title. Above the individual titles you can add a super title with plt.suptitle("my shop"), which appears over and above all the subplot titles.

Text element Call Where it appears
Left chart title plt.title("sales") above the left subplot
Right chart title plt.title("income") above the right subplot
Frame title plt.suptitle("my shop") over and above both titles

Sense-check: two charts, two titles, one frame title — the hierarchy matches the layout: super title names the whole dashboard, subplot titles name the individual charts.

The analogy that ties it back to the tool phase: in Tableau you create individual sheets and then drag them onto a dashboard; in Python you do exactly the same thing, except you declare how many subplots you want and their sequence in code. A super title is like the dashboard title, and the subplot titles are like the titles of the individual sheets. You can make one plot bigger, another smaller, combine different data — show sales in one place, profit in another — and build a story. In effect, subplots let you build a dashboard in Python.

Intuition — the same dashboard you already know: remember the worksheet → dashboard pipeline from the recap: sheets are worksheets, the grid of subplots is the dashboard canvas, the super title is the dashboard title, and the sequence of subplot grids you arrange is the story. The only difference is the hand: in Tableau you drag sheets onto a dashboard, here you declare rows, columns, and cell numbers in code — and then the story-building rules from the tool phase apply unchanged.

Pitfalls:

  • Reading the arguments in the wrong orderplt.subplot(2, 3, 1) is rows, columns, number — a common slip is passing columns, rows and getting a different grid than intended.
  • Numbering outside the grid — the third argument must be between 1 and rows × columns; subplot(2, 2, 5) names a cell that does not exist.
  • Plotting into the wrong cell — data attaches to the subplot that is active when the plotting call runs, so a missing plt.subplot between charts can draw the second chart over the first.
  • Forgetting titles attach per subplot — each subplot needs its own plt.title call if each chart should have one.

Recap + bridge: plt.subplot(rows, columns, plot_number) carves a cell out of a grid, ordinary plotting fills the active cell, titles attach to the active cell, and plt.suptitle crowns the whole frame — a dashboard built in code. Next session's closer: where the class stopped, what the assignment will look like, and what comes after subplots.

Real-world: subplot grids are how Python reproduces the multi-view dashboards of BI tools: a market report with sales, profit, and margin side by side; a monitoring page with six small charts over time; a paper with panels (a) through (f). Anywhere a comparison needs adjacency, the rows × columns grid is the layout engine — the same dashboard logic, expressed as three integers.

12.15 Wrap-Up: What Comes Next

12.15.1 Where We Stopped

The class covered the foundation of matplotlib: what it is, how it compares with the BI tools, how to install it, the pyplot interface, the three-layer architecture, and live demos of plotting, markers, lines, labels, titles, fonts, grids, and subplots.

The deliberate message at the end: with Python you can control almost everything, and the only real difference from the tools is the interface — there you have a UI, fonts, and formats; here you pass parameters. In terms of richness and interactivity the tools are far more mature, and no programming is needed there; in Python almost everything is also possible — all graphs, data points, statistics — because you can do the calculations inside your code and plot the results directly.

The balance of power, restated: the tools remain the champions of richness and interactivity with zero programming; Python gives up nothing essential in return because the calculations happen inside the code — the data can be computed, transformed, and summarized in the same script that draws the chart, which is exactly what a BI tool hides behind its click-through interface.

The next session starts with the scatter plot, continues with bar charts and other graphs, then covers the advanced features: loading data from CSV, interactivity, and more advanced Python concepts. The session was a deliberately light touch on Python; the next class goes a bit deeper.

12.15.2 The Assignment Question

Q: The assignment is coming soon — can we have programming in the assignment, can we use Python for what you are teaching now? A: My plan is to give the assignment on a dashboard and story — that is the core of what we learned. If you are confident, you can do it in Python, but think about how you would build a story and its flow: the assignment will most likely have a story, and that is where a data visualization tool does the work. I am planning to give an option between Power BI and Tableau. I will be publishing a sample data set in the next one or two days, so keep watching the announcements.

Why Python is the harder road for this assignment: the story and its flow are what the assignment will be judged on, and a story is precisely where the visualization tools do the work — sequencing dashboards, preserving the narrative state, guiding the reader. In Python you would have to rebuild that machinery yourself (subplot grids and navigation code), which is possible but adds risk precisely where the points are. The safe plan: build the dashboard and story in Power BI or Tableau, and use Python for the analyses that feed them if you want to practice.

Exam note: Expect the assignment to be built on a dashboard plus story, with a choice between Power BI and Tableau. A sample data set is published shortly after this session, so practicing the story flow on it is the recommended preparation.

Recap + bridge: the class covered matplotlib's foundation — installation, pyplot, the three-layer architecture, and one-line control of plots, markers, lines, labels, fonts, grids, and subplots — with the tools still ahead on richness and interactivity. The next session goes deeper: scatter plots, bar charts, then CSV loading and interactivity. And the assignment waits: a dashboard and story, Power BI or Tableau, sample data within one or two days.

Exam Guidance Summary

  • The upcoming assignment is hands-on: build a dashboard and a story from a sample data set. An option between Power BI and Tableau is planned; Python is accepted only if you are confident enough to build a story flow in it, and that is harder — the story and its flow are what the assignment will be judged on. The sample data arrives within one to two days of this session.
  • Calculated fields: know how to create one (top menu or Analysis menu), how the dialog validates the formula, and how to identify one by the equals-plus-hash icon.
  • Practice is the main requirement from the tool phase: drag-and-drop mechanics are simple but need repetition to become automatic.
  • For Python, remember the conceptual layer over the syntax: syntax will come and go, so be conceptually clear. Design principles from the tool phase (less clutter, coloring, pre-attentive attributes, making key elements bigger) apply to matplotlib charts too.
  • Know the tools-versus-Python comparison framework: technical skills, learning curve, customization, interactivity, data source connectivity, deployment and sharing, cost, and team collaboration.
  • Understand the plotting fundamentals shown in the demos: plt.plot(x, y) draws a line through the points; one array alone is treated as y with x auto-filled 0, 1, 2, ...; markers, line styles, colors, labels, titles, grids, and subplots are all one-line parameter changes.
  • For grids, be ready to justify the choice: avoid them unless the data is small and precise reading matters.

Key Industry Applications

  • Matplotlib in industry: a mature, open-source library (since about 2002) used by large companies and data scientists for publication-quality charts; outputs include screen, notebook, image, and PDF, so the same code feeds reports and papers. Its vector formats (SVG, PDF) keep figures sharp at any size, which is why scientific publications favor it.
  • Ecosystem: seaborn and bokeh are built on top of matplotlib; NumPy and Pandas handle the numbers that feed the charts — the standard data stack across industry data teams. Learning matplotlib is learning the foundation the other libraries stand on.
  • Google Colab: a free browser notebook where files live in Google Drive — a common way teams prototype charts and share them.
  • Anaconda and Jupyter notebooks: the default distribution/editor for Python data work, with packages preinstalled.
  • Tableau Public: real-time URL sharing of dashboards; Power BI and Tableau ship 50-plus data connectors (ODBC, JDBC — SQL, Oracle, SAP), which is why enterprises with many data sources standardize on tools rather than Python.
  • Python in products: Python libraries are embedded in web pages and applications for highly customized, interactive visuals; matplotlib itself powers everything from simple line charts in apps to 3D plots and multi-panel dashboards built with subplots.

DVI Lecture 12 notes · Matplotlib and Python for Data Visualization

Data Visualization and Interpretation· postgraduate· 2026-08-11

Sections Breakdown

112.1 Last Session Recap: Dashboards and Stories

The worksheet-to-dashboard-to-story pipeline, dashboard objects and actions, and story types from the tool phase.

212.2 Calculated Fields

Creating user-defined fields from formulas, validation, and the equals-plus-hash icon.

312.3 The Shift from Tools to Python

Why the course moves from drag-and-drop tools to Python, and the standing advice about syntax.

412.4 Data Visualization Tools vs. Python

The eight-dimension comparison between BI tools and Python libraries.

512.5 What Is Matplotlib

The foundational Python plotting library: definition, prerequisites, and facts and history.

612.6 Setting Up the Python Environment

Three ways to get started: plain Python, Anaconda, Google Colab; installing and checking the version.

712.7 Pyplot — the Plotting Interface

The pyplot submodule, the plt alias, matplotlib vs pyplot, and key features.

812.8 The Layered Architecture of Matplotlib

The scripting, artist, and backend layers and the benefits of separation.

912.9 Plotting with plt.plot

Basic plotting, many points, the one-array auto-x behavior, and why it matters.

1012.10 Markers

Marker shapes, size, edge and face colors, and the three ways to specify color.

1112.11 Controlling Lines

Line style, color and width, and multiple lines on one plot.

1212.12 Labels, Titles and Fonts

Setting labels and titles, and customizing fonts per element.

1312.13 Grids

Adding and tuning grids, and when to skip them.

1412.14 Subplots

Grid layouts with plt.subplot, worked layouts, titles and the dashboard analogy.

1512.15 Wrap-Up: What Comes Next

Where the class stopped, what comes next, and the assignment question.

16Exam Guidance Summary

The professor's consolidated exam guidance for the session.

17Key Industry Applications

Real-world uses of matplotlib and the Python data stack.

Postgraduate students in Data Visualization and Interpretation

Exam Revision Notes

Below is the distilled, exam-ready core. Every entry comes from the full explanation above. Use this section for rapid review; return to the main notes when a point needs more context.

Last Session Recap: Dashboards and Stories

Must-know: The three-level pipeline: worksheet (single view) → dashboard (several worksheets/objects on one screen) → story (dashboards sequenced into a narrative).

⚠️ Top pitfall: Using dashboards as dumping grounds; more worksheets does not mean more insight.

Self-check: Name the three dashboard action types and what each one does.

Connects to: 12.2 Calculated Fields, 12.14 Subplots

Calculated Fields

Must-know: Create a calculated field (top menu or Analysis menu), name it, combine existing fields with functions, let the dialog validate the formula, and recognize it by the equals-plus-hash icon.

⚠️ Top pitfall: Clicking through the 'formula contains errors' validation message, or confusing the plain-hash (imported) with the equals-plus-hash (calculated) field icon.

Self-check: If sales = 120 and profit = 25, what does a calculated field 'cost price = [sales] - [profit]' produce for that row?

Connects to: 12.1 Last Session Recap, 12.14 Subplots

The Shift from Tools to Python

Must-know: The shift to Python is a shift in control, not in design principles; syntax will come and go, so stay conceptually clear.

⚠️ Top pitfall: Getting emotional about syntax — mourning the exact spelling of commands instead of holding on to the concepts that transfer across tools and versions.

Self-check: What transfers unchanged from the tool phase into Python charts?

Connects to: 12.4 Data Visualization Tools vs. Python

Data Visualization Tools vs. Python

Must-know: The eight comparison dimensions and where each side wins: tools = learning curve, interactivity, connectivity, sharing, collaboration; Python = customization, cost.

⚠️ Top pitfall: Choosing on a single dimension (customization or cost alone) instead of the whole framework.

Self-check: Which side wins on interactivity and why?

Connects to: 12.3 The Shift from Tools to Python, 12.5 What Is Matplotlib

What Is Matplotlib

Must-know: Matplotlib: foundational Python visualization library, inspired by MATLAB, open source, mature since ~2002, static/animated/interactive outputs, many output formats (raster PNG/JPG vs vector PDF/SVG).

⚠️ Top pitfall: Starting to plot before mastering NumPy/Pandas — matplotlib draws numbers, so data handling skills come first.

Self-check: Which two libraries are built on top of matplotlib, and what are the two output format families?

Connects to: 12.4 Data Visualization Tools vs. Python, 12.6 Setting Up the Python Environment, 12.7 Pyplot — the Plotting Interface

Setting Up the Python Environment

Must-know: Setup routes: plain Python + pip install matplotlib; Anaconda with preinstalled packages and Jupyter; Colab in the browser. Verify with import matplotlib; print(matplotlib.__version__).

⚠️ Top pitfall: Skipping the version check — a successful install is proven only when import and print run without error.

Self-check: Which setup route ships NumPy and Matplotlib preinstalled?

Connects to: 12.5 What Is Matplotlib, 12.7 Pyplot — the Plotting Interface

Pyplot — the Plotting Interface

Must-know: from matplotlib import pyplot as plt is the standard import; plt is a consistent alias; pyplot is the easy interface to the deeper matplotlib API.

⚠️ Top pitfall: Calling plt functions before the import line runs, or mixing alias styles within one program.

Self-check: What does plt.ion() do?

Connects to: 12.5 What Is Matplotlib, 12.8 The Layered Architecture of Matplotlib, 12.9 Plotting with plt.plot

The Layered Architecture of Matplotlib

Must-know: Three layers: scripting (pyplot, easy), artist (figure/axes/ticks/labels/lines/legends), backend (rendering); separation of concerns = customization + extensibility.

⚠️ Top pitfall: Assuming customization is impossible because the scripting layer hides the internals — the artist layer is always reachable.

Self-check: Which layer renders the plot to screen or file?

Connects to: 12.7 Pyplot — the Plotting Interface, 12.9 Plotting with plt.plot

Plotting with plt.plot

Must-know: plt.plot(x, y) pairs arrays position by position into points and draws a line; one array alone is treated as y with auto x = 0, 1, 2, ...

⚠️ Top pitfall: Passing mismatched array lengths, or expecting a single array to respect your own x positions.

Self-check: With y = [3, 8, 1, 10, 5, 7] and no x given, what are the first two plotted points?

Connects to: 12.7 Pyplot — the Plotting Interface, 12.10 Markers, 12.11 Controlling Lines

Markers

Must-know: marker shapes ('o', '*', 'd'/'D' diamond, 's'), markersize, mec = marker edge color, mfc = marker face color; colors: single letter, hex code, named color.

⚠️ Top pitfall: Mixing up marker letters and color letters — 'b' is the color blue, not a marker shape.

Self-check: What do mec='r' and mfc='r' together do to a marker?

Connects to: 12.9 Plotting with plt.plot, 12.11 Controlling Lines

Controlling Lines

Must-know: linestyle ('dotted', 'dashed', etc.) changes how a line is drawn, color changes its color, linewidth its thickness; styles are per element and can be set programmatically.

⚠️ Top pitfall: Confusing linestyle with linewidth, or expecting styles to carry over between plot calls.

Self-check: Two plt.plot calls with no color argument — what colors do the two lines get?

Connects to: 12.9 Plotting with plt.plot, 12.10 Markers

Labels, Titles and Fonts

Must-know: plt.xlabel/plt.ylabel/plt.title add chart text; font dictionaries (family, color, size) give per-element fonts; loc='left' positions the title.

⚠️ Top pitfall: Applying one font to the whole chart, flattening the visual hierarchy between title and labels.

Self-check: How do you give the title a blue serif font at size 20?

Connects to: 12.9 Plotting with plt.plot, 12.11 Controlling Lines

Grids

Must-know: plt.grid() shows both-axis grid with automatic spacing; tune with axis, color, linestyle, linewidth; avoid grids unless the data is small and precise reading matters.

⚠️ Top pitfall: Adding grids by default — grid lines compete with the data on dense charts and add complexity rather than clarity.

Self-check: When can a grid be justified?

Connects to: 12.9 Plotting with plt.plot, 12.12 Labels, Titles and Fonts

Subplots

Must-know: plt.subplot(rows, columns, plot_number): first arg rows, second columns, third cell number counted left-to-right, top-to-bottom; suptitle sits above all subplot titles.

⚠️ Top pitfall: Swapping rows and columns, or numbering a cell outside rows × columns.

Self-check: In a 2x3 grid, which cell is subplot(2, 3, 4)?

Connects to: 12.1 Last Session Recap, 12.9 Plotting with plt.plot

Wrap-Up: What Comes Next

Must-know: Assignment = dashboard + story, option between Power BI and Tableau, sample data published within one to two days; Python is possible but the story flow favors a visualization tool.

⚠️ Top pitfall: Choosing Python for the assignment when the story and its flow — the judged part — are exactly where the tools do the work.

Self-check: What is the assignment judged on, and which tools are offered as the option?

Connects to: 12.1 Last Session Recap, 12.4 Data Visualization Tools vs. Python, 12.9 Plotting with plt.plot

Exam Guidance Summary

Must-know: The assignment is a dashboard + story with a Power BI/Tableau option; the story and its flow carry the grade, and sample data is published within one to two days.

⚠️ Top pitfall: Over-prioritizing Python syntax over the conceptual comparison framework and plotting fundamentals that the course tests.

Self-check: Name the eight dimensions of the tools-versus-Python comparison framework.

Connects to: 12.1 Last Session Recap, 12.4 Data Visualization Tools vs. Python, 12.9 Plotting with plt.plot

Key Industry Applications

Must-know: Matplotlib's vector outputs (SVG, PDF) keep figures sharp at any size, which is why scientific publications use it; the standard industry stack is NumPy/Pandas feeding matplotlib and its ecosystem.

⚠️ Top pitfall: Assuming enterprises pick Python over tools purely on capability — connectivity breadth (ODBC, JDBC, SQL, Oracle, SAP) and easy sharing often decide in favor of the tools.

Self-check: Why do scientific publications favor matplotlib's vector outputs?

Connects to: 12.4 Data Visualization Tools vs. Python, 12.5 What Is Matplotlib, 12.14 Subplots

Was this lecture useful?

Loading comments…
🤖

BitsNotes AI Assistant

Subject Notes Assistant

Configure AI Chat

Choose how to access the chatbot
Have your own API key?

Switch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.

🔑 Enter API key above to fetch live models from provider, or enter model name manually.
OpenAI-Compatible API Support

Choose any provider preset (Gemini, DeepSeek, Kimi, GLM, MiniMax, Qwen, OpenAI, Groq, Ollama, etc.) or enter a custom endpoint URL.

Security & Privacy First

Your API key is sent directly from your browser to your specified provider. BitsNotes servers never store or see your key.