matplotlib_4 文字和图例

matplotlib_4 文字和图例

一、Figure和Axes上的文本

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

1.文本API介绍

通过pyplot API和objected-oriented API分别创建文本的方式:

pyplot APIOO APIdescription
texttext在子图axes的任意位置添加文本
annotateannotate在子图axes的任意位置添加注解,包含指向性的箭头
xlabelset_xlabel为子图axes添加x轴标签
ylabelset_ylabel为子图axes添加y轴标签
titleset_title为子图axes添加标题
figtexttext在画布figure的任意位置添加文本
suptitlesuptitle为画布figure添加标题

通过一个综合例子,以OO模式展示这些API是如何控制一个图像中各部分的文本,后续再详细分析这些api的使用技巧。

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot()
# 分别为figure和ax设置标题,注意两者的位置是不同的
fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')
ax.set_title('axes title')
# 设置x和y轴标签
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')
# 设置x和y轴显示范围均为0到10
ax.axis([0, 10, 0, 10])
# 在子图上添加文本
ax.text(3, 8, 'boxed italics text in data coords', style='italic',
        bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 10})
# 在画布上添加文本,一般在子图上添加文本是更常见的操作,这种方法很少用
fig.text(0.4,0.8,'This is text for figure')

ax.plot([2], [1], 'o')
# 添加注解
ax.annotate('annotate', xy=(2, 1), xytext=(3, 4),arrowprops=dict(facecolor='black', shrink=0.05))
plt.show()

在这里插入图片描述

2.text - 子图上的文本

text的调用方式为Axes.text(x, y, s, fontdict=None, **kwargs)
参数说明:
x,y为文本出现的位置,默认状态下即为当前坐标系下的坐标值,
s为文本的内容,
fontdict是可选参数,用于覆盖默认的文本属性,
**kwargs为关键字参数,也可以用于传入文本样式参数

fontdict和**kwargs参数,都可以用于调整呈现的文本样式,最终效果是一样的,不仅text方法,其他文本方法如set_xlabel,set_title等同样适用这两种方式修改样式:

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,3))
axes = fig.subplots(1,2)

# 使用关键字参数修改文本样式
axes[0].text(0.3, 0.8, 'modify by **kwargs', style='italic',
        bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 10});

# 使用fontdict参数修改文本样式
font = {'bbox':{'facecolor': 'red', 'alpha': 0.5, 'pad': 10}, 'style':'italic'}
axes[1].text(0.3, 0.8, 'modify by fontdict', fontdict=font)
plt.show()

在这里插入图片描述

matplotlib中所有支持的样式参数(以及例子如热力图、箱线图等)请参考官网文档说明,大多数时候需要用到的时候再查询即可。

一些常用的参数:

PropertyDescription
alphafloat or None 透明度,越接近0越透明,越接近1越不透明
backgroundcolorcolor 文本的背景颜色
bboxdict with properties for patches.FancyBboxPatch 用来设置text周围的box外框
color or ccolor 字体的颜色
fontfamily or family{FONTNAME, ‘serif’, ‘sans-serif’, ‘cursive’, ‘fantasy’, ‘monospace’} 字体的类型
fontsize or sizefloat or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’} 字体大小
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’} 选择文本左对齐右对齐还是居中对齐
linespacingfloat (multiple of font size) 文本间距
rotationfloat or {‘vertical’, ‘horizontal’} 指text逆时针旋转的角度,“horizontal”等于0,“vertical”等于90
verticalalignment or va{‘center’, ‘top’, ‘bottom’, ‘baseline’, ‘center_baseline’} 文本在垂直角度的对齐方式

3.xlabel和ylabel - 子图的x,y轴标签

