0% found this document useful (0 votes)
8 views27 pages

Matplotlib Plot Types Explained

The document provides an overview of various plot types available in Matplotlib for data visualization, including line graphs, scatter plots, bar charts, histograms, and more. It also covers creating multiple subplots, adjusting spacing, sharing axes, and advanced customization techniques for enhancing plot readability and aesthetics. Each section includes code examples to illustrate the implementation of these plotting techniques.

Uploaded by

Adetola Olamide
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views27 pages

Matplotlib Plot Types Explained

The document provides an overview of various plot types available in Matplotlib for data visualization, including line graphs, scatter plots, bar charts, histograms, and more. It also covers creating multiple subplots, adjusting spacing, sharing axes, and advanced customization techniques for enhancing plot readability and aesthetics. Each section includes code examples to illustrate the implementation of these plotting techniques.

Uploaded by

Adetola Olamide
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Matplotlib for Data Visualization

- Part 2
Type Data science masterclass

IV. Types of Plots in Matplotlib


Matplotlib provides a variety of plots to visualize different types of data. Each plot
type is suited for specific use cases, from trend analysis (line plots) to
distribution visualization (histograms & KDE plots).

4.1 Line Graphs


Use Case:

Best for visualizing trends over time or continuous data.

import [Link] as plt

x = [1, 2, 3, 4, 5]
y = [10, 12, 8, 15, 10]

[Link](x, y, marker="o", linestyle="-", color="b", label="Line Graph")


[Link]("X-axis")
[Link]("Y-axis")
[Link]("Line Plot Example")
[Link]()
[Link]()

Line Plot Output:

Matplotlib for Data Visualization - Part 2 1


4.2 Scatter Plots
Use Case:

Used to show relationships between two numerical variables.

import numpy as np

x = [Link](50) * 10
y = [Link](50) * 10

[Link](x, y, color="red", marker="o", alpha=0.7)


[Link]("X-axis")
[Link]("Y-axis")
[Link]("Scatter Plot Example")
[Link]()

Scatter Plot Output:

Matplotlib for Data Visualization - Part 2 2


4.3 Bar Charts (Vertical & Horizontal)
Use Case:

Ideal for comparing categorical data.

Vertical Bar Chart

categories = ["A", "B", "C", "D"]


values = [10, 20, 15, 25]

[Link](categories, values, color="green")


[Link]("Categories")
[Link]("Values")
[Link]("Vertical Bar Chart")
[Link]()

Matplotlib for Data Visualization - Part 2 3


Horizontal Bar Chart

[Link](categories, values, color="purple")


[Link]("Values")
[Link]("Categories")
[Link]("Horizontal Bar Chart")
[Link]()

Bar Chart Output:

4.4 Histograms & KDE Plots


Use Case:

Matplotlib for Data Visualization - Part 2 4


Shows the distribution of numerical data.

Histogram

data = [Link](1000)

[Link](data, bins=30, color="blue", alpha=0.7, edgecolor="black")


[Link]("Value")
[Link]("Frequency")
[Link]("Histogram Example")
[Link]()

Kernel Density Estimation (KDE) Plot

import seaborn as sns

[Link](data, shade=True, color="red")


[Link]("Value")
[Link]("Density")
[Link]("KDE Plot Example")
[Link]()

Matplotlib for Data Visualization - Part 2 5


Histogram & KDE Plot Output:

4.5 Box Plots & Violin Plots


Use Case:

Box Plots: Show distribution, outliers, and quartiles.

Violin Plots: Show density in addition to quartiles.

Box Plot

data = [[Link](100) for _ in range(3)]

[Link](data, patch_artist=True, vert=True, labels=["A", "B", "C"])


[Link]("Categories")
[Link]("Values")
[Link]("Box Plot Example")
[Link]()

Matplotlib for Data Visualization - Part 2 6


Violin Plot

[Link](data=data)
[Link]("Categories")
[Link]("Values")
[Link]("Violin Plot Example")
[Link]()

Box Plot & Violin Plot Output:

4.6 Pie Charts & Donut Charts


