Matplotlib Basics¶
Load Font¶
In [ ]:
Copied!
!wget "https://github.com/web-fonts/ttf/raw/refs/heads/master/arial-geo-webfont.ttf"
# Arial GEO
!wget "https://github.com/web-fonts/ttf/raw/refs/heads/master/arial-geo-webfont.ttf"
# Arial GEO
In [18]:
Copied!
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from pathlib import Path
# Path to the Arial font file
fpath = Path("./arial-geo-webfont.ttf")
# Load and register the Arial font
arial_font = fm.FontProperties(fname=fpath)
fm.fontManager.addfont(fpath) # Add the font to Matplotlib's font manager
# Set the global font to Arial
plt.rcParams['font.family'] = arial_font.get_name()
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from pathlib import Path
# Path to the Arial font file
fpath = Path("./arial-geo-webfont.ttf")
# Load and register the Arial font
arial_font = fm.FontProperties(fname=fpath)
fm.fontManager.addfont(fpath) # Add the font to Matplotlib's font manager
# Set the global font to Arial
plt.rcParams['font.family'] = arial_font.get_name()
Imports¶
In [4]:
Copied!
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.datasets import load_breast_cancer, load_iris
import seaborn as sns
plt.style.use('Solarize_Light2')
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.datasets import load_breast_cancer, load_iris
import seaborn as sns
plt.style.use('Solarize_Light2')
Import and Generate Data¶
In [8]:
Copied!
# pandas
# M(0) = malignant, B(1) = benign
bc_X, bc_y = load_breast_cancer(return_X_y=True, as_frame=True)
bc_X.head(2)
# pandas
# M(0) = malignant, B(1) = benign
bc_X, bc_y = load_breast_cancer(return_X_y=True, as_frame=True)
bc_X.head(2)
Out[8]:
mean radius | mean texture | mean perimeter | mean area | mean smoothness | mean compactness | mean concavity | mean concave points | mean symmetry | mean fractal dimension | ... | worst radius | worst texture | worst perimeter | worst area | worst smoothness | worst compactness | worst concavity | worst concave points | worst symmetry | worst fractal dimension | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 17.99 | 10.38 | 122.8 | 1001.0 | 0.11840 | 0.27760 | 0.3001 | 0.14710 | 0.2419 | 0.07871 | ... | 25.38 | 17.33 | 184.6 | 2019.0 | 0.1622 | 0.6656 | 0.7119 | 0.2654 | 0.4601 | 0.11890 |
1 | 20.57 | 17.77 | 132.9 | 1326.0 | 0.08474 | 0.07864 | 0.0869 | 0.07017 | 0.1812 | 0.05667 | ... | 24.99 | 23.41 | 158.8 | 1956.0 | 0.1238 | 0.1866 | 0.2416 | 0.1860 | 0.2750 | 0.08902 |
2 rows × 30 columns
In [9]:
Copied!
# numpy
iris_X, iris_y = load_iris(return_X_y=True)
iris_X[:2, :]
# numpy
iris_X, iris_y = load_iris(return_X_y=True)
iris_X[:2, :]
Out[9]:
array([[5.1, 3.5, 1.4, 0.2], [4.9, 3. , 1.4, 0.2]])
In [10]:
Copied!
# generated
rand_X = np.random.random(50) * 100
rand_y = np.random.random(50) * 100
# generated
rand_X = np.random.random(50) * 100
rand_y = np.random.random(50) * 100
Scatter Plot¶
In [17]:
Copied!
sns.scatterplot(x=rand_X, y=rand_y)
plt.title("sns", fontdict={"fontsize": 20, "fontname": "Arial GEO"})
plt.xlabel("rand X")
plt.ylabel("rand y")
plt.yticks(rand_y[::10], [f"{y:.0f}k" for y in rand_y[::10]])
plt.show()
sns.scatterplot(x=rand_X, y=rand_y)
plt.title("sns", fontdict={"fontsize": 20, "fontname": "Arial GEO"})
plt.xlabel("rand X")
plt.ylabel("rand y")
plt.yticks(rand_y[::10], [f"{y:.0f}k" for y in rand_y[::10]])
plt.show()
In [33]:
Copied!
plt.scatter(x=rand_X, y=rand_y, c="purple", marker="^", s=50, alpha=0.5)
plt.title("plt")
plt.show()
plt.scatter(x=rand_X, y=rand_y, c="purple", marker="^", s=50, alpha=0.5)
plt.title("plt")
plt.show()
In [6]:
Copied!
sns.scatterplot(x=iris_X[:, 2], y=iris_X[:, 3], hue=iris_y, palette="tab10", s=50)
sns.scatterplot(x=iris_X[:, 2], y=iris_X[:, 3], hue=iris_y, palette="tab10", s=50)
Out[6]:
<Axes: >
Line Chart¶
In [19]:
Copied!
years = np.array([2001 + x for x in range(24)])
profitsSaj = np.random.randint(5_000, 20_000, (24, ))
profitsRez = np.random.randint(5_000, 20_000, (24, ))
years = np.array([2001 + x for x in range(24)])
profitsSaj = np.random.randint(5_000, 20_000, (24, ))
profitsRez = np.random.randint(5_000, 20_000, (24, ))
In [21]:
Copied!
# supported values are '-', '--', '-.', ':', 'None', ' ', '', 'solid', 'dashed', 'dashdot', 'dotted'
plt.plot(years, profitsSaj, c="g", lw=1, linestyle="-.", label="Sajjad")
plt.show()
# supported values are '-', '--', '-.', ':', 'None', ' ', '', 'solid', 'dashed', 'dashdot', 'dotted'
plt.plot(years, profitsSaj, c="g", lw=1, linestyle="-.", label="Sajjad")
plt.show()
Bar Plot¶
Different from Histogram (In bar charts there is a gab)
In [9]:
Copied!
x = ["Python", "C#", "Rust", "RUby", "R", "Golang"]
y = [200, 50, 100, 70, 90, 120]
x = ["Python", "C#", "Rust", "RUby", "R", "Golang"]
y = [200, 50, 100, 70, 90, 120]
In [10]:
Copied!
# supported values are 'center', 'edge'
plt.bar(x, y, align="edge", width=0.5, edgecolor="black", lw=3)
# supported values are 'center', 'edge'
plt.bar(x, y, align="edge", width=0.5, edgecolor="black", lw=3)
Out[10]:
<BarContainer object of 6 artists>
Histogram¶
In [11]:
Copied!
ages = np.random.normal(20, 1, 1000)
ages = np.random.normal(20, 1, 1000)
In [12]:
Copied!
# plt.hist(ages, bins=[18, 20, 23]) # you can specify bin ranges
plt.hist(ages, bins=100)
plt.show()
# plt.hist(ages, bins=[18, 20, 23]) # you can specify bin ranges
plt.hist(ages, bins=100)
plt.show()
In [13]:
Copied!
plt.hist(ages, bins=20, cumulative=True)
plt.show()
plt.hist(ages, bins=20, cumulative=True)
plt.show()
Pie Chart¶
In [14]:
Copied!
unique, counts = np.unique(iris_y, return_counts=True)
plt.pie(x=counts, labels=["Type 1", "Type 2", "Type 3"], explode=[0.05, 0, 0], autopct="%.2f%%")
plt.show()
counts = bc_y.value_counts().to_numpy()
plt.pie(x=counts, labels=["benign", "malignant"], autopct="%.2f%%", pctdistance=1.3)
plt.show()
unique, counts = np.unique(iris_y, return_counts=True)
plt.pie(x=counts, labels=["Type 1", "Type 2", "Type 3"], explode=[0.05, 0, 0], autopct="%.2f%%")
plt.show()
counts = bc_y.value_counts().to_numpy()
plt.pie(x=counts, labels=["benign", "malignant"], autopct="%.2f%%", pctdistance=1.3)
plt.show()
In [14]:
Copied!
Box Plot¶
Statistical Plot
In [15]:
Copied!
heights = np.random.normal(172, 8, 500)
heights = np.random.normal(172, 8, 500)
In [23]:
Copied!
plt.boxplot(heights)
plt.show()
"""
Min is 150,
Max is 195,
Median is green line in square
circles are out layers
"""
plt.boxplot(heights)
plt.show()
"""
Min is 150,
Max is 195,
Median is green line in square
circles are out layers
"""
Out[23]:
'\nMin is 150,\nMax is 195,\nMedian is green line in square\ncircles are out layers\n'
Heatmap Plot¶
In [27]:
Copied!
vegetables = np.array(["cucumber", "tomato", "lettuce", "asparagus",
"potato", "wheat", "barley"])
farmers = np.array(["Farmer Joe", "Upland Bros.", "Smith Gardening",
"Agrifun", "Organiculture", "BioGoods Ltd.", "Cornylee Corp."])
harvest = np.array([[0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0],
[2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0],
[1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0],
[0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0],
[0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0],
[1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1],
[0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]])
vegetables = np.array(["cucumber", "tomato", "lettuce", "asparagus",
"potato", "wheat", "barley"])
farmers = np.array(["Farmer Joe", "Upland Bros.", "Smith Gardening",
"Agrifun", "Organiculture", "BioGoods Ltd.", "Cornylee Corp."])
harvest = np.array([[0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0],
[2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0],
[1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0],
[0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0],
[0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0],
[1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1],
[0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]])
In [30]:
Copied!
sns.heatmap(harvest, xticklabels=farmers, yticklabels=vegetables, annot=True)
sns.heatmap(harvest, xticklabels=farmers, yticklabels=vegetables, annot=True)
Out[30]:
<Axes: >
Legend¶
In [24]:
Copied!
plt.plot(years, profitsSaj, c="g", lw=1, linestyle="-.", label="Sajjad")
plt.plot(years, profitsRez, c="r", lw=1, linestyle="--", label="Reza")
# supported values are 'best', 'upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center'
plt.legend(loc="lower left") # To show the labels
plt.show()
plt.plot(years, profitsSaj, c="g", lw=1, linestyle="-.", label="Sajjad")
plt.plot(years, profitsRez, c="r", lw=1, linestyle="--", label="Reza")
# supported values are 'best', 'upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center'
plt.legend(loc="lower left") # To show the labels
plt.show()
SubPlots + Save¶
In [51]:
Copied!
fig, axs= plt.subplots(nrows=2, ncols=2, figsize=(12, 8))
col_names = bc_X.columns
col_count = len(col_names)
col_index = 0
for i in range(2):
for j in range(2):
if col_index == col_count - 1:
break
axs[i][j].scatter(x=bc_X.iloc[:, col_index], y=bc_X.iloc[:, col_index + 1], c="purple", marker="o", s=50, alpha=0.5)
axs[i][j].set_title("Breast Cancer")
axs[i][j].set_xlabel(col_names[col_index])
axs[i][j].set_ylabel(col_names[col_index + 1])
col_index += 1
fig.suptitle("Breast Cancer", fontsize=30)
plt.tight_layout() # prevent overlap
plt.savefig("bc.png", dpi=300)
plt.show()
fig, axs= plt.subplots(nrows=2, ncols=2, figsize=(12, 8))
col_names = bc_X.columns
col_count = len(col_names)
col_index = 0
for i in range(2):
for j in range(2):
if col_index == col_count - 1:
break
axs[i][j].scatter(x=bc_X.iloc[:, col_index], y=bc_X.iloc[:, col_index + 1], c="purple", marker="o", s=50, alpha=0.5)
axs[i][j].set_title("Breast Cancer")
axs[i][j].set_xlabel(col_names[col_index])
axs[i][j].set_ylabel(col_names[col_index + 1])
col_index += 1
fig.suptitle("Breast Cancer", fontsize=30)
plt.tight_layout() # prevent overlap
plt.savefig("bc.png", dpi=300)
plt.show()
Showing Saved Fig¶
In [52]:
Copied!
# Imports PIL module
from PIL import Image
# open method used to open different extension image file
im = Image.open("bc.png")
# This method will show image in any image viewer
# im.show()
im
# Imports PIL module
from PIL import Image
# open method used to open different extension image file
im = Image.open("bc.png")
# This method will show image in any image viewer
# im.show()
im
Out[52]:
3D Plot¶
Scatter Plot¶
In [54]:
Copied!
ax = plt.axes(projection="3d")
x = np.random.random(100)
y = np.random.random(100)
z = np.random.random(100)
ax.scatter(x, y, z)
ax = plt.axes(projection="3d")
x = np.random.random(100)
y = np.random.random(100)
z = np.random.random(100)
ax.scatter(x, y, z)
Out[54]:
<mpl_toolkits.mplot3d.art3d.Path3DCollection at 0x7b8bacf24390>
Line Plot¶
In [56]:
Copied!
ax = plt.axes(projection="3d")
x = np.arange(0, 50, 0.1)
y = np.arange(0, 50, 0.1)
z = np.cos(x + y)
ax.plot(x, y, z)
ax = plt.axes(projection="3d")
x = np.arange(0, 50, 0.1)
y = np.arange(0, 50, 0.1)
z = np.cos(x + y)
ax.plot(x, y, z)
Out[56]:
[<mpl_toolkits.mplot3d.art3d.Line3D at 0x7b8bac705410>]
Surface Plot¶
In [67]:
Copied!
ax = plt.axes(projection="3d")
x = np.arange(-5, 5, 0.1)
y = np.arange(-5, 5, 0.1)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)
ax.plot_surface(X, Y, Z, cmap="Spectral")
# ax.view_init(azim = 0, elev = 90) # change view
ax = plt.axes(projection="3d")
x = np.arange(-5, 5, 0.1)
y = np.arange(-5, 5, 0.1)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)
ax.plot_surface(X, Y, Z, cmap="Spectral")
# ax.view_init(azim = 0, elev = 90) # change view
Out[67]:
<mpl_toolkits.mplot3d.art3d.Poly3DCollection at 0x7b8ba7d41cd0>
Animation Plot¶
not working in ipynb
In [71]:
Copied!
import random
heads_tails = [0, 0]
for _ in range(20):
heads_tails[random.randint(0, 1)] += 10
plt.bar(["Heads", "Tails"], heads_tails, color=["skyblue", "purple"])
plt.pause(0.001)
plt.show()
import random
heads_tails = [0, 0]
for _ in range(20):
heads_tails[random.randint(0, 1)] += 10
plt.bar(["Heads", "Tails"], heads_tails, color=["skyblue", "purple"])
plt.pause(0.001)
plt.show()
In [ ]:
Copied!