0% found this document useful (0 votes)
0 views19 pages

class 9_plot

The document provides an overview of using Matplotlib for data visualization in Python, detailing various plotting interfaces such as pyplot and object-oriented programming (OOP) methods. It covers the creation of different types of plots including line plots, bar charts, and scatter plots, as well as techniques for customizing figures, subplots, and annotations. Additionally, it discusses time series plotting with date axes and rolling windows.

Uploaded by

jumcofficial
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)
0 views19 pages

class 9_plot

The document provides an overview of using Matplotlib for data visualization in Python, detailing various plotting interfaces such as pyplot and object-oriented programming (OOP) methods. It covers the creation of different types of plots including line plots, bar charts, and scatter plots, as well as techniques for customizing figures, subplots, and annotations. Additionally, it discusses time series plotting with date axes and rolling windows.

Uploaded by

jumcofficial
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

class 9_plot [Link]

html

!pip install matplotlib

In [2]: import numpy as np


import pandas as pd

In [3]: import matplotlib


import [Link] as plt

matplotlib.__version__

Out[3]: '3.10.0'

6.1 Figure, axes & the pyplot


interface

Interface
• Paper

pyplot (plt) →→ Quick & stateful →→ Fast exploratory


plots — one chart at a time →→ [Link](x, y)

• White board

OOP (fig, ax) →→ Explicit & controlled →→ Multi-chart


layouts, reusable code, professional output →→

fig, ax = [Link]()

[Link](x, y)

Interface Paper: pyplot


1 of 19 09-Jul-26, 11:02 PM
class 9_plot [Link]

In [8]: x = [1, 2, 3, 4, 5]
y = [3, 5, 4, 8, 6]

[Link](x, y)

[Link]("Shirajum Monira")

[Link]()

Interface Whiteboard: OOP


— explicit Figure + Axes

Figure — whiteboard
• fig.set_size_inches()
• [Link]()

2 of 19 09-Jul-26, 11:02 PM
class 9_plot [Link]

Axes — small pictures

• [Link]()
• ax.set_title()
• ax.set_xlabel/ylabel()
• [Link]()

In [9]: x = [1, 2, 3, 4, 5]
y = [3, 5, 4, 8, 6]

In [21]: fig, ax = [Link](figsize=(7, 4))

[Link](x, y)

ax.set_title("LAL")
ax.set_xlabel("Kanika")
ax.set_ylabel("Abu Hanif")
plt.tight_layout()
[Link]()

6.2 Line plots, bar charts &


3 of 19 09-Jul-26, 11:02 PM
class 9_plot [Link]

scatter plots
• Line plot
[Link](x, y)
• Bar plot
[Link](categories, values)
• Scatter plot
[Link](x, y)

In [24]:

Out[24]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1


2])

In [25]: [Link](42)
x = [Link](1, 13)

y1 = [42, 45, 48, 55, 62, 70, 68, 73, 69, 64, 58, 76]

y2 = [38, 40, 36, 44, 52, 60, 58, 62, 55, 50, 48, 65]

In [40]: fig, ax = [Link](figsize=(9, 4))

