使用subplot2grid()函数可以将整个画布规划成非等分布局的区域,并可在选中的某个区域中绘制单个字图,subplot2grid()函数的语法格式如下:
subplot2grid(shape,loc,rowspan=1,colspan=1,fig=None,**kwargs)
shape | 表示规划的区域结构,是一个包含两个整数数据的元组。 |
loc | 表示选择区域的位置,列数从0开始。 |
rowspan | 表示向下跨越的行数,默认为1。 |
colspan | 表示向右跨越的列数,默认为1. |
fig | 表示放置子图的画布,默认为当前画布。 |
需求一? 利用subplot2grid()修改下列代码,使其运行结果如图所示(2行4列)
代码显示如下:
%matplotlib auto #弹出窗口显示
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.subplot2grid((2,4), (0,1),colspan=2)
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的销售额", 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.subplot2grid((2,4), (1,0))
ax2.pie(y1, radius=1, wedgeprops={'width':0.5}, labels=labels, autopct='%3.1f%%', pctdistance=0.75)
#添加第二个子图的标题
ax2.set_title('产品A的销售额 ')
# 绘制第三个子图
ax3 = plt.subplot2grid((2,4), (1,3))
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()
代码运行效果如下:
1、-------- subplot()函数先划分m行*n个等分区域,然后在指定的区域内创建一个“坐标系实例”,总共m*n个实例打包成数组返回。(注:若指定区域已经有图标存在,它会先清空指定区域的已有的坐标系图例。)
2、--------- subplots()函数先划分m行*n个等分区域,然后在各区域内创建一个“坐标系实例”,总共m*n个实例打包成数组返回。
3、---------- %matplotlib auto 通过弹出的可交互GUI窗口来展示图标,可清晰地看出绘图区域的划分情况