一、绘制固定区域子图
matplotlib可以将整个画布规划成等分布局的mn(行列)的矩阵区域,并按照先行后列的·方式对每个区域进行编号(编号从1开始),之后在选中的某个区域或某些区域中绘制单个‘或多个子图。
(1)绘制单子图
使用pyplot的subplot()函数可以规划好的某个区域中绘制单个子图,subplot()函数的语法格式如下:
subplot(nrows,ncols,index,projection,polar,sharex,sharey,label,**kwargs)
例子:
将画布规划成32的矩阵区域,并在索引为6的区域中绘制子图;再将画布规划成31的矩阵区域,并在索引为2的区域绘制子图,代码如下:
%matplotlib inline
import matplotlib.pyplot as plt
ax_one = plt.subplot(326)
ax_one.plot([1, 2, 3, 4, 5])
ax_two = plt.subplot(312)
ax_two.plot([1, 2, 3, 4, 5])
plt.title("20200806903017")
plt.show()
运行结果:
#实例某工厂A,B产品销售额分析、
代码如下:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ["SimHei"]
x = [x for x in range(1, 13)]
y1 = [20, 28, 23, 16, 29, 36, 39, 33, 31, 19, 21, 25]
y2 = [17, 22, 39, 26, 35, 23, 25, 27, 29, 38, 28, 20]
labels = ['1 月', '2 月', '3 月', '4 月', '5 月', '6 月', '7月', '8 月', '9 月', '10 月', '11 月', '12 月']
ax1 = plt.subplot(211)
ax1.plot(x, y1, 'm--o', lw=2, ms=5, label='产品A')
ax1.plot(x, y2, 'g--o', lw=2, ms=5, label='产品B')
ax1.set_title("产品A 与产品B的销售额2020080603017", fontsize=11)
ax1.set_ylim(10, 45)
ax1.set_ylabel('销售额(亿元)')
ax1.set_xlabel('月份')
for xy1 in zip(x, y1):
ax1.annotate("%s" % xy1[1], xy=xy1, xytext=(-5, 5), textcoords='offset points')
for xy2 in zip(x, y2):
ax1.annotate("%s" % xy2[1], xy=xy2, xytext=(-5, 5), textcoords='offset points')
ax1.legend()
ax2 = plt.subplot(223)
ax2.pie(y1, radius=1, wedgeprops={'width':0.5}, labels=labels, autopct='%3.1f%%', pctdistance=0.75)
ax2.set_title('产品A的销售额 ')
ax3 = plt.subplot(224)
ax3.pie(y2, radius=1, wedgeprops={'width':0.5}, labels=labels,autopct='%3.1f%%', pctdistance=0.75)
ax3.set_title('产品B的销售额 ')
plt.tight_layout()
plt.show()
运行结果:
(2)、绘制多子图
使用pylot的subplots()函数可以在规划好的所有区域中一次绘制多个子图。subplots()函数的语法格式如下:
subplots(nrows=1,ncols=1,sharex=False,sharey=False,squeeze=True,
subplot_kw=None,gridspec_kw=None,**fig_kw)
案例:将画布规划成2*2的矩形区域,之后在第3个区域中绘制子图,
代码如下:
%matplotlib inline
import matplotlib.pyplot as plt
fig, ax_arr = plt.subplots(2, 2)
ax_thr = ax_arr[1, 0]
ax_thr.plot([1, 2, 3, 4, 5])
运行结果:
#实例养猫养狗人群比例分析
代码如下:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ["Si