2.3. Matplotlib#

last update: Feb 07, 2024

Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. - Matplotlib

import matplotlib.pyplot as plt
import numpy as np

2.3.1. 1. Plot a line#

# make a square function
def square(x):
    return x**2

# Make x and y values.
# np.linxpace() is a function that returns evenly spaced numbers over a specified interval.
# We use it to make x values from -5 to 5 with 100 points in between.
x = np.linspace(-5, 5, 100)
y = square(x)
# plot the function. ` plt` is an alias for `matplotlib.pyplot`.
plt.plot(x, y)
plt.show()
../../_images/90c57864dca69036f57686daf2f183992bc83cf77f17dfceb1c16b13533a62e0.png
# plot the function. ` plt` is an alias for `matplotlib.pyplot`.
plt.plot(x, y)

# Add labels to the axes
plt.xlabel('x')
plt.ylabel('y')

# Add a title
plt.title('Square function')

plt.show()
../../_images/2bdea82e9a00929c740931cf1a9c5757cab24c00f37a93c1d2e7f98eae274a29.png

Change color, marker style and line style#

x = np.linspace(-5, 5, 10)
y = square(x)

# You can specify the color, marker, and line style in the plot function as below.
plt.plot(x, y, color='red', marker='o', linestyle='--', label='label')

# Show the legend. It uses the `label` defined in the `plot()` function.
plt.legend()

# Add labels to the axes
plt.xlabel('x')
plt.ylabel('y')

# Add a title
plt.title('Square function')

plt.show()
../../_images/54ca3ba8343115670d354cae48398b75f904ecf3bb6b6ec651e50a00afd4825f.png

Add cube function plot.

def cube(x):
    return x**3
x = np.linspace(-3, 3, 10)
y = square(x)
z = cube(x)

# You can specify the color, marker, and line style in the plot function as below.
plt.plot(x, y, color='red', marker='o', linestyle='--', label='Square')
plt.plot(x, z, color='blue', marker='x', linestyle='-', label='Cube')

# Show the legend. It uses the `label` defined in the `plot()` function
plt.legend() 

# Add labels to the axes
plt.xlabel('x')
plt.ylabel('y')

# Add a title
plt.title('Square function and cube function')

plt.show()
../../_images/af14fcbe6b1d29b8e07ef1bee2faef9f5f5fb31ac1c125ff74d5fe1e6d00db7f.png

plt.semilogy plots the y-axis in log scale.#

x = np.linspace(0.1, 10, 10)
y = square(x)
z = cube(x)

# You can specify the color, marker, and line style in the plot function as below.
plt.semilogy(x, y, color='red', marker='o', linestyle='--', label='Square')
plt.semilogy(x, z, color='blue', marker='x', linestyle='-', label='Cube')

# Show the legend. It uses the `label` defined in the `plot()` function
plt.legend() 

# Add labels to the axes
plt.xlabel('x')
plt.ylabel('y')

# Add a title
plt.title('Square function and cube function')

plt.show()
../../_images/80374736fa0dd5b80c5091e3007a0e901fefb4dbd602205ec4472cd39d747e3d.png
x = np.linspace(-5, 5, 10)
y = np.exp(x)

# You can specify the color, marker, and line style in the plot function as below.
plt.semilogy(x, y, label='Exponential')

# Show the legend. It uses the `label` defined in the `plot()` function
plt.legend() 

# Add labels to the axes
plt.xlabel('x')
plt.ylabel('exp(x)')

# Add a title
plt.title('Exponential function')

plt.show()
../../_images/8b2d0fbd14d189dca8ccdf838d85e299d696cabfec6a33aa9778a6840669125a.png

2.3.2. 2. Scatter plot#

# Scatter plot
x = np.linspace(-5, 5, 20)
y = square(x)

plt.scatter(x, y)
plt.show()
../../_images/b428ac29ccc3c8e84356ff1cf03455881c9808c1d0735ff10f1ad6d1a31acfcf.png
np.random.seed(0)

# Scatter plot: gaussian distribution with mean 0 and standard deviation 1
x = np.random.normal(size=1000)
y = np.random.normal(size=1000)