[Link](x, y1, color="blue", marker="o", linewidth=1, markers


[Link](x, y2, color="red", marker="s", linewidth=2,markersiz

ax.set_xlabel("Month")
ax.set_ylabel("Sales")
[Link]()

[Link](True, alpha=0.3)

ax.set_xticks(x)

ax.set_xticklabels(["Jan","Feb","Mar","Apr","May","Jun"

plt.tight_layout()
[Link]()

4 of 19 09-Jul-26, 11:02 PM
class 9_plot [Link]

In [42]: products = ["Laptop", "Phone", "Tablet", "Monitor", "Keyboar


revenues = [246, 165, 82, 134, 47]
colors = ["#1565C0", "#D84315", "#2E7D32", "#6A1B9A"

In [56]: fig, ax = [Link](figsize=(8, 4))

[Link](products, revenues, color=colors, edgecolor="black"

Out[56]: <BarContainer object of 5 artists>

In [57]: fig, ax = [Link](figsize=(8, 4))

[Link](products, revenues, color=colors, edgecolor="black"

ax.set_title("Revenue by Product (thousands)", fontsize

ax.set_ylabel("Revenue (k )")
ax.set_ylim(0, 280)

5 of 19 09-Jul-26, 11:02 PM
class 9_plot [Link]

plt.tight_layout()
[Link]()

In [59]: [Link](7)
ad_spend = [Link](5, 50, 60)

sales = 3.2 * ad_spend + [Link](0, 15, 60

regions = [Link](["Dhaka", "Ctg", "Sylhet"],

In [62]: regions

Out[62]: array(['Sylhet', 'Dhaka', 'Sylhet', 'Dhaka', 'Dhaka',


'Ctg', 'Dhaka',
'Ctg', 'Dhaka', 'Sylhet', 'Sylhet', 'Sylhet',
'Dhaka', 'Ctg',
'Dhaka', 'Sylhet', 'Dhaka', 'Dhaka', 'Dhaka',
'Dhaka', 'Ctg',
'Sylhet', 'Dhaka', 'Sylhet', 'Dhaka', 'Ctg', '
Ctg', 'Dhaka', 'Ctg',
'Sylhet', 'Dhaka', 'Dhaka', 'Dhaka', 'Ctg', 'D
haka', 'Ctg', 'Ctg',
'Ctg', 'Sylhet', 'Sylhet', 'Dhaka', 'Dhaka', '
Dhaka', 'Sylhet',
'Sylhet', 'Dhaka', 'Sylhet', 'Sylhet', 'Sylhet
', 'Ctg', 'Ctg',
'Ctg', 'Dhaka', 'Ctg', 'Sylhet', 'Dhaka', 'Ctg
', 'Dhaka', 'Sylhet',
'Ctg'], dtype='<U6')

6 of 19 09-Jul-26, 11:02 PM
class 9_plot [Link]

In [63]: color_map = {

"Dhaka": "red", "Ctg": "blue", "Sylhet": "green"

In [72]: fig, ax = [Link](figsize=(7, 5))

for region, clr in color_map.items():

condition = regions == region

[Link](ad_spend[condition], sales[condition],color

In [ ]: X= [1,2,3,4,5]

y= x+2

6.3 Subplots, layout & figure


sizing
Subplots let you show multiple charts side-by-side in one

7 of 19 09-Jul-26, 11:02 PM
class 9_plot [Link]

figure — perfect for comparing charts or building a


dashboard.
[Link](rows, cols) returns a grid of Axes objects.

In [73]: [Link]()

Out[73]: (<Figure size 640x480 with 1 Axes>, <Axes: >)

In [74]: [Link]( 2, 2 )

Out[74]: (<Figure size 640x480 with 4 Axes>,


array([[<Axes: >, <Axes: >],
[<Axes: >, <Axes: >]], dtype=object))

8 of 19 09-Jul-26, 11:02 PM
class 9_plot [Link]

In [75]: fig, axs = [Link](figsize=(10, 7))

In [78]: fig, picture = [Link]( 2, 2, figsize=(10, 7) )

9 of 19 09-Jul-26, 11:02 PM
class 9_plot [Link]

In [86]: [Link](42)

x = [Link](0, 2*[Link], 100)

y= [Link](x)

In [91]: cats = ["Q1", "Q2", "Q3", "Q4"]

vals = [45, 62, 58, 71]

In [87]: table, picture = [Link](2, 2, figsize=(10, 7))

picture[0,0].plot(x,y )

Out[87]: [<[Link].Line2D at 0x1f345f30550>]

10 of 19 09-Jul-26, 11:02 PM
class 9_plot [Link]

In [ ]: # Top-left [0,0] — line plot


axs[0, 0].plot(x, [Link](x), color="#1565C0", lw=2)

In [115… fig, picture = [Link](2, 2, figsize=(10, 7))

# Top-right [0,1] — bar chart

picture[0, 1].bar(cats, vals, color=["#1565C0","#D84315"

Out[115… <BarContainer object of 4 artists>

11 of 19 09-Jul-26, 11:02 PM
class 9_plot [Link]

In [95]: fig, axs = [Link](2, 2, figsize=(10, 7))

sx = [Link](80)

sy = [Link](80)

axs[1, 0].scatter(sx, sy, s=30)

Out[95]: <[Link] at 0x1f34713fd


90>

12 of 19 09-Jul-26, 11:02 PM
class 9_plot [Link]

In [96]: fig, axs = [Link](2, 2, figsize=(10, 7))

data = [Link](65, 12, 300)


axs[1, 1].hist(data, bins=20, color="#2E7D32", edgecolor
axs[1, 1].set_title("Score distribution (histogram)")

Out[96]: Text(0.5, 1.0, 'Score distribution (histogram)')

13 of 19 09-Jul-26, 11:02 PM
class 9_plot [Link]

In [97]: fig, axs = [Link](2, 2, figsize=(10, 7))

# Top-left [0,0] — line plot


axs[0, 0].plot(x, [Link](x), color="#1565C0", lw=2)

# Top-right [0,1] — bar chart


axs[0, 1].bar(cats, vals, color=["#1565C0","#D84315","#2E7D32
axs[0, 1].set_title("Quarterly sales (bar)")
axs[0, 1].grid(True, axis="y", alpha=0.3)

# Bottom-left [1,0] — scatter


sx, sy = [Link](80), [Link](80)
axs[1, 0].scatter(sx, sy, alpha=0.6, color="#D84315", s
axs[1, 0].set_title("Random scatter")

# Bottom-right [1,1] — histogram


data = [Link](65, 12, 300)
axs[1, 1].hist(data, bins=20, color="#2E7D32", edgecolor
axs[1, 1].set_title("Score distribution (histogram)")

[Link]("Four chart types in one figure", fontsize


plt.tight_layout()
[Link]()

6.4 Titles, axis labels,


14 of 19 09-Jul-26, 11:02 PM
class 9_plot [Link]

legends & annotations


In [102… months = [Link](1, 13)

In [103… target = [Link](12, 60)


actual = [42, 48, 55, 63, 70, 78, 74, 80, 77, 85, 79, 92

In [104… fig, ax = [Link](figsize=(10, 5))

# Lines
[Link](months, actual, color="#1565C0", lw=2.5, marker

[Link](months, target, color="#D84315", lw=1.8, linestyle

Out[104… [<[Link].Line2D at 0x1f346286990>]

In [107… fig, ax = [Link](figsize=(10, 5))

# Lines
[Link](months, actual, color="#1565C0", lw=2.5, marker

[Link](months, target, color="#D84315", lw=1.8, linestyle

[Link]("max point",xy=(12, 92), xytext=(10, 85), arrowpr

15 of 19 09-Jul-26, 11:02 PM
class 9_plot [Link]

# Horizontal reference line


[Link](y=60, color="grey", linestyle=":", linewidth

# Labels, title, legend


ax.set_title("Sales Performance vs Target (2024)", fontsize
ax.set_xlabel("Month", fontsize=11)
ax.set_ylabel("Units Sold", fontsize=11)
ax.set_xticks(months)
ax.set_xticklabels(["Jan","Feb","Mar","Apr","May","Jun"
[Link](loc="upper left", framealpha=0.9)
ax.set_ylim(30, 100)
[Link](True, alpha=0.25)
plt.tight_layout()
[Link]()

6.5 Plotting time series —


date axes & rolling windows
In [108… import [Link] as mdates

[Link](42)
# Build a daily time series — 6 months

dates = pd.date_range("2024-01-01", periods=180, freq

16 of 19 09-Jul-26, 11:02 PM
class 9_plot [Link]

trend = [Link](100, 160, 180)

seasonal = 20 * [Link](2*[Link]*[Link](180) / 30) # month

noise = [Link](0, 8, 180)

In [109… sales = trend + seasonal + noise

In [110… df = [Link]({"sales": sales}, index=dates)

In [111… df

Out[111… sales

2024-01-01 103.973713

2024-01-02 103.387315

2024-01-03 113.986632

2024-01-04 124.945530

2024-01-05 114.330452

... ...

2024-06-24 147.956176

2024-06-25 144.235532

2024-06-26 159.202177

2024-06-27 149.412817

2024-06-28 177.603120

180 rows × 1 columns

In [112… df["7d_avg"] = df["sales"].rolling(7).mean()


df["30d_avg"] = df["sales"].rolling(30).mean()

In [113… df

17 of 19 09-Jul-26, 11:02 PM
class 9_plot [Link]

Out[113… sales 7d_avg 30d_avg

2024-01-01 103.973713 NaN NaN

2024-01-02 103.387315 NaN NaN

2024-01-03 113.986632 NaN NaN

2024-01-04 124.945530 NaN NaN

2024-01-05 114.330452 NaN NaN

... ... ... ...

2024-06-24 147.956176 138.217040 154.519701

2024-06-25 144.235532 139.428507 155.188217

2024-06-26 159.202177 143.236444 156.263144

2024-06-27 149.412817 145.756729 156.388580

2024-06-28 177.603120 151.536263 157.369958

180 rows × 3 columns

In [114… fig, ax = [Link](figsize=(11, 4.5))

[Link]( [Link], df["sales"], color="#90CAF9", lw=0.8

[Link]([Link], df["7d_avg"], color="#1565C0", lw=1.8

[Link]([Link], df["30d_avg"], color="#D84315", lw=2.5

# Format x-axis as dates


[Link].set_major_locator([Link]())
[Link].set_major_formatter([Link]("%b %Y"
[Link]([Link].get_majorticklabels(), rotation=20, ha

18 of 19 09-Jul-26, 11:02 PM
class 9_plot [Link]

ax.set_title("Daily Sales with 7-day & 30-day Rolling Average


ax.set_ylabel("Sales (units)")
[Link](loc="upper left")
[Link](True, alpha=0.25)
plt.tight_layout()
[Link]()

In [ ]:

19 of 19 09-Jul-26, 11:02 PM

You might also like