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

Format Strings in Matplotlib

Learn how to customize plot appearance using format strings. Understand colors, markers, line styles, shorthand notation, and how to combine them to create clear and attractive charts.

1. Learning Objectives

After completing this lesson, you will be able to:

  • Understand format strings in Matplotlib.
  • Learn the structure of a format string.
  • Customize line colors using shorthand characters.
  • Choose different marker styles.
  • Apply different line styles.
  • Combine color, marker, and line style in one format string.
  • Use format strings with multiple data series.
  • Understand the difference between format strings and keyword arguments.

2. Introduction to Format Strings

Matplotlib provides format strings to customize the appearance of plotted data. A format string is a short notation that can specify the color, marker style, and line style of a plot.

Instead of writing separate parameters for every property, you can combine them into a single string.

Example

plt.plot(x, y, "ro--")

This format string represents:

  • r - Red color.
  • o - Circular markers.
  • -- - Dashed line.

Basic Syntax

plt.plot(x, y, fmt)

Where:

  • x represents X-axis data.
  • y represents Y-axis data.
  • fmt represents the format string.

3. Structure of a Format String

A Matplotlib format string can contain three main components: color, marker, and line style.

Format String Structure r + o + -- Color Marker Line Style Example: "ro--"

A format string combines color, marker, and line style.

Example

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]

plt.plot(x, y, "ro--")

plt.show()

Expected Output

Plot Appearance:

Color       : Red
Marker      : Circle
Line Style  : Dashed

The chart displays a red dashed line
with circular markers.
Tip: Format strings are optional. You can also customize colors, markers, and line styles using separate keyword arguments.

4. Color Codes in Format Strings

Matplotlib supports shorthand color characters that can be included in format strings.

Character Color Full Color Name
bBlueblue
gGreengreen
rRedred
cCyancyan
mMagentamagenta
yYellowyellow
kBlackblack
wWhitewhite

Color Reference

b Blue g Green r Red c Cyan m Magenta y Yellow k Black w White

Common shorthand color characters supported by Matplotlib.

Example: Using Different Colors

import matplotlib.pyplot as plt

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

plt.plot(x, [10, 20, 30, 40, 50], "r", label="Red")
plt.plot(x, [15, 25, 35, 45, 55], "g", label="Green")
plt.plot(x, [20, 30, 40, 50, 60], "b", label="Blue")

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

plt.legend()
plt.show()

Expected Output

Chart Title: Different Colors

Three Lines:
1. Red Line
2. Green Line
3. Blue Line

Legend:
Red
Green
Blue

5. Marker Styles in Format Strings

Markers are symbols used to identify individual data points on a plot. Matplotlib provides several marker styles.

Marker Symbol Description
oCircleCircular marker.
sSquareSquare marker.
^Triangle UpUpward-pointing triangle.
vTriangle DownDownward-pointing triangle.
DDiamondDiamond-shaped marker.
*StarStar-shaped marker.
+PlusPlus-shaped marker.
xCrossX-shaped marker.
.PointSmall point marker.
pPentagonPentagon-shaped marker.

Marker Reference Diagram

o - Circle s - Square ^ - Triangle v - Down D - Diamond * - Star x - Cross + - Plus x - Cross . - Point p - Pentagon

Common marker shapes used to represent data points.

Example: Different Markers

import matplotlib.pyplot as plt

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

plt.plot(x, [10, 20, 30, 40, 50], "bo", label="Circle")
plt.plot(x, [15, 25, 35, 45, 55], "gs", label="Square")
plt.plot(x, [20, 30, 40, 50, 60], "r^", label="Triangle")

plt.title("Different Marker Styles")
plt.legend()

plt.show()

Expected Output

Chart Title: Different Marker Styles

Data Series:
1. Blue circular markers
2. Green square markers
3. Red triangle markers

Legend:
Circle
Square
Triangle

6. Line Styles in Format Strings

Line styles define how the connecting line between data points appears in a chart.

Format Line Style Description
- Solid Continuous line.
-- Dashed Line made of dashes.
-. Dash-dot Combination of dashes and dots.
: Dotted Line made of dots.

Line Style Reference Diagram

Solid (-) Dashed (--) Dash-dot (-.) Dotted (:)

Visual comparison of common Matplotlib line styles.

Example: Multiple Line Styles

import matplotlib.pyplot as plt

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

plt.plot(x, [10, 20, 30, 40, 50], "b-", label="Solid")
plt.plot(x, [15, 25, 35, 45, 55], "r--", label="Dashed")
plt.plot(x, [20, 30, 40, 50, 60], "g-.", label="Dash Dot")
plt.plot(x, [25, 35, 45, 55, 65], "m:", label="Dotted")

plt.title("Different Line Styles")
plt.legend()

plt.show()

Expected Output

Chart Title: Different Line Styles

