Python数据分析可视化---深入解析图表绘制工具Matplotlib子图

在matplotlib中,整个图像为一个Figure图像,在每个Figure图像中可以包含一个或多个Axes图像,每个Axes图像都是一个拥有自己坐标系统的绘图区域
(1)在一个Figure中绘制多个图表

fig1 = plt.figure(num=1,figsize=(4,2))
plt.plot(np.random.rand(50).cumsum(),'k--')
fig2 = plt.figure(num=2,figsize=(4,2))
plt.plot(50-np.random.rand(50).cumsum(),'k--')

输出结果:
在这里插入图片描述
其中figure函数的参数中,num为图表序号,figsize为图表大小,还可以通过dpi设置其分辨率,如果在绘图的时候不写plt.figure(),则最后会默认生成一个图表
(2)子图创建1—先建立子图然后填充图表
我们可以先创建好子图的框架,然后再创建图表来填充子图,比如:

fig = plt.figure(figsize=(10,6),facecolor = 'gray')#背景颜色为gray

ax1 = fig.add_subplot(2,2,1)  # 创建2*2四个子图,ax1为第一个

填充子图:

plt.plot(np.random.rand(50).cumsum(),'k--')
plt.plot(np.random.randn(50).cumsum(),'b--')

创建其他的子图并填充

ax2 = fig.add_subplot(2,2,2)  # 第一行的右图
ax2.hist(np.random.rand(50),alpha=0.5)

ax4 = fig.add_subplot(2,2,4)  # 第二行的右图
df2 = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
ax4.plot(df2,alpha=0.5,linestyle='--',marker='.')

输出结果:
在这里插入图片描述
(3)子图创建2—创建一个新的figure,并返回一个subplot对象的numpy数组
这种方法是调用plt.subplots( ) 的方法来实现

fig,axes = plt.subplots(2,3,figsize=(10,4))
ts = pd.Series(np.random.randn(1000).cumsum())
print(axes, axes.shape, type(axes))
#生成图表对象的数组

ax1 = axes[0,1]#子图为第0行第1个
ax1.plot(ts)#绘制子图

输出结果:
在这里插入图片描述
(4)参数调整
调用plt.subplot( ) 时可以适当调整其参数,比如不同的子图是否共享其x和y刻度:

fig,axes = plt.subplots(2,2,sharex=True,sharey=True)

通过plt.subplots_adjust( ) 的参数wspace和hspace来控制宽度和高度的百分比,比如subplot之间的间距

for i in range(2):
    for j in range(2):
        axes[i,j].hist(np.random.randn(500),color='k',alpha=0.5)
plt.subplots_adjust(wspace=0,hspace=0)

在这里插入图片描述
(5)子图创建3—多系列图,分别绘制
可以将一个Dataframe的不同columns分别绘制到不同的子图中

df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))#创建Dataframe
df = df.cumsum()#提取columns

df.plot(style = '--.',alpha = 0.4,grid = True,figsize = (8,8),
       subplots = True,
       layout = (2,3),
       sharex = False)#subplots是否分别绘制子图

plt.subplots_adjust(wspace=0,hspace=0.2)

输出结果:
在这里插入图片描述
这篇博客和前两篇博客的内容就是matplotlib的一些基础知识了,从下一篇博客开始将要写matplotlib的一些具体的绘制方法

关注欢喜,走向成功~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值