Matlab的使用补充

Matlab的使用补充

1.子图

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

返回元素分别是画布和子图构成的列表,第一个数字为行,第二个为列

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

image-20231128175715802

2.使用GridSpec绘制非均匀子图

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

利用 add_gridspec 可以指定相对宽度比例 width_ratios 和相对高度比例参数 height_ratios

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

样例如下所示:

image-20231128175816708

二、子图上的方法

ax 对象上定义了和 plt 类似的图形绘制函数,常用的有: plot, hist, scatter, bar, barh, pie

分别对应的为画直线、直方图、散点图、柱状图、饼状图等。

使用 set_xscale, set_title, set_xlabel 分别可以设置坐标轴的规度(指对数坐标等)、标题、轴名

代码实例

fig, axs = plt.subplots(1, 2, figsize=(10, 4))
fig.suptitle('大标题', size=20)
for j in range(2):
    axs[j].plot(list('abcd'), [10**i for i in range(4)])
    if j==0:
        axs[j].set_yscale('log')
        axs[j].set_title('子标题1')
        axs[j].set_ylabel('对数坐标')
    else:
        axs[j].set_title('子标题1')
        axs[j].set_ylabel('普通坐标')
fig.tight_layout()

三、Matlab上的文本内容详解

1、Figure和Axes上的文本

Matplotlib具有广泛的文本支持,包括对数学表达式的支持、对栅格和矢量输出的TrueType支持、具有任意旋转的换行分隔文本以及Unicode支持。

下面的命令是介绍了通过pyplot API和objected-oriented API分别创建文本的方式。

pyplot APIOO APIdescription
texttextAxes的任意位置添加text。
titleset_titleAxes添加title
figtexttextFigure的任意位置添加text.
suptitlesuptitleFigure添加title
xlabelset_xlabelAxes的x-axis添加label
ylabelset_ylabelAxes的y-axis添加label
annotateannotateAxes的任意位置添加带有可选箭头的标注.

2.text

pyplot API:matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs)
OO API:Axes.text(self, x, y, s, fontdict=None, **kwargs)
参数:此方法接受以下描述的参数:
s:此参数是要添加的文本。
xy:此参数是放置文本的点(x,y)。
fontdict:此参数是一个可选参数,并且是一个覆盖默认文本属性的字典。如果fontdict为None,则由rcParams确定默认值。
返回值:此方法返回作为创建的文本实例的文本。

fontdict主要参数具体介绍,更多参数请参考官网说明

PropertyDescription
alphafloat or None 该参数指透明度,越接近0越透明,越接近1越不透明
backgroundcolorcolor 该参数指文本的背景颜色,具体matplotlib支持颜色如下
bboxdict with properties for patches.FancyBboxPatch 这个是用来设置text周围的box外框
color or ccolor 指的是字体的颜色
fontfamily or family{FONTNAME, ‘serif’, ‘sans-serif’, ‘cursive’, ‘fantasy’, ‘monospace’} 该参数指的是字体的类型
fontproperties or font or font_propertiesfont_manager.FontProperties or str or pathlib.Path
fontsize or sizefloat or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’} 该参数指字体大小
fontstretch or stretch{a numeric value in range 0-1000, ‘ultra-condensed’, ‘extra-condensed’, ‘condensed’, ‘semi-condensed’, ‘normal’, ‘semi-expanded’, ‘expanded’, ‘extra-expanded’, ‘ultra-expanded’} 该参数是指从字体中选择正常、压缩或扩展的字体
fontstyle or style{‘normal’, ‘italic’, ‘oblique’} 该参数是指字体的样式是否倾斜等
fontweight or weight{a numeric value in range 0-1000, ‘ultralight’, ‘light’, ‘normal’, ‘regular’, ‘book’, ‘medium’, ‘roman’, ‘semibold’, ‘demibold’, ‘demi’, ‘bold’, ‘heavy’, ‘extra bold’, ‘black’}
horizontalalignment or ha{‘center’, ‘right’, ‘left’} 该参数是指选择文本左对齐右对齐还是居中对齐
labelobject
linespacingfloat (multiple of font size)
position(float, float)
rotationfloat or {‘vertical’, ‘horizontal’} 该参数是指text逆时针旋转的角度,“horizontal”等于0,“vertical”等于90。我们可以根据自己设定来选择合适角度
verticalalignment or va{‘center’, ‘top’, ‘bottom’, ‘baseline’, ‘center_baseline’}

3.字体的属性设置

字体设置一般有全局字体设置和自定义局部字体设置两种方法。

#首先可以查看matplotlib所有可用的字体
from matplotlib import font_manager
font_family = font_manager.fontManager.ttflist
font_name_list = [i.name for i in font_family]
for font in font_name_list:
    print(f'{font}\n')

4.数学表达式

在文本标签中使用数学表达式。有关MathText的概述,请参见 写数学表达式,但由于数学表达式的练习想必我们都在markdown语法和latex语法中多少有接触,故在此不继续展开,愿意深入学习的可以参看官方文档.下面是一个官方案例,供参考了解。

import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)

plt.plot(t, s)
plt.title(r'$\alpha_i > \beta_i$', fontsize=20)
plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20)
plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$',
         fontsize=20)
plt.xlabel('time (s)')
plt.ylabel('volts (mV)')
plt.show()

image-20231128180253238

四、Matlab的绘图样式

在matplotlib中,要想设置绘制样式,最简单的方法是在绘制元素时单独设置样式。 但是有时候,当用户在做专题报告时,往往会希望保持整体风格的统一而不用对每张图一张张修改,因此matplotlib库还提供了四种批量修改全局样式的方式

1.matplotlib预先定义样式

matplotlib贴心地提供了许多内置的样式供用户使用,使用方法很简单,只需在python脚本的最开始输入想使用style的名称即可调用,尝试调用不同内置样式,比较区别

plt.style.use('default')
plt.plot([1,2,3,4],[2,3,4,5])

plt.style.use('ggplot')
plt.plot([1,2,3,4],[2,3,4,5])

那么matplotlib究竟内置了那些样式供使用呢?总共以下26种丰富的样式可供选择。

print(plt.style.available)

image-20231128180510156

2.用户自定义stylesheet

在任意路径下创建一个后缀名为mplstyle的样式清单,编辑文件添加以下样式内容

axes.titlesize : 24
axes.labelsize : 20
lines.linewidth : 3
lines.markersize : 10
xtick.labelsize : 16
ytick.labelsize : 16

引用自定义stylesheet后观察图表变化。

plt.style.use('file/presentation.mplstyle')
plt.plot([1,2,3,4],[2,3,4,5])

image-20231128180551971

5.参考链接

5.参考链接

Matplotlib实践 -AI学习-阿里云天池 (aliyun.com)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值