一、subplot2grid()是Matplotlib库中的一个函数,用于在特定的网格位置上创建子图。它可以让你自由地在网格中指定子图的位置、大小以及形状。
# 需求一: 利用subplot2grid()修改下列代码,使其运行结果如图所示(2行4列)
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的销售额", 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()
二、 subplot2grid函数
基本语法
subplot2grid((rows, cols), position, rowspan=None, colspan=None, **kwargs)
rows与cols这两个参数可以设置网格的行与列。
position这个参数是一个元组,可以设置子图位置。
rowspan参数与colspan参数分别表示子图占用的行数与列数。
**kwargs关键字参数会被传递给其他的绘图函数
基本参数
shape:是一个二维数组或者元组,表示子图所在网格的形状。
loc:是一个元组,表示子图在网格中的位置。
rowspan:表示子图在行方向上的跨度,如果不指定则默认为1。
colspan:表示子图在列方向上的跨度,如果不指定则默认为1。
三、实际操作
按上方要求,仅需修改少部分代码,使用subplot2grid()函数并设置其参数,即可达到效果。
#导入库
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.subplots(figsize=(24,10)) #设置画布尺寸
ax1=plt.subplot2grid((2,4),(0,1),colspan=2) #通过subplot2grid设置网格的行与列和子图的位置,划分子图区域以及子图所占的列数
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)) #通过subplot2grid设置网格的行与列和子图的位置,划分子图区域以及子图所占的列数
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)) #通过subplot2grid设置网格的行与列和子图的位置,划分子图区域以及子图所占的列数
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.savefig('C:\\Users\\Pictures\\Screenshots\\子图位置调整.png') #保存图片
plt.show()
注意:使用jupyter notebook如果使用默认画布尺寸可能无法达到我们想要的运行效果,这时我们可以加上%matplotlib notebook使图形作为交互对象呈现,或修改画布尺寸。
运行结果