xlabel(ylabel)的调用方式为Axes.set_xlabel(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)
参数说明:
xlabel即为标签内容,
fontdict**kwargs用来修改样式,同上一小节
labelpad为标签和坐标轴的距离,默认为4,
loc为粗略调整标签位置,可选的值为’left’, ‘center’, 'right’之一,默认为居中;
精确设置标签位置:position参数+horizontalalignment参数
position由一个元组组成,第一个元素0.2表示x轴标签在x轴的位置,第二个元素对于xlabel其实是无意义的,随便填一个数都可以
horizontalalignment='left’表示左对齐,这样设置后x轴标签就能精确定位在x=0.2的位置处

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,3))
axes = fig.subplots(1,2)
axes[0].set_xlabel('xlabel',labelpad=20,loc='left')
axes[1].set_xlabel('xlabel', position=(0.2, 0.4), horizontalalignment='left')
plt.show()

在这里插入图片描述

4.title和suptitle - 子图和画布的标题

子图标题 title的调用方式为Axes.set_title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)
参数介绍:
label为子图标签的内容,
fontdict,loc,**kwargs和之前相同,
pad是指标题偏离图表顶部的距离,默认为6
y是title所在子图垂向的位置。默认值为1,即title位于子图的顶部。

画布标题 suptitle的调用方式为figure.suptitle(t, **kwargs)
参数说明:t为画布的标题内容

# 观察pad参数的使用效果
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,3))
fig.suptitle('This is figure title',y=1.2) # 通过参数y设置高度
axes = fig.subplots(1,2)
axes[0].set_title('This is title',pad=15)
axes[1].set_title('This is title',pad=6)

在这里插入图片描述

5.annotate - 子图的注解

annotate的调用方式为Axes.annotate(text, xy, *args, **kwargs)
参数介绍:
text为注解的内容,
xy为注解箭头指向的坐标,
xytext为注解文字的坐标,
xycoords用来定义xy参数的坐标系,
textcoords用来定义xytext参数的坐标系,
arrowprops用来定义指向箭头的样式
annotate的参数非常复杂,这里仅仅展示一个简单的例子,更多参数可以查看官方文档中的annotate介绍

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot()
ax.annotate("",
            xy=(0.2, 0.2), xycoords='data',
            xytext=(0.8, 0.8), textcoords='data',
            arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0.2")
            )
plt.show()

在这里插入图片描述

6.字体的属性设置

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

为方便在图中加入合适的字体,可以尝试了解中文字体的英文名称 该链接说明了常用中文的英文名称

全局字体设置

修改字体默认属性,完成全局字体的更改。

plt.rcParams['font.sans-serif'] = ['SimSun']    # 指定默认字体为新宋体。
plt.rcParams['axes.unicode_minus'] = False      # 解决保存图像时 负号'-' 显示为方块和报错的问题。
自定义局部字体设置
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
plt.plot(x, label='小示例图标签')

# 直接用字体的名字
plt.xlabel('x 轴名称参数', fontproperties='Microsoft YaHei', fontsize=16)         # 设置x轴名称,采用微软雅黑字体
plt.ylabel('y 轴名称参数', fontproperties='Microsoft YaHei', fontsize=14)         # 设置Y轴名称
plt.title('坐标系的标题',  fontproperties='Microsoft YaHei', fontsize=20)         # 设置坐标系标题的字体
plt.legend(loc='lower right', prop={"family": 'Microsoft YaHei'}, fontsize=10)  # 小示例图的字体设置
plt.show()

在这里插入图片描述

二、Tick上的文本

设置tick(刻度)和ticklabel(刻度标签)

1.简单模式

可以使用axis的set_ticks方法手动设置标签位置;使用axis的set_ticklabels方法手动设置标签格式。

使用axis的set_ticks方法手动设置刻度位置
import numpy as np
import matplotlib.pyplot as plt
x1 = np.linspace(0.0, 5.0, 100)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True)
axs[0].plot(x1, y1)
axs[1].plot(x1, y1)
axs[1].xaxis.set_ticks(np.arange(0., 10.1, 2.))
plt.show()

在这里插入图片描述

使用axis的set_ticklabels方法手动设置刻度标签格式
import numpy as np
import matplotlib.pyplot as plt
x1 = np.linspace(0.0, 5.0, 100)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True)
axs[0].plot(x1, y1)
axs[1].plot(x1, y1)
ticks = np.arange(0., 8.1, 2.)
tickla = [f'{tick:1.2f}' for tick in ticks]
axs[1].xaxis.set_ticks(ticks)
axs[1].xaxis.set_ticklabels(tickla)
plt.show()