Use Case:

Matplotlib for Data Visualization - Part 2 7


Used for percentage-based comparisons.

Pie Chart

labels = ["A", "B", "C", "D"]


sizes = [30, 20, 25, 25]

[Link](sizes, labels=labels, autopct="%1.1f%%", colors=["blue", "green", "re


d", "orange"])
[Link]("Pie Chart Example")
[Link]()

Donut Chart (Modified Pie Chart)

[Link](sizes, labels=labels, autopct="%1.1f%%", colors=["blue", "green", "re


d", "orange"], wedgeprops={"edgecolor": "white"})
[Link]().add_artist([Link]((0,0),0.6,fc='white')) # Adding a circle in the mid
dle
[Link]("Donut Chart Example")
[Link]()

Matplotlib for Data Visualization - Part 2 8


4.7 Area Plots & Stack Plots
Use Case:

Show cumulative values across categories or time.

Area Plot

x = [Link](1, 6)
y1 = [Link]([3, 6, 9, 12, 15])
y2 = [Link]([2, 4, 6, 8, 10])

plt.fill_between(x, y1, color="blue", alpha=0.4, label="Series 1")


plt.fill_between(x, y2, color="red", alpha=0.4, label="Series 2")
[Link]("X-axis")
[Link]("Values")
[Link]("Area Plot Example")
[Link]()
[Link]()

Matplotlib for Data Visualization - Part 2 9


Stacked Plot

[Link](x, y1, y2, colors=["blue", "red"], labels=["Series 1", "Series 2"])


[Link]("X-axis")
[Link]("Values")
[Link]("Stacked Area Plot Example")
[Link]()
[Link]()

4.8 Stem & Step Plots


Use Case:

Matplotlib for Data Visualization - Part 2 10


Stem Plots: Show individual data points, often used for discrete signals.

Step Plots: Show changes in a stepwise fashion, useful for discrete events.

Stem Plot

[Link](x, y1, linefmt="r-", markerfmt="ro", basefmt="k-")


[Link]("X-axis")
[Link]("Values")
[Link]("Stem Plot Example")
[Link]()

Step Plot

[Link](x, y1, where="mid", color="blue", label="Step Plot")


[Link]("X-axis")
[Link]("Values")
[Link]("Step Plot Example")
[Link]()
[Link]()

Matplotlib for Data Visualization - Part 2 11


V. Working with Multiple Plots
Matplotlib provides multiple ways to create multi-panel visualizations to compare
datasets effectively. The most commonly used approaches include:

1. [Link]() – Simple subplot creation.

2. [Link]() – Flexible figure and axes handling.

3. GridSpec & subplot2grid() – Advanced layout control.

5.1 Creating Multiple Subplots ( [Link] vs.


[Link] )

Using [Link]() (Single Figure, Indexed Subplots)


: Creates a grid of plots with
[Link](nrows, ncols, index) index referring to the
current subplot position.

import [Link] as plt


import numpy as np

x = [Link](0, 10, 100)

Matplotlib for Data Visualization - Part 2 12


y1, y2, y3 = [Link](x), [Link](x), [Link](x)

[Link](figsize=(8, 6))

[Link](3, 1, 1) # 3 rows, 1 column, 1st subplot


[Link](x, y1, color="blue")
[Link]("Sine Function")

[Link](3, 1, 2) # 3 rows, 1 column, 2nd subplot


[Link](x, y2, color="red")
[Link]("Cosine Function")

[Link](3, 1, 3) # 3 rows, 1 column, 3rd subplot


[Link](x, y3, color="green")
[Link]("Tangent Function")

plt.tight_layout() # Adjust spacing


[Link]()

Using [Link]() (More Control, Returns Figure & Axes)


[Link](nrows, ncols) : Returns a figure object and an array of axes.

Matplotlib for Data Visualization - Part 2 13


fig, axes = [Link](2, 2, figsize=(8, 6))

x = [Link](0, 10, 100)


axes[0, 0].plot(x, [Link](x), color="blue")
axes[0, 0].set_title("Sine")

axes[0, 1].plot(x, [Link](x), color="red")


axes[0, 1].set_title("Cosine")

axes[1, 0].plot(x, [Link](x), color="green")


axes[1, 0].set_title("Tangent")

axes[1, 1].plot(x, [Link](x/5), color="purple")


axes[1, 1].set_title("Exponential")

plt.tight_layout() # Adjusts spacing


[Link]()

5.2 Adjusting Spacing Between Subplots


When creating multiple subplots, the default layout might overlap. Use
plt.tight_layout() or fig.subplots_adjust() to fix spacing.

Matplotlib for Data Visualization - Part 2 14


Using plt.tight_layout() (Automatic Adjustment)

fig, axes = [Link](2, 2, figsize=(8, 6))


for ax in [Link]:
[Link](x, [Link](x))
plt.tight_layout()
[Link]()

Using subplots_adjust() (Manual Control)

fig, axes = [Link](2, 2, figsize=(8, 6))


plt.subplots_adjust(wspace=0.4, hspace=0.4) # Adjust horizontal and vertical
space
[Link]()

Matplotlib for Data Visualization - Part 2 15


5.3 Sharing Axes Across Subplots
When plotting related data, it is often useful to share X or Y axes.

Sharing X-Axis

fig, axes = [Link](2, 1, sharex=True, figsize=(8, 6))


axes[0].plot(x, [Link](x), color="blue")
axes[0].set_title("Sine Function")

axes[1].plot(x, [Link](x), color="red")


axes[1].set_title("Cosine Function")

[Link]()

Matplotlib for Data Visualization - Part 2 16


Sharing Y-Axis

fig, axes = [Link](1, 2, sharey=True, figsize=(8, 6))


axes[0].plot(x, [Link](x), color="blue")
axes[0].set_title("Sine Function")

axes[1].plot(x, [Link](x) * 2, color="red")


axes[1].set_title("Scaled Sine Function")

[Link]()

Matplotlib for Data Visualization - Part 2 17


5.4 Different Layouts (GridSpec & subplot2grid )
Using GridSpec (Advanced Grid Control)
Allows creating asymmetrical or custom-sized subplots.

import [Link] as gridspec

fig = [Link](figsize=(8, 6))


gs = [Link](2, 2, width_ratios=[1, 2], height_ratios=[2, 1])

ax1 = [Link](gs[0, 0]) # Row 0, Col 0


ax2 = [Link](gs[0, 1]) # Row 0, Col 1
ax3 = [Link](gs[1, :]) # Row 1, spans both columns

[Link](x, [Link](x))
[Link](x, [Link](x))
[Link](x, [Link](x))

plt.tight_layout()
[Link]()

Using subplot2grid() (Manually Place Subplots)

Matplotlib for Data Visualization - Part 2 18


fig = [Link](figsize=(8, 6))

ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=2) # Top row, spans 2 columns
ax2 = plt.subplot2grid((3, 3), (0, 2)) # Top right
ax3 = plt.subplot2grid((3, 3), (1, 0), rowspan=2) # Bottom left, spans 2 rows
ax4 = plt.subplot2grid((3, 3), (1, 1), colspan=2, rowspan=2) # Bottom right

[Link](x, [Link](x))
[Link](x, [Link](x))
[Link](x, [Link](x))
[Link](x, [Link](x / 5))

plt.tight_layout()
[Link]()

VI. Advanced Plot Customization


Customizing plots is essential for clear, informative, and visually appealing data
visualizations. This section covers advanced customization techniques like

Matplotlib for Data Visualization - Part 2 19


modifying legends, adding arrows, customizing fonts, working with date/time
data, and changing themes.

6.1 Customizing Legends


A well-positioned and formatted legend makes a plot more readable. Matplotlib
provides extensive customization options using [Link]() .

Basic Legend

import [Link] as plt


import numpy as np

x = [Link](0, 10, 100)


y1, y2 = [Link](x), [Link](x)

[Link](x, y1, label="Sine Wave", color="blue")


[Link](x, y2, label="Cosine Wave", color="red")

[Link]() # Default placement


[Link]("Basic Legend")
[Link]()

Matplotlib for Data Visualization - Part 2 20


Customizing Legend Position
loc parameter controls placement (e.g., 'upper left' , 'lower right' ).

bbox_to_anchor fine-tunes the position.

frameon=False removes the legend box.

[Link](x, y1, label="Sine Wave", color="blue")


[Link](x, y2, label="Cosine Wave", color="red")

[Link](loc="upper right", bbox_to_anchor=(1, 1), fontsize=12, frameon=Fal


se)
[Link]("Customized Legend Position")
[Link]()

6.2 Adding Arrows & Shapes


Annotations such as arrows and shapes help highlight important points.

Adding Arrows ( [Link]() )

[Link](x, y1, label="Sine Wave", color="blue")


[Link](3, 0, 1, 0.5, head_width=0.1, head_length=0.2, fc="black", ec="blac

Matplotlib for Data Visualization - Part 2 21


k")

[Link](3, 0, "Important Point", fontsize=12, verticalalignment="bottom")


[Link]()
[Link]()

Adding Rectangles, Circles, and Other Shapes


Using patches from Matplotlib:

import [Link] as patches

fig, ax = [Link]()
[Link](x, y1, label="Sine Wave", color="blue")

# Adding a rectangle
rect = [Link]((2, -1), 2, 2, color="gray", alpha=0.3)
ax.add_patch(rect)

[Link]()
[Link]()

Matplotlib for Data Visualization - Part 2 22


6.3 Customizing Fonts & Styles
Changing Font Styles
You can customize font properties globally using rcParams or locally using fontdict .

[Link](x, y1, label="Sine Wave", color="blue")

[Link]("Customized Title", fontsize=16, fontweight="bold", fontname="Arial")


[Link]("X-axis", fontsize=14, fontstyle="italic")
[Link]("Y-axis", fontsize=14, fontfamily="monospace")

[Link]()
[Link]()

Matplotlib for Data Visualization - Part 2 23


Setting Global Font Styles

[Link]["[Link]"] = 14
[Link]["[Link]"] = "serif"

[Link](x, y1, label="Sine Wave", color="blue")


[Link]("Global Font Style Applied")
[Link]()
[Link]()

6.4 Working with Date & Time Data in Plots

Matplotlib for Data Visualization - Part 2 24


Matplotlib supports time-series data using [Link] and datetime .

Plotting Time-Series Data

import [Link] as mdates


import datetime

# Generate sample date-time data


dates = [[Link](2023, 1, i) for i in range(1, 11)]
values = [Link]([Link](0, 10, 10))

fig, ax = [Link]()
[Link](dates, values, marker="o", linestyle="-")

[Link].set_major_formatter([Link]("%b %d")) # Format dat


es
[Link].set_major_locator([Link](interval=1)) # Show every day

[Link]("Time-Series Plot")
[Link]("Date")
[Link]("Value")
[Link](rotation=45)
[Link]()

Matplotlib for Data Visualization - Part 2 25


6.5 Customizing Backgrounds & Themes
Changing Background Color

fig, ax = [Link]()
[Link](x, y1, label="Sine Wave", color="blue")

ax.set_facecolor("#f0f0f0") # Light gray background


[Link]("Custom Background Color")
[Link]()

Using Built-in Styles


Matplotlib provides several predefined styles. Use [Link] to list them.

import [Link] as style

[Link]("ggplot") # Apply ggplot style

[Link](x, y1, label="Sine Wave", color="blue")


[Link]("Using ggplot Style")
[Link]()
[Link]()

Matplotlib for Data Visualization - Part 2 26


Creating a Custom Theme

[Link]["[Link]"] = "#f5f5f5"
[Link]["[Link]"] = "#333333"
[Link]["[Link]"] = "gray"

[Link](x, y1, label="Sine Wave", color="blue")


[Link]("Custom Theme Applied")
[Link]()
[Link]()

Matplotlib for Data Visualization - Part 2 27

You might also like