matplotlib第3部分 布局格式定乾坤

布局格式定乾坤

1. 子图

1.1 使用 plt.subplots 绘制均匀状态下的子图

subplots 的函数格式如下:

fig , ax = plt.subplots(nrows, ncols)

nrows 与 ncols 表示两个整数参数,它们指定子图所占的行数、列数。不传入时默认值都为1。figsize 参数可以指定整个画布的大小,sharex 和 sharey 分别表示是否共享横轴和纵轴刻度,tight_layout 函数可以调整子图的相对大小使字符不会重叠。函数的返回值是一个元组,包括一个图形对象和所有的 axes 对象。其中 axes 对象的数量等于 nrows * ncols,且每个 axes 对象均可通过索引值访问(从1开始)。

import numpy as np
import matplotlib.pyplot as plt
fig,axs=plt.subplots(2,5,figsize=(10,4),sharex=True,sharey=True)
fig.suptitle('样例1',size=20)
for i in range(2):
    for j in range(5):
        axs[i][j].scatter(np.random.randn(10),np.random.randn(10))
        axs[i][j].set_title('第%d行,第%d列'%(i+1,j+1))
        axs[i][j].set_xlim(-5,5)
        axs[i][j].set_ylim(-5,5)
        if i==1:
            axs[i][j].set_xlabel('横坐标')
        if j==0:
            axs[i][j].set_ylabel('纵坐标')
fig.tight_layout()

在这里插入图片描述
subplot() 函数可以均等地划分画布,该函数的参数格式如下:

plt.subplot(nrows, ncols, index)

nrows 与 ncols 表示要划分几行几列的子区域(nrows*nclos表示子图数量),index 的初始值为1,用来选定具体的某个子区域。

plt.figure()
# 子图1
plt.subplot(2,2,1)
plt.plot([1,2],'r')
# 子图2
plt.subplot(2,2,2)
plt.plot([1,2],'b')
# 子图3
plt.subplot(224) # 当三位数都小于10时,可以省略中间的逗号,这行命令等价于plt.subplot(2,2,4)
plt.plot([1,2],'m')
plt.show()

在这里插入图片描述
可以通过projection方法创建极坐标系下的图表

# 极坐标
N=150
r=2*np.random.rand(N)
theta=2*np.pi*np.random.rand(N)
area=200*r**2
colors=theta
plt.subplot(projection='polar')
plt.scatter(theta,r,c=colors,s=area,cmap='hsv',alpha=0.75)
plt.show()

在这里插入图片描述

1.2 使用 GridSpac 绘制非均匀子图

所谓非均匀包含两层含义,第一是指图的比例大小不同但没有跨行或跨列,第二是指图为跨列或跨行状态。
利用 add_gridspec 可以指定相对宽度比例 width_ratios 和相对高度比例参数 height_ratios。

# 使用GridSpec 绘制非均匀子图
fig=plt.figure(figsize=(10,4))
spec=fig.add_gridspec(nrows=2,ncols=5,width_ratios=[1,2,3,4,5],height_ratios=[1,3])
fig.suptitle('样例2',size=20)
for i in range(2):
    for j in range(5):
        ax=fig.add_subplot(spec[i,j])
        ax.scatter(np.random.randn(10),np.random.randn(10))
        ax.set_title('第%d行,第%d列'%(i+1,j+1))
        if i==1: ax.set_xlabel('横坐标')
        if j==0: ax.set_ylabel('纵坐标')
fig.tight_layout()

在这里插入图片描述

fig=plt.figure(figsize=(10,4))
spec=fig.add_gridspec(nrows=2,ncols=6,width_ratios=[2,2.5,3,1,1.5,2],height_ratios=[1,2])
fig.suptitle('样例3',size=20)
#sub1
ax=fig.add_subplot(spec[0,:3])
ax.scatter(np.random.randn(10),np.random.randn(10))
#sub2
ax=fig.add_subplot(spec[0,3:5])
ax.scatter(np.random.randn(10),np.random.randn(10))
#sub3
ax=fig.add_subplot(spec[:,5])
ax.scatter(np.random.randn(10),np.random.randn(10))
#sub4
ax=fig.add_subplot(spec[1,0])
ax.scatter(np.random.randn(10),np.random.randn(10))
#sub5
ax=fig.add_subplot(spec[1,1:5])
ax.scatter(np.random.randn(10),np.random.randn(10))
fig.tight_layout()

在这里插入图片描述

2. 子图上的方法

常用直线的画法为: axhline, axvline, axline (水平、垂直、任意方向)

fig,ax=plt.subplots(figsize=(4,3))
ax.axhline(0.5,0.2,0.8)
ax.axvline(0.5,0.2,0.8)
ax.axline([0.3,0.3],[0.7,0.7]);

在这里插入图片描述
使用 grid 可以加灰色网格

fig,ax=plt.subplots(figsize=(4,3))
ax.grid(True)

在这里插入图片描述

思考题

  • 墨尔本1981年至1990年的每月温度情况。数据集来自github仓库下data/layout_ex1.csv,请利用数据,画出图。
  • 画出数据的散点图和边际分布。
# 读取数据
import pandas as pd
path='./layout_ex1.csv'
dg=pd.read_csv(path)
dg.head()

在这里插入图片描述

dg['Year']=pd.to_datetime(dg['Time']).dt.year
dg['Month']=pd.to_datetime(dg['Time']).dt.month
fig,axes=plt.subplots(2,5,figsize=(25,6),sharex=True,sharey=True)
fig.suptitle('墨尔本1981年至1990年月温度曲线')
t=0
g=0
for i,j in dg.groupby('Year'):
    if t<=4:
        axes[0][t].set_title('{}年'.format(i),size=12)
        axes[0][t].plot(j['Month'],j['Temperature'],'cD-')
        axes[0][t].grid(True)
        t+=1
    else:
        axes[1][g].set_title('{}年'.format(i),size=10)
        axes[1][g].plot(j['Month'],j['Temperature'],'yo:')
        axes[1][g].set_xticks(range(1,13))
        axes[1][g].grid(True)
        g+=1

在这里插入图片描述

  • 用 np.random.randn(2, 150) 生成一组二维数据,使用两种非均匀子图的分割方法,做出该数据对应的散点图和边际分布图
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
data=np.random.randn(2, 150) 
fig = plt.figure()
spec = gridspec.GridSpec(nrows=6, ncols=6, width_ratios=[1,1,1,1,1,1], height_ratios=[1,1,1,1,1,1])
#子图1
ax=fig.add_subplot(spec[0,:5])
ax.hist(data[0,:],bins=10,rwidth=0.8,color='y',alpha=0.5) 
for i in ['right','left','top','bottom']:
   ax.spines[i].set_visible(False) #边框不可见
ax.get_xaxis().set_visible(False) # x轴不可见
ax.get_yaxis().set_visible(False) # y轴不可见
#子图3
ax=fig.add_subplot(spec[1:,:5])
area=200*np.random.rand(150)
ax.scatter(data[0,:],data[1,:],c='m',marker='o',s=area,alpha=0.75)
ax.grid(True)
ax.set_xlabel('my_data_x')
ax.set_ylabel('my_data_y')
#子图4
ax=fig.add_subplot(spec[1:,5:6])
ax.hist(data[1,:],orientation='horizontal',bins=10,rwidth=0.8,color='y',alpha=0.5)
for i in ['right','left','top','bottom']:
   ax.spines[i].set_visible(False)
ax.get_xaxis().set_visible(False) # x轴不可见
ax.get_yaxis().set_visible(False) # y轴不可见
plt.tight_layout()

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Matplotlib是一个强大的Python数据可视化库,可以用于创建各种类型的图形。分块图布局是一种将图形分成多块,并在每块中显示不同图形的布局方式。 要创建分块图布局,可以使用Matplotlib中的子图功能。子图类似于将画布分成多个网格,并在每个网格中显示不同的图形。 首先,我们需要导入Matplotlib库并创建一个画布和子图对象。可以使用`plt.subplots`函数来创建画布和子图对象。例如,`fig, axes = plt.subplots(nrows, ncols)`会创建一个包含nrows行和ncols列的子图。 然后,可以使用`axes`对象进行绘图操作。每个子图都可以看作是一个坐标轴对象,可以使用常见的Matplotlib绘图函数(如`plot`,`bar`,`scatter`等)来在每个子图中绘图。 下面是一个简单的示例: ```python import matplotlib.pyplot as plt # 创建一个包含2行2列的子图布局 fig, axes = plt.subplots(nrows=2, ncols=2) # 在第一个子图绘制折线图 axes[0, 0].plot([1, 2, 3, 4], [1, 4, 9, 16]) axes[0, 0].set_title('折线图') # 在第二个子图绘制柱状图 axes[0, 1].bar(['A', 'B', 'C', 'D'], [3, 7, 2, 9]) axes[0, 1].set_title('柱状图') # 在第三个子图绘制散点图 axes[1, 0].scatter([1, 2, 3, 4], [1, 4, 9, 16]) axes[1, 0].set_title('散点图') # 在第四个子图绘制饼图 axes[1, 1].pie([30, 40, 20, 10]) axes[1, 1].set_title('饼图') # 调整子图之间的间距 plt.tight_layout() # 显示图形 plt.show() ``` 在这个示例中,我们使用`subplots`函数创建了一个2行2列的子图布局。然后,使用`plot`函数在第一个子图绘制了折线图,在第二个子图绘制了柱状图,在第三个子图绘制了散点图,在第四个子图绘制了饼图。最后,调用`tight_layout`函数来自动调整子图之间的间距,并使用`show`函数显示图形。 这就是使用Matplotlib创建分块图布局的基本方法。通过更改子图的行数和列数,并在每个子图绘制不同类型的图形,可以创建灵活多样的分块图布局
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值