导入模块
import matplotlib.pyplot as plt
import numpy as np
1.带子图的图标
要点:利用add_axes()函数 在figure上定义两个Axes对象
x1 = np.arange(10)
y1 = np.array([2,3,9,1,7,3,2,4,3,5])
x2 = np.arange(10)
y2 = np.array([4,5,6,6,7,2,1,7,8,4])
fig = plt.figure()
ax = fig.add_axes([0,0,1,1]) #相当于图像在(0,0)为起始点,长宽分别为1,1的方形区域中
inner_ax = fig.add_axes([0.6,0.6,0.35,0.35]) #添加的第二张图像以(0.6,0.6)为起始点,长宽分别为0.35,0.35的方形区域中
ax.plot(x1,y1)
inner_ax.plot(x2,y2)
ax.set_xlabel('A')
ax.set_ylabel('B')
inner_ax.set_xlabel('A')
inner_ax.set_ylabel('B')
plt.show()
2.多个不同子图
要点:利用subplots()函数添加多个子图,再用GridSpec()函数来管理
x1 = np.arange(5)
y1 = np.array([2,3,9,1,7])
x2 = np.arange(5)
y2 = np.array([4,5,7,8,4])
x3 = np.arange(5)
y3 = np.array([3,2,4,3,5])
x4 = np.arange(5)
y4 = np.array([2,1,7,8,4])
x5 = np.arange(5)
y5 = np.array([6,6,7,2,1])
fig = plt.figure(figsize=(6,6))
gs = plt.GridSpec(3,3) #分成三行三列的格网
s1 = fig.add_subplot(gs[0,:2])
s2 = fig.add_subplot(gs[1,:2])
s3 = fig.add_subplot(gs[2,0])
s4 = fig.add_subplot(gs[:2,2])
s5 = fig.add_subplot(gs[2,1:3])
s1.plot(x1,y1,'c--')
s2.plot(x2,y2,'^')
s3.scatter(x3,y3,marker='*')
s4.barh(x4,y4,color='b',alpha=0.5,xerr=[0.2,0.5,0.4,0.8,0.6],error_kw={'ecolor':'r','capsize':3})
s5.bar(x5,y5,color='w',hatch='///')
plt.show()
参考:
法比奥·内利. Python数据分析实战:第2版.北京:人民邮电出版社, 2019.11.