基础的text命令
下面这些命令是在pyplot用户界面中创建文本:
- text()——在axes中任意位置添加文本
- xlabel()——在X轴上添加轴标签
- ylabel()——在Y轴上添加轴标签
- title()——给axes添加标题
- figtext()——给一个figure中任意位置添加文本
- suptitle()——给一个figure添加标题
- annotate()——在axes中添加批注,可带有箭
上述的这些函数都会创建并返回一个matplotlib.text.Text()实例,它可以用来设置各种字体或者属性。下面看看上述这些函数的实际效果:
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
fig = plt.figure()
fig.suptitle('use suptitle()', fontsize=14, fontweight='bold')
ax = fig.add_subplot(111)
fig.subplots_adjust(top=0.85)
ax.set_title('use set_title()')
ax.set_xlabel('use set_xlabel')
ax.set_ylabel('use set_ylabel')
ax.text(3, 8, 'use text() in data coords', style='italic',
bbox={
'facecolor':'red', 'alpha':0.5, 'pad':10})
ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15)
ax.text(3, 2, u'unicode: Institut f\374r Festk\366rperphysik')
ax.text(0.95, 0.01, 'colored text in axes coords',
verticalalignment='bottom', horizontalalignment='right',
transform=ax.transAxes,
color='green', fontsize=15)
ax.plot([2], [1], 'o')
ax.annotate('use annotate()', xy=(2, 1), xytext=(3, 4),
arrowprops=dict(facecolor='black', shrink=0.05))
ax.axis([0, 10, 0, 10])
plt.show()
注意:plt.xlabel()设置的是当前坐标系的X坐标,而代码里的ax.set_xlabel()则是利用坐标系对象直接设置X坐标。其效果如下:
文本属性和布局
matplotlib