利用subplot2grid功能来画图

先导入所需要的库

import numpy as np
import matplotlib.pyplot as plt

设置中文样式

plt.rcParams['font.sans-serif'] = ['SimHei']

导入数据

x = [x for i 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 月']

开始编写绘制图形代码

首先,先解释一下matplotlib中的subplot2grid。

它是用来创建一个子图网格

以下是它的语法

plt.subplot2grid(shape, loc, rowspan)

  • shape: 这个是一个元组,表示网格的大小。例如,(3, 3)表示一个3x3的网格。
  • loc: 这是一个元组,表示子图在网格中的位置。例如,(0, 0)表示左上角的子图。
  • rowspan: 这个参数表示子图应跨越多少行。默认情况下,它为1,即子图只占据一行。如果你想让子图跨越两行,那么可以将它设为2

绘制第一个子图

ax1 = plt.subplot2grid(shape=(2, 4), loc=(0, 1), colspan=2)#设置子图位置
ax1.plot(x, y1, 'm--o', lw=2, ms=5, label='产品A')#折线图1
ax1.plot(x, y2, 'g--o', lw=2, ms=5, label='产品B')#折线图2
ax1.set_title("产品A 与产品B的销售额", fontsize=11)#设置整体标题
ax1.set_ylim(10, 45) #设置y轴的长度
ax1.set_ylabel('销售额(亿元)')#设置y轴标题
ax1.set_xlabel('月份')#设置x轴标题
for xy1 in zip(x, y1): #zip内置函数,用于打包参数
    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()#添加图例

第二个子图(饼图) 

x2 = plt.subplot2grid(shape=(2, 4), loc=(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(shape=(2, 4), loc=(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()#展示图例

 效果图

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值