Master Matplotlib From Scratch

Learn Matplotlib fundamentals, figure anatomy, basic plotting, chart customization, subplots, statistical visualizations, color mapping, annotations, 3D plotting, animations, and interactive visualizations through structured practical lessons.

COURSE SYLLABUS
1. Introduction & Environment Setup
What is Matplotlib? Installation Environment Setup Imports and Conventions
2. Core Figure Anatomy & Structures
Figure vs Axes Creating Canvas Dimensions and Resolution Saving Visuals
3. Basic Plotting
Line Plots Scatter Plots Bar Charts Histograms
4. Basic Visual Formatting & Labels
Titles and Labels Text Customization Legends Grid Lines
5. Advanced Plot Customization
Format Strings Line and Marker Styling Color Systems Transparency
6. Axis Control, Ticks & Limits
Axis Limits Custom Ticks Tick Labels Axis Scaling
7. Multi-Plot Layouts & Subplots
Basic Subplots Indexing Subplots Layout Tuning Advanced Grids
8. Advanced Statistical & Data-Specific Plots
Pie Charts Box and Whisker Plots Violin Plots Error Bars
9. Color Mapping & 2D Data Visualizations
Colormaps Heatmaps and Images Colorbars Contour Plots
10. Annotations & Shapes
Basic Text Smart Annotations Drawing Shapes Shading Areas
11. Customizing Styles & Themes
Built-in Styles Custom Style Sheets Global Configurations
12. Object-Oriented API vs Pyplot
Pyplot vs Object-Oriented API Transitioning Methods Dual Axis Plots
13. Deep Integration with Pandas & Seaborn
Pandas Plotting Backend Seaborn Overlays Passing Axes
14. 3D Plotting
3D Setup 3D Lines and Scatter Surface and Wireframes Camera View
15. Dynamic & Live Plots
Interactive Mode Animation Module Real-time Updates Exporting Animations
16. Performance Optimization & Interactive Backends
Plotting Speed Interactive Backends Event Handling

Color Systems in Matplotlib

Learn how Matplotlib represents colors using named colors, RGB, RGBA, hexadecimal values, color palettes, and colormaps. Understand how to select and apply colors to create meaningful and professional data visualizations.

1. Learning Objectives

After completing this lesson, you will be able to:

  • Understand color systems in Matplotlib.
  • Use predefined named colors.
  • Understand RGB and RGBA color models.
  • Apply hexadecimal color codes.
  • Use custom color combinations in charts.
  • Understand colormaps and their categories.
  • Apply sequential, diverging, and qualitative colormaps.
  • Use color palettes for multiple data series.
  • Choose suitable colors for data visualization.

2. Introduction to Color Systems

Colors are an important part of data visualization. They help users identify different data series, compare values, highlight important information, and understand patterns in charts.

Matplotlib supports multiple ways to specify colors. You can use simple color names, shorthand characters, RGB values, RGBA values, hexadecimal codes, and predefined colormaps.

Why Are Color Systems Important?

Consider a chart that displays sales for five different products. If every line uses the same color, it becomes difficult to identify individual products. Different colors make the chart easier to understand.

Common Color Systems

Color System Description
Named Colors Uses predefined color names such as red, blue, and green.
RGB Defines colors using red, green, and blue components.
RGBA Uses red, green, blue, and alpha transparency.
Hexadecimal Represents colors using hexadecimal notation.
Colormaps Maps numerical values to colors.

3. Using Named Colors

Matplotlib supports many predefined color names. You can directly pass a color name to the color parameter when creating a plot.

Common Named Colors

red blue green yellow purple orange cyan pink gray brown

Examples of named colors available in Matplotlib.

Example: Using Named Colors

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

plt.plot(x, [10, 20, 30, 40, 50],
         color="red", label="Red")

plt.plot(x, [15, 25, 35, 45, 55],
         color="blue", label="Blue")

plt.plot(x, [20, 30, 40, 50, 60],
         color="green", label="Green")

plt.title("Named Colors Example")
plt.xlabel("X Values")
plt.ylabel("Y Values")