plt.scatter(x, y)
plt.show()
../../_images/34166a083ff52c13b574178e7cadf70448b776f950e0e0f3a5a8a2707f12ae08.png

2.3.3. 3. Histogram#

np.random.seed(0)

# Generate 10000 random numbers from a normal distribution with mean 0 and standard deviation 1.

x = np.random.normal(0, 1, 10000)

# Plot a histogram with 50 bins.
plt.hist(x, bins=50)
plt.show()
../../_images/23974a3d018cc34dd675b31785e88ef2232277d14c0ece496168c2bf2fbe69c6.png

Add another histogram#

np.random.seed(0)

# Generate 10000 random numbers from a normal distribution with mean 0 and standard deviation 1.
x = np.random.normal(0, 1, 10000)
# Generate 10000 random numbers from a normal distribution with mean 2 and standard deviation 0.5.
y = np.random.normal(2, 0.5, 10000)

# Plot a histogram with 50 bins.
# `alpha` is the transparency of the bars. used to compare several histograms.
plt.hist(x, bins=50, color='blue', alpha=0.5, label='x')
plt.hist(y, bins=50, color='green', alpha=0.5, label='y')

# Show the legend. It uses the `label` defined in the `hist()` function.
plt.legend()

# Add labels to the axes
plt.xlabel('value')
plt.ylabel('count')

# Add a title
plt.title('Histogram')

plt.show()
../../_images/4eb065e71530cc63d4c071863d99873f78887fe34ff81fe6c702c08a091928a3.png
import matplotlib.pyplot as plt
import numpy as np

year = ("2003", "2013", "2023")
gdps = {
    'Japan': (4519.56, 5212.33, 4409.74),
    'China': (1656.96, 9624.93, 19373.59),
    'America': (11456.45, 16843.23, 26854.60),
}

x = np.arange(len(year)) * 1  # the label locations
width = 0.3  # the width of the bars
multiplier = 0

fig, ax = plt.subplots(layout='constrained')

for country, gdp in gdps.items():
    offset = width * multiplier
    rects = ax.bar(x + offset, gdp, width, label=country)
    ax.bar_label(rects, padding=3)
    multiplier += 1


ax.set_ylabel('GDP (billion USD)')
ax.set_title('GDP')
ax.set_xticks(x + width, year)
ax.legend(loc='upper left', ncols=3)

plt.show()
../../_images/c3a4cb8fff9b6e8e4710f910d01aeede69be1237beaaa8e5692c1247298e46d5.png

2.3.4. 5. 2D plots#

import matplotlib.pyplot as plt
import numpy as np

t = np.linspace(0, 2 * np.pi, 1024)
data2d = np.sin(t)[:, np.newaxis] * np.sin(t)[np.newaxis, :]

fig, ax = plt.subplots()
im = ax.imshow(data2d)

fig.colorbar(im, ax=ax, label='Colorbar')

ax.set_title('sin(x)sin(y)')
plt.show()
../../_images/658a2c01aa90e38f423a62d2288e91e2b205f840607a12bbacf99a8b0757f9fe.png

2.3.5. 6. 3D line plots#

def pos(t):
    
    x = np.exp(-t) * np.cos(10 * np.pi * t)
    y = np.exp(-t) * np.sin(10 * np.pi * t)
    z = t
    
    return x, y, z

t = np.linspace(0, 2, 1000)

x, y, z = pos(t)

fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(projection='3d')

ax.plot(x, y, z, label='parametric curve')

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

ax.set_title("3D Parametric Curve")
plt.show()
../../_images/38e33b593fbb67e86602bc200fba121486d2e89566423d283573455da94fe3f5.png

2.3.6. 7. 3D surface plot#

import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator
import numpy as np

fig, ax = plt.subplots(subplot_kw={"projection": "3d"})

# Make data.
X = np.arange(-5, 5, 0.05)
Y = np.arange(-5, 5, 0.05)
X, Y = np.meshgrid(X, Y)
Z = np.sin(X) * np.cos(Y)

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=0, antialiased=False)

# Customize the z axis.
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(5))
ax.zaxis.set_major_formatter('{x:.02f}')

# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=9)

plt.show()
../../_images/3a232880b1a37222f5fb8b7c3d8ccdb1ba687e269e743555b1c337e08ea47f08.png