Plot Functions
Plot the graphs for some functions.
import matplotlib.pyplot as plt
import numpy as np
X = np.linspace(-1, 1, 100)
I = np.ones(100)
def myfig():
fig, ax = plt.subplots()
ax.set_xlabel('x')
ax.set_ylabel('f(x)')
ax.grid(True, which='both')
ax.axhline(y=0, color='k')
ax.axvline(x=0, color='k')
return fig, ax
# sqrt(x)
fig, ax = myfig()
ax.plot(X, np.sqrt(I + X), label='f(x) = sqrt(x)')
ax.plot(X, np.sqrt(I - X), label='f(x) = sqrt(1-x)')
plt.legend(loc='upper right')
# x^2
fig, ax = myfig()
ax.plot(X, X**2, label='f(x) = x^2')
ax.plot(X, -X**2, label='f(x) = -x^2')
plt.legend(loc='upper right')
# 1/x^2
fig, ax = myfig()
X1 = np.linspace(0.5, 10, 100)
X2 = np.linspace(-0.5, -10, 100)
ax.plot(X1, 1/X1**2, label='f(x) = 1/x^2')
ax.plot(X2, -1/X2**2, label='f(x) = -1/x^2')
plt.legend(loc='upper right')
# x^2-4 / x-2
fig, ax = myfig()
X = np.linspace(-4, 5, 10)
ax.plot(X, (X**2-4) / (X-2), label='f(x) = x^2-4 / x-2') # no value at x=2
ax.plot(X, (X + 2) + 1, label='f(x) = x + 2')
plt.scatter(X, (X**2 - 4) / (X - 2))
plt.legend(loc='upper right')
plt.show()
Plot Slope
Draw slope line from point
import numpy as np
import matplotlib.pyplot as plt
def myfig():
fig, ax = plt.subplots()
ax.set_xlabel('x')
ax.set_ylabel('f(x)')
ax.grid(True, which='both')
ax.axhline(y=0, color='k')
ax.axvline(x=0, color='k')
return fig, ax
fig, ax = myfig()
X = np.linspace(-2, 2, 100)
plt.plot(X, X**2, label='f(x) = x^2')
def plot_slope(x1, y1, slope):
# Calculate intercept "b" in y = ax + b
b = y1 - slope * x1
# Draw a point around the input point
x2, y2 = (x1 + 1, slope * (x1 + 1) + b)
# Draw start line point
plt.scatter(x1, y1)
plt.annotate('(%s, %s)'%(x1, y1), xy=(x1, y1), xytext=(x1, y1))
# Draw slope line
plt.plot((x1, x2), (y1, y2), linestyle='--', label='d(x) = 2x + %s' %b)
x1, y1 = (-1, 1)
slope = 2 * x1
plot_slope(x1, y1, slope)
x1, y1 = (-1.42, 2)
slope = 2 * x1
plot_slope(x1, y1, slope)
x1, y1 = (-2, 4)
slope = 2 * x1
plot_slope(x1, y1, slope)
plt.legend(loc='upper right')
plt.show()
Figure and Axes
We can then use axs.plot to draw some data.
"""
Simple line, subplots, bubbles
"""
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots() # Figure with single axes
# Lines
ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) # [x1, x2, x3, x4], [y1, ...
# Subplots
fig, axs = plt.subplots(1, 2) # Figure with 2x2 grid of axes
# Bubbles
np.random.seed(100000000)
data = {
'a': np.arange(50),
'c': np.random.randint(0, 50, 50),
'd': np.random.randn(50),
}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100
fix, ax = plt.subplots(figsize=(5, 2.7))
ax.scatter('a', 'b', c='c', s='d', data=data) # s=size, c=color
ax.set_xlabel('a')
ax.set_ylabel('b')
plt.show()
Usage Styles
There are essentially two ways to use Matplotlib.
""" Tow ways of using Matplotlib
Explicitly create Figures and Axes, and call methods on them (OOP) and ...
Rely on pyplot to create and manage Figures and Axes, end use functions
"""
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2, 100)
# OOP style
fix, ax = plt.subplots()
ax.plot(x, x, label='linear')
ax.plot(x, x**2, label='quadratic')
ax.plot(x, x**3, label='cubic')
ax.set_xlabel('x')
ax.set_ylabel('f(x)')
ax.legend()
# Pyplot style
plt.figure(figsize=(5, 2.7), layout='constrained')
plt.plot(x, x, label='linear')
plt.plot(x, x**2, label='quadratic')
plt.plot(x, x**3, label='cubic')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.legend()
plt.show()
Annotations
We can also annotate points on a plot
"""
Annotate points on plot
"""
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0.0, 5.0, 0.01)
y = np.cos(2 * np.pi * x)
fig, ax = plt.subplots(figsize=(5, 2.7))
ax.plot(x, y, lw=2)
ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='gray', shrink=0.05))
ax.set_ylim(-2, 2)
plt.show()
Annotations (plt)
Annotations when using plt scatter() function.
""" Annotations (when using plt.scatter)
"""
import matplotlib.pyplot as plt
xa = [1, 2, 3, 4]
ya = [5, 6, 7, 8]
plt.scatter(xa, ya, color='r', marker='x')
for i, p in enumerate(zip(xa, ya)):
plt.annotate(f"({p[0]}, {p[1]})", (p[0]+0.1, p[1]-.1))
plt.show()
Additional axis
Use twinx to add a new Axes with an invisible x-axis.
"""
Plotting data of different magnitude in one chart
may require an additional y-axis
"""
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x = np.arange(0.0, 5.0, 0.01)
y = np.cos(2 * np.pi * x)
l1, = ax.plot(x, y)
ax2 = ax.twinx() # invisible x-ax
l2, = ax2.plot(x, range(len(x)), 'C1')
plt.show()
Colored map
Often we want to have a third dimension in a plot.
"""
Third dimension in a plot represented by a colors in a colormap
"""
import matplotlib.pyplot as plt
import numpy as np
X, Y = np.meshgrid(np.linspace(-3, 3, 128), np.linspace(-3, 3, 128))
Z = (1 - X/2 + X**5 + Y**3) * np.exp(-X**2 - Y**2)
fig, ax = plt.subplots()
co = ax.contourf(X, Y, Z, levels=np.linspace(-1.25, 1.25, 11))
fig.colorbar(co)
ax.set_title('contourf()')
ax.set_xlabel('X')
ax.set_ylabel('Y')
plt.show()
Last update: 263 days ago