1.导包
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['font.sans-serif'] = "SimHei"
plt.rcParams["axes.unicode_minus"] = False
%config Inlinebackend.figure_format = "svg"
2.subplot()函数
fig = plt.figure(figsize=(8,5))
x = np.linspace(-np.pi,np.pi,30)
y = np.sin(x)
ax1 = plt.subplot(2,2,1)
ax1.plot(x,y)
ax1.set_title("子图1")
ax2 = plt.subplot(2,2,2)
ax2.plot(x,y)
ax2.set_title("子图2")
ax3 = plt.subplot(2,2,3)
ax3.plot(x,y)
ax3.set_title("子图3")
ax4 = plt.subplot(2,2,4)
ax4.plot(x,y)
ax4.set_title("子图4")
fig.tight_layout()
plt.figure(figsize=(8,5))
x = np.linspace(-np.pi,np.pi,30)
y = np.sin(x)
ax1 = plt.subplot(2,2,1)
ax1.plot(x,y)
ax2 = plt.subplot(2,2,2)
ax2.plot(x,y)
ax3 = plt.subplot(2,1,2)
ax3.plot(x,np.sin(x*x))
[<matplotlib.lines.Line2D at 0x136d47df410>]
3.使用 subplots() 函数
x = np.linspace(0, 2*np.pi)
fig, ax = plt.subplots(3, 3)
ax1, ax2, ax3 = ax
ax11, ax12, ax13 = ax1
ax21, ax22, ax23 = ax2
ax31, ax32, ax33 = ax3
fig.set_figwidth(8)
fig.set_figheight(8)
ax11.plot(x, np.sin(x))
ax12.plot(x, np.cos(x))
ax13.plot(x, np.tan(x))
ax21.plot(x, np.tanh(x))
ax22.plot(x, np.cosh(x))
ax23.plot(x, np.sinh(x))
ax31.plot(x, np.sin(x) + np.cos(x))
ax32.plot(x, np.sin(x*x) + np.cos(x*x))
ax33.plot(x, np.sin(x) * np.cos(x))
plt.tight_layout()
4.图形嵌套
fig = plt.figure(figsize=(8,5))
axes1 = fig.add_subplot(1, 1, 1)
axes1.plot([0, 1], [1, 3])
axes2 = fig.add_subplot(2, 2, 1, facecolor="pink")
axes2.plot([1, 3])
[<matplotlib.lines.Line2D at 0x136d69e1490>]
- 使用 axes() 函数 和 add_axes() 函数
fig = plt.figure(figsize=(8,5))
x = np.linspace(0, 2*np.pi, 30)
y = np.sin(x)
plt.plot(x, y)
axes1 = plt.axes([0.55, 0.55, 0.3, 0.3])
axes1.plot(x, y, color="g")
axes2 = fig.add_axes([0.18, 0.18, 0.3, 0.3])
axes2.plot(x, y, color="r")
[<matplotlib.lines.Line2D at 0x136d7336c10>]
5.双轴显示
plt.figure(figsize=(6, 4))
x = np.linspace(0, 10, 100)
axes1 = plt.gca()
axes1.plot(x, np.exp(x), c="r")
axes1.set_xlabel("time")
axes1.set_ylabel("exp", c="r")
axes1.tick_params(axis="y", labelcolor="red")
axes2 = axes1.twinx()
axes2.plot(x, np.sin(x), c="b")
axes2.set_ylabel("sin", c="b")
axes2.tick_params(axis="y", labelcolor="blue")
plt.tight_layout()