在这里插入图片描述

一般绘图时会自动创建刻度,但使用set_ticks创建刻度时可能会导致tick的范围与所绘制图形的范围不一致。所以在下面的案例中,axs[1]中set_xtick的设置要与数据范围所对应,然后再通过set_xticklabels设置刻度所对应的标签

import numpy as np
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2, 1, figsize=(6, 4), tight_layout=True)
x1 = np.linspace(0.0, 6.0, 100)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
axs[0].plot(x1, y1)
axs[0].set_xticks([0,1,2,3,4,5,6])

axs[1].plot(x1, y1)
axs[1].set_xticks([0,1,2,3,4,5,6])#要将x轴的刻度放在数据范围中的哪些位置
axs[1].set_xticklabels(['zero','one', 'two', 'three', 'four', 'five','six'],#设置刻度对应的标签
                   rotation=30, fontsize='small')#rotation选项设定x刻度标签倾斜30度。
axs[1].xaxis.set_ticks_position('bottom')#set_ticks_position()方法是用来设置刻度所在的位置,常用的参数有bottom、top、both、none
print(axs[1].xaxis.get_ticklines())
#  <a list of 14 Line2D ticklines objects>
plt.show()

在这里插入图片描述

2.Tick Locators and Formatters

除了上述的简单模式,还可以使用Tick Locators and Formatters完成对于刻度位置和刻度标签的设置。
Axis.set_major_locatorAxis.set_minor_locator方法用来设置标签的位置;Axis.set_major_formatterAxis.set_minor_formatter方法用来设置标签的格式。这种方式的好处是不用显式地列举出刻度值列表。

a) Tick Formatters_设置刻度格式

set_major_formatter和set_minor_formatter这两个formatter格式命令可以接收字符串格式(matplotlib.ticker.StrMethodFormatter)或函数参数(matplotlib.ticker.FuncFormatter)来设置刻度值的格式 。

formatter格式命令接收字符串格式
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
x1 = np.linspace(0.0, 6.0, 100)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
fig, axs = plt.subplots(2, 2, figsize=(8, 5), tight_layout=True)
for n, ax in enumerate(axs.flat):   # [enumerate()函数介绍](https://www.runoob.com/python/python-func-enumerate.html)
    ax.plot(x1*10., y1)

formatter = matplotlib.ticker.FormatStrFormatter('%1.1f')
axs[0, 1].xaxis.set_major_formatter(formatter)

formatter = matplotlib.ticker.FormatStrFormatter('-%1.1f')
axs[1, 0].xaxis.set_major_formatter(formatter)

formatter = matplotlib.ticker.FormatStrFormatter('%1.5f')
axs[1, 1].xaxis.set_major_formatter(formatter)
plt.show()

在这里插入图片描述

formatter格式命令接收函数
import numpy as np
import matplotlib.pyplot as plt
x1 = np.linspace(0.0, 6.0, 100)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
def formatoddticks(x, pos):
    if x % 2:
        return f'{x:1.2f}'
    else:
        return ''

fig, ax = plt.subplots(figsize=(5, 3), tight_layout=True)
ax.plot(x1, y1)
ax.xaxis.set_major_formatter(formatoddticks)
plt.show()

在这里插入图片描述

b) Tick Locators_设置刻度位置

要绘制更复杂的图时,可以先设置locator的类型,然后通过axs.xaxis.set_major_locator(locator)绘制。

设置locator的类型:

locator=plt.MaxNLocator(nbins=7)  # 最大间隔数为7
locator=plt.FixedLocator(locs=[0,0.5,1.5,2.5,3.5,4.5,5.5,6])#直接指定刻度所在的位置  
locator=plt.AutoLocator()#自动分配刻度值的位置  
locator=plt.IndexLocator(offset=0.5, base=1)#面元间距是1,从0.5开始  
locator=plt.MultipleLocator(1.5)#将刻度的标签设置为1.5的倍数  
locator=plt.LinearLocator(numticks=5)#线性划分5等分,4个刻度  