plt.legend()
plt.show()

Expected Output

Chart Title: Named Colors Example

Three Lines:
Red Line
Blue Line
Green Line

Legend:
Red
Blue
Green
Tip: Named colors are easy to read and remember. Use them when you do not need an exact custom color.

4. RGB Color System

RGB stands for Red, Green, and Blue. It is a color model that creates different colors by combining these three components.

In Matplotlib, RGB colors can be represented using a tuple of three values. Each value normally ranges from 0 to 1.

RGB Color Structure

Red Green Blue RGB (Red, Green, Blue) Each component ranges from 0 to 1.

RGB colors are created by combining red, green, and blue components.

RGB Value Examples

RGB Tuple Color
(1, 0, 0) Red
(0, 1, 0) Green
(0, 0, 1) Blue
(1, 1, 0) Yellow
(1, 1, 1) White
(0, 0, 0) Black
(0.5, 0.5, 0.5) Gray

Example: RGB Colors in Matplotlib

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

red_color = (1, 0, 0)
green_color = (0, 1, 0)
blue_color = (0, 0, 1)

plt.plot(x, [10, 20, 30, 40, 50],
         color=red_color, label="RGB Red")

plt.plot(x, [15, 25, 35, 45, 55],
         color=green_color, label="RGB Green")

plt.plot(x, [20, 30, 40, 50, 60],
         color=blue_color, label="RGB Blue")

plt.title("RGB Color Example")
plt.legend()

plt.show()

Expected Output

Chart Title: RGB Color Example

Data Series:
1. Red using (1, 0, 0)
2. Green using (0, 1, 0)
3. Blue using (0, 0, 1)

Three colored lines are displayed
with their respective legend entries.
Tip: RGB values in Matplotlib generally use floating-point numbers between 0 and 1, not integer values between 0 and 255.

5. RGBA Color System

RGBA stands for Red, Green, Blue, and Alpha. It extends the RGB color system by adding an alpha component that controls transparency.

The first three values define the color. The fourth value controls how transparent or opaque that color appears.

RGBA Structure

color = (red, green, blue, alpha)
Component Purpose Range
Red Red color intensity. 0 to 1
Green Green color intensity. 0 to 1
Blue Blue color intensity. 0 to 1
Alpha Transparency level. 0 to 1

Alpha Value Reference

Alpha 0.0 Alpha 0.25 Alpha 0.5 Alpha 1.0 Transparent Light Medium Opaque

Alpha determines the transparency of an RGBA color.

Example: RGBA Color

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

transparent_red = (1, 0, 0, 0.3)
opaque_blue = (0, 0, 1, 1)

plt.plot(
    x,
    [10, 20, 30, 40, 50],
    color=transparent_red,
    linewidth=5,
    label="Transparent Red"
)

plt.plot(
    x,
    [15, 25, 35, 45, 55],
    color=opaque_blue,
    linewidth=5,
    label="Opaque Blue"
)

plt.title("RGBA Color Example")
plt.legend()

plt.show()

Expected Output

Chart Title: RGBA Color Example

First Line:
Red with alpha 0.3.

Second Line:
Blue with alpha 1.0.

The red line appears transparent,
while the blue line appears opaque.

6. Hexadecimal Color Codes

Hexadecimal color codes are another way to specify colors in Matplotlib. A hexadecimal color code begins with the # symbol and contains six hexadecimal digits.

The six digits represent three color components: red, green, and blue.

Hexadecimal Structure

Hex Color: #FF5733 FF 57 33 Red Green Blue

A six-digit hexadecimal color code contains red, green, and blue components.

Common Hexadecimal Colors

Hex Code Color
#FF0000Red
#00FF00Green
#0000FFBlue
#FFFF00Yellow
#000000Black
#FFFFFFWhite
#FF5733Orange-red
#800080Purple

Example: Using Hexadecimal Colors

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]

plt.plot(
    x,
    [10, 20, 30, 40, 50],
    color="#FF5733",
    linewidth=3,
    label="Orange Red"
)

plt.plot(
    x,
    [15, 25, 35, 45, 55],
    color="#800080",
    linewidth=3,
    label="Purple"
)

plt.title("Hexadecimal Color Example")
plt.legend()

plt.show()

Expected Output

Chart Title: Hexadecimal Color Example

First Line:
Hex Color #FF5733

Second Line:
Hex Color #800080

Legend:
Orange Red
Purple
Tip: Hexadecimal codes are useful when you need to match exact brand colors or predefined design colors.

7. Working with Color Palettes

A color palette is a collection of colors selected to work together. Color palettes are useful when a chart contains multiple categories or data series.

You can create your own palette using a Python list and apply each color to a different data series.

Example: Custom Color Palette

import matplotlib.pyplot as plt

colors = [
    "#2563EB",
    "#16A34A",
    "#F97316",
    "#A855F7",
    "#DC2626"
]

months = [1, 2, 3, 4, 5]

data = [
    [10, 20, 30, 40, 50],
    [15, 25, 35, 45, 55],
    [20, 30, 40, 50, 60],
    [25, 35, 45, 55, 65],
    [30, 40, 50, 60, 70]
]

for i, values in enumerate(data):
    plt.plot(
        months,
        values,
        color=colors[i],
        label=f"Series {i + 1}"
    )

plt.title("Custom Color Palette")
plt.xlabel("Month")
plt.ylabel("Values")

plt.legend()
plt.show()

Expected Output

Chart Title: Custom Color Palette

Five Data Series:
Series 1: Blue
Series 2: Green
Series 3: Orange
Series 4: Purple
Series 5: Red

Each series uses a different palette color.
Tip: Choose colors with sufficient contrast so that different data series remain easy to identify.

8. Introduction to Colormaps

A colormap is a predefined mapping between numerical values and colors. It allows Matplotlib to represent different numerical values using different colors.

Colormaps are especially useful for heatmaps, images, scatter plots, contour plots, and other visualizations involving continuous numerical values.

How Colormaps Work

Numerical Values to Colors Low 25% Medium 75% High

A continuous colormap assigns colors to different numerical values.

Common Matplotlib Colormaps

Colormap Description
viridisDark purple through green to yellow.
plasmaDark purple through pink to yellow.
infernoDark colors progressing to bright yellow.
magmaDark purple progressing to light colors.
cividisBlue to yellow, designed for accessibility.
coolwarmBlue to neutral to red.
GreysGrayscale color mapping.
turboHigh-contrast multicolor mapping.

9. Categories of Colormaps

Matplotlib provides different categories of colormaps. Choosing the correct category depends on the type of information you want to communicate.

9.1 Sequential Colormaps

Sequential colormaps are used when numerical data moves from low values to high values. The colors generally progress from lighter to darker or darker to lighter.

Examples: viridis, plasma, inferno, magma.

Low Values High Values

Sequential color progression.

9.2 Diverging Colormaps

Diverging colormaps are useful when data contains a meaningful central value, such as zero or an average. Colors move away from a central neutral color in two different directions.

Examples: coolwarm, RdBu, seismic.

Low Center High

Diverging colors with a central reference value.

9.3 Qualitative Colormaps

Qualitative colormaps are used to represent different categories or groups. Each category receives a distinct color rather than representing a numerical progression.

Examples: tab10, tab20, Set1, Pastel1.

Different colors represent different categories.

Qualitative colors for separate categories.

10. Using Colormaps in Scatter Plots

Colormaps can be applied to scatter plots using the c parameter and the cmap parameter. The c parameter supplies values used to determine the colors of individual points.

Example: Scatter Plot with Colormap

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5, 6, 7, 8]
y = [10, 15, 13, 20, 25, 22, 30, 35]

values = [10, 20, 30, 40, 50, 60, 70, 80]

scatter = plt.scatter(
    x,
    y,
    c=values,
    cmap="viridis",
    s=100
)

plt.colorbar(scatter, label="Data Values")

plt.title("Scatter Plot with Colormap")
plt.xlabel("X Values")
plt.ylabel("Y Values")

plt.show()

Expected Output

Chart Title: Scatter Plot with Colormap

Plot Type:
Scatter Plot

Markers:
Eight data points.

Colormap:
viridis

Colorbar:
Displays the numerical color scale.

Point Colors:
Different colors represent different data values.
Tip: Use a colorbar when a colormap represents numerical values. It helps users understand what each color means.

11. Applying Colormaps to Image Data

Matplotlib's imshow() function displays image-like two-dimensional data. You can apply a colormap to represent the numerical values in the data using different colors.

Example: Displaying Data with a Colormap

import matplotlib.pyplot as plt
import numpy as np

data = np.array([
    [10, 20, 30, 40],
    [20, 30, 40, 50],
    [30, 40, 50, 60],
    [40, 50, 60, 70]
])

image = plt.imshow(
    data,
    cmap="plasma"
)

plt.colorbar(image, label="Values")

plt.title("Colormap Image Example")

plt.show()

Expected Output

Chart Title: Colormap Image Example

Image:
A 4 x 4 numerical data grid.

Colormap:
plasma

Colorbar:
Displays the numerical value range.

Each cell receives a color based on its value.

12. Listing Available Colormaps

Matplotlib provides many built-in colormaps. You can access available colormap names through plt.colormaps.

Example

import matplotlib.pyplot as plt

available_colormaps = plt.colormaps()

print("Available Colormaps:")

for cmap in available_colormaps:
    print(cmap)

Expected Output

Available Colormaps:

magma
inferno
plasma
viridis
cividis
twilight
twilight_shifted
turbo
coolwarm
bwr
seismic
Greys
Blues
Greens
Reds
Purples
Oranges
...

The complete list depends on the
installed Matplotlib version.
Tip: Use plt.colormaps() to inspect available colormap names in your installed version of Matplotlib.

13. Reversing a Colormap

Matplotlib supports reversed versions of built-in colormaps. You can reverse a colormap by adding _r to its name.

Example

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
values = [10, 20, 30, 40, 50]

plt.scatter(
    x,
    y,
    c=values,
    cmap="viridis_r",
    s=150
)

plt.colorbar(label="Values")

plt.title("Reversed Viridis Colormap")

plt.show()

Expected Output

Chart Title: Reversed Viridis Colormap

Plot Type:
Scatter Plot

Colormap:
viridis_r

Color Mapping:
The original viridis color sequence
is displayed in reverse order.

14. Practical Activity

Task: Create a Student Performance Visualization

Create a scatter plot to represent student performance using marks as numerical values.

Given Data:

students = [1, 2, 3, 4, 5, 6, 7, 8]

marks = [45, 55, 60, 70, 75, 80, 90, 95]

Requirements:

  • Create a scatter plot using the student data.
  • Use marks as the color values.
  • Apply the viridis colormap.
  • Set marker size to 150.
  • Add a colorbar with the label Student Marks.
  • Add a meaningful chart title.
  • Add X-axis and Y-axis labels.
  • Display the chart using plt.show().

15. Practice Questions

  1. What is a color system in Matplotlib?
  2. What is the RGB color model?
  3. What is the difference between RGB and RGBA?
  4. What does the alpha component represent?
  5. How do you specify a hexadecimal color?
  6. What is a color palette?
  7. What is a colormap?
  8. What is the difference between sequential and diverging colormaps?
  9. When should qualitative colormaps be used?
  10. What is the purpose of the cmap parameter?
  11. How do you display a colorbar?
  12. How can you reverse a built-in colormap?
  13. Which function lists available Matplotlib colormaps?

Summary

In this lesson, you learned how Matplotlib uses different color systems to customize data visualizations. You explored named colors, RGB values, RGBA transparency, and hexadecimal color codes to define exact colors for plotted data.

You also learned how to create custom color palettes and apply different colormaps to scatter plots and image data. Sequential colormaps are useful for numerical progressions, diverging colormaps help highlight values around a central reference, and qualitative colormaps distinguish separate categories.

Finally, you explored how to display colorbars, list available colormaps, and reverse a colormap using the _r suffix. These techniques help create informative, readable, and professional Matplotlib visualizations.