datawhale matplotlib(3)

本文介绍了使用Matplotlib进行科学绘图的方法,包括布局格式、子图管理、直角坐标系及极坐标系的使用技巧,并提供了GridSpec非均匀子图的具体实现方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

布局格式

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']   #用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False   #用来正常显示负号

子图

方法

ax.plot, hist, scatter, bar, barh, pie
ax. axhline, axvline, axline (水平、垂直、任意方向)

plt.axhline(y=0.0, c=“r”, ls="–", lw=2)可以绘制辅助线
y:水平参考线的出发点
c:参考线的线条颜色
ls:参考线的线条风格
lw:参考线的线条宽度

ax.grid 添加灰色网格
ax.set_xscale, set_title, set_xlabel 分别可以设置坐标轴的规度(指对数坐标等)、标题、轴名

fig.suptitle('大标题', size=20)
axs[j].set_title('子标题1')

在这里插入图片描述
ax.legend, annotate, arrow, text

legend(loc=?)
best:0
upper right:1
upper left:2
lower left:3
lower right:4
right:5
center left:6
center right:7
lower center:8
upper center:9
center:10

对应都有例如plt.legend之类的命令

subplots

直角坐标系

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

sharex 和 sharey 分别表示是否共享横轴和纵轴刻度

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

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

极坐标系

plt.subplot(projection='polar')

GridSpec 非均匀子图

利用 add_gridspec 可以指定相对宽度比例 width_ratios 和相对高度比例参数 height_ratios。 spec[i, j]可以不跨图也可以跨图 。

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

报错: ‘Figure’ object has no attribute ‘add_gridspec’
需要更新matplotlib的版本
不跨图
跨图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值