【matplotlib可视化】布局

本文详细探讨了matplotlib库中的布局技巧,包括如何创建均匀和非均匀子图,如plt.subplots用于生成均匀子图,fig.add_gridspec用于实现非均匀布局。文章还介绍了如何调整子图比例、跨行跨列以及使用各种图形元素,如线图、直方图、散点图、条形图、饼图等。同时,讲解了坐标轴的设置、文本注释和图例的使用,帮助读者掌握matplotlib的高级可视化技术。
摘要由CSDN通过智能技术生成

matplotlib 布局

子图

plt.subplots均匀子图

fig, axs = plt.subplots(2, 5, figsize=(10, 4), sharex=True, sharey=True)

  • 返回元素分别是画布和子图构成的列表

  • 第一个数字为行,第二个为列

  • figsize 参数可以指定整个画布的大小

  • sharexsharey 分别表示是否共享横轴和纵轴刻度

  • tight_layout 函数可以调整子图的相对大小使字符不会重叠

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()

在这里插入图片描述

⭐极坐标系plt.subplot没有s

plt.subplot(projection="polar")

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')   # 要用subplot
plt.scatter(theta, r, c=colors, s=area, cmap='hsv', alpha=0.75)
# cmap: 配色方案
# c:color
# s: scale
# alpha:透明度

在这里插入图片描述

fig.add_gridspec非均匀子图

所谓非均匀包含两层含义,第一是指图的比例大小不同但没有跨行或跨列,第二是指图为跨列或跨行状态

spec = fig.add_gridspec(nrows, ncols, width_ratios, height_ratios)

  • width_ratios 可以指定相对宽度比例
  • height_ratios相对高度比例参数

搭配ax = fig.add_subplot(spec[i,j])

图的比例大小不同
fig = plt.figure(figsize=(10, 4))
spec = fig.add_gridspec(nrows=2, ncols=5, width_ratios=[1,2,3,4,5]
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值