使用样例:

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
x1 = np.linspace(0.0, 6.0, 100)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
fig, axs = plt.subplots(2, 2, figsize=(8, 5), tight_layout=True)
for n, ax in enumerate(axs.flat):
    ax.plot(x1*10., y1)

locator = matplotlib.ticker.AutoLocator()
axs[0, 0].xaxis.set_major_locator(locator)

locator = matplotlib.ticker.MaxNLocator(nbins=9)
axs[0, 1].xaxis.set_major_locator(locator)

locator = matplotlib.ticker.MultipleLocator(5)
axs[1, 0].xaxis.set_major_locator(locator)

locator = matplotlib.ticker.FixedLocator([0,7,14,21,28])
axs[1, 1].xaxis.set_major_locator(locator)

plt.show()

在这里插入图片描述

c)日期型刻度格式和位置设置

此外matplotlib.dates 模块还提供了特殊的设置日期型刻度格式和位置的方式

# 特殊的日期型locator和formatter
import numpy as np
import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
x1 = np.linspace(0.0, 6.0, 100)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
locator = mdates.DayLocator(bymonthday=[1,15,25])
formatter = mdates.DateFormatter('%b %d')

fig, ax = plt.subplots(figsize=(5, 3), tight_layout=True)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
base = datetime.datetime(2017, 1, 1, 0, 0, 1)
time = [base + datetime.timedelta(days=x) for x in range(len(x1))]
ax.plot(time, y1)
ax.tick_params(axis='x', rotation=70) # [ax.tick_params()参数详解](https://blog.csdn.net/qq_35240640/article/details/89478662)
plt.show()

在这里插入图片描述

三、legend(图例)

关于图例的术语

1.legend entry(图例条目)

每个图例由一个或多个legend entries组成。一个entry包含一个key和其对应的label。

2.legend key(图例键)

每个 legend label左面的colored/patterned marker(彩色/图案标记)。

3.legend label(图例标签)

描述由key来表示的handle的文本。

4.legend handle(图例句柄)

用于在图例中生成适当图例条目的原始对象。

以下图为例,右侧的方框中的共有两个legend entry;两个legend key:一个蓝色和一个黄色;两个legend label:一个名为‘Line up’,一个名为‘Line Down’。

图例的绘制legend()

图例的绘制同样有OO模式和pyplot模式两种方式,写法是一样的,使用legend()调用。

legend()函数两个重要参数

在使用legend方法时:

  • 手动传入两个变量:句柄和标签,用以指定条目中的特定绘图对象和显示的标签值。
  • 不传入任何参数,此时matplotlib会自动寻找合适的图例条目。
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
line_up, = ax.plot([1, 2, 3], label='Line 2')
line_down, = ax.plot([3, 2, 1], label='Line 1')
ax.legend(handles = [line_up, line_down], labels = ['Line Up', 'Line Down'])
plt.show()

在这里插入图片描述

legend()函数其他常用参数
1.loc 设置图例位置

loc参数接收一个字符串或数字表示图例出现的位置。

Location StringLocation Code
‘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

表格使用举例:ax.legend(loc=‘upper center’) 等同于 ax.legend(loc=9)

import matplotlib.pyplot as plt
fig,axes = plt.subplots(1,4,figsize=(10,4))
for i in range(4):
    axes[i].plot([0.5],[0.5])
    axes[i].legend(labels='a',loc=i)  # 观察loc参数传入不同值时图例的位置
fig.tight_layout()
plt.show()

在这里插入图片描述

2.设置图例边框及背景
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,3))
axes = fig.subplots(1,3)
for i, ax in enumerate(axes):
    ax.plot([1,2,3],label=f'ax {i}')
axes[0].legend(frameon=False) #去掉图例边框
axes[1].legend(edgecolor='blue') #设置图例边框颜色
axes[2].legend(facecolor='gray') #设置图例背景颜色,若无边框,参数无效
plt.show()

在这里插入图片描述

3.设置图例标题
import matplotlib.pyplot as plt
fig,ax =plt.subplots()
ax.plot([1,2,3],label='label')
ax.legend(title='legend title')
plt.show()

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值