Four data series:
1. Blue solid line
2. Red dashed line
3. Green dash-dot line
4. Magenta dotted line

Legend:
Solid
Dashed
Dash Dot
Dotted

7. Combining Color, Marker, and Line Style

The main advantage of format strings is that you can combine different visual properties into one short string.

Format String Examples

Format String Color Marker Line Style
ro- Red Circle Solid
bs-- Blue Square Dashed
g^: Green Triangle Dotted
mD-. Magenta Diamond Dash-dot
k*- Black Star Solid

Example: Combined Format Strings

import matplotlib.pyplot as plt

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

y1 = [10, 20, 30, 40, 50]
y2 = [15, 25, 35, 45, 55]
y3 = [20, 30, 40, 50, 60]
y4 = [25, 35, 45, 55, 65]

plt.plot(x, y1, "ro-", label="Red Circle")
plt.plot(x, y2, "bs--", label="Blue Square")
plt.plot(x, y3, "g^:", label="Green Triangle")
plt.plot(x, y4, "mD-.", label="Magenta Diamond")

plt.title("Combined Format Strings")
plt.xlabel("X Values")
plt.ylabel("Y Values")

plt.legend()
plt.grid(True)

plt.show()

Expected Output

Chart Title: Combined Format Strings

Data Series:
1. Red solid line with circular markers
2. Blue dashed line with square markers
3. Green dotted line with triangle markers
4. Magenta dash-dot line with diamond markers

Legend:
Red Circle
Blue Square
Green Triangle
Magenta Diamond
Tip: Choose different combinations for each data series so users can distinguish them easily.

8. Format Strings vs Keyword Arguments

Format strings are a compact way to specify common plot styles. However, Matplotlib also allows you to set these properties separately using keyword arguments.

Using a Format String

plt.plot(x, y, "ro--")

Using Keyword Arguments

plt.plot(
    x,
    y,
    color="red",
    marker="o",
    linestyle="--"
)

Comparison

Format Strings Keyword Arguments
Short and compact. More descriptive.
Useful for simple combinations. Useful for detailed customization.
Uses shorthand characters. Uses named parameters.
Less flexible for advanced styling. Supports additional styling options.
Important: Avoid specifying conflicting values for the same property in a format string and keyword arguments. For example, do not combine a red color code in the format string with a separate blue color argument.

9. Format Strings with Multiple Data Series

You can use different format strings for each data series in the same chart. This is useful when comparing multiple groups, products, or measurements.

Example: Student Marks Comparison

import matplotlib.pyplot as plt

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

student_a = [85, 90, 78, 92, 88]
student_b = [75, 82, 80, 85, 90]
student_c = [90, 88, 92, 86, 95]

plt.plot(subjects, student_a, "ro-", label="Student A")
plt.plot(subjects, student_b, "bs--", label="Student B")
plt.plot(subjects, student_c, "g^:", label="Student C")

plt.title("Student Marks Comparison")
plt.xlabel("Subject Number")
plt.ylabel("Marks")

plt.legend()
plt.grid(True)

plt.show()

Expected Output

Chart Title: Student Marks Comparison

Three Student Series:

Student A:
Red solid line with circle markers.

Student B:
Blue dashed line with square markers.

Student C:
Green dotted line with triangle markers.

Legend:
Student A
Student B
Student C

10. Practical Activity

Task: Create a Product Sales Comparison Chart

Create a chart to compare the sales of three products across five months.

Given Data:

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

laptop = [100, 120, 150, 170, 200]
mobile = [80, 110, 130, 160, 180]
tablet = [50, 70, 90, 110, 140]

Requirements:

  • Create three line plots.
  • Use red circle markers for Laptop.
  • Use blue square markers for Mobile.
  • Use green triangle markers for Tablet.
  • Use different line styles.
  • Add a title and axis labels.
  • Display a legend.
  • Enable grid lines.

11. Practice Questions

  1. What is a format string in Matplotlib?
  2. What are the three main components of a format string?
  3. What does the character r represent?
  4. Which marker character represents a circle?
  5. Which symbol represents a dashed line?
  6. What is the meaning of the format string ro--?
  7. How do you create a blue line with square markers?
  8. What is the difference between format strings and keyword arguments?
  9. Can you use different format strings for multiple data series?
  10. Why are format strings useful in Matplotlib?

Summary

In this lesson, you learned how to use Matplotlib format strings to customize the appearance of charts. You explored color shorthand, marker symbols, line styles, and combinations of these properties.

  • Format strings provide a compact way to style plots.
  • Color characters define the line or marker color.
  • Marker symbols identify individual data points.
  • Line styles control the appearance of connecting lines.
  • Multiple style properties can be combined in one string.
  • Keyword arguments provide more descriptive customization.
  • Different format strings can distinguish multiple data series.

You are now ready to customize Matplotlib plots using format strings. In the next lesson, you will learn more advanced line and marker styling techniques.