matplotlib(三)——Working with text

版权声明:本文为博主原创文章,转载请说明出处 https://blog.csdn.net/qq_31192383/article/details/54380736

基础的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.text.Text实例有许多属性,可以通过关键字参数来设置它们,下面是文本的所有属性和其取值:
这里写图片描述
你可以使用horizontalalignment, verticalalignment, 或者multialignment属性来设置文本的对其方式。horizontalalignment控制X方向上文本位于左右还是居中显示,verticalalignment则是控制文本的上下还是居中显示。
看下面这个例子:

import matplotlib.pyplot as plt
import matplotlib.patches as patches

# build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height

fig = plt.figure()
ax = fig.add_subplot(111)

# axes coordinates are 0,0 is bottom left and 1,1 is upper right
p = patches.Rectangle(
    (left, bottom), width, height,
    fill=False, transform=ax.transAxes, clip_on=False
    )

ax.add_patch(p)

ax.text(left, bottom, 'left top',
        horizontalalignment='left',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, bottom, 'left bottom',
        horizontalalignment='left',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right bottom',
        horizontalalignment='right',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right top',
        horizontalalignment='right',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(right, bottom, 'center top',
        horizontalalignment='center',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, 0.5*(bottom+top), 'right center',
        horizontalalignment='right',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, 0.5*(bottom+top), 'left center',
        horizontalalignment='left',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(0.5*(left+right), 0.5*(bottom+top), 'middle',
        horizontalalignment='center',
        verticalalignment='center',
        fontsize=20, color='red',
        transform=ax.transAxes)

ax.text(right, 0.5*(bottom+top), 'centered',
        horizontalalignment='center',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, top, 'rotated\nwith newlines',
        horizontalalignment='center',
        verticalalignment='center',
        rotation=45,
        transform=ax.transAxes)

#ax.set_axis_off()
plt.show()

这里写图片描述
其中transform=ax.transAxes这句话是为了说明坐标轴是以axes坐标系为标准的,(0,0)就是axes的左下角,(1,1)是右上角。

##数学表达式##
由于数学表达式众多,而且不易记住,这里需要不再一一列举,需要用时再去官方文档查看:数学表达式
注意数学表达式可以和一般文字一同书写,只是数学表达式需要使用【r’$ xxx plt.title(r \alpha > \beta$’)显示的就是这里写图片描述

注释文本##

注释文本annotate()基本用法在matplotlib(一)已经提过。
默认情况下xycoords和textcoords的值取’data’,即xy=(2,1)和xytext=(3,1.5)指的的数据刻度的坐标。这里当然可以改变坐标系,其取值有以下几种:
这里写图片描述
比如我们要将文本坐标系放在fractional axes坐标系中,我们可以这样设置:

ax.annotate('local max', xy=(3, 1),  xycoords='data',
            xytext=(0.8, 0.95), textcoords='axes fraction',
            arrowprops=dict(facecolor='black', shrink=0.05),
            horizontalalignment='right', verticalalignment='top',
            )

一般的坐标系都是左下角为坐标原点。如果取值是负的,可以让右上角为原点,类似于负索引序列。

你可以指定箭头的属性,通过arrowprops()设定箭头属性字典,其取值有:
这里写图片描述
下面的例子中,点xy处于本地坐标系(极坐标系)。对于一个极坐标,其坐标为(角度theta,半径radius)。这个例子中的文本处于figure fraction坐标系中,annotate()和text()拥有一样的属性,例如horizontalalignment等:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111, polar=True)
r = np.arange(0,1,0.001)
theta = 2*2*np.pi*r
line, = ax.plot(theta, r, color='#ee8d18', lw=3)

ind = 800
thisr, thistheta = r[ind], theta[ind]
ax.plot([thistheta], [thisr], 'o')
ax.annotate('a polar annotation',
            xy=(thistheta, thisr),  # theta, radius
            xytext=(0.05, 0.05),    # fraction, fraction
            textcoords='figure fraction',
            arrowprops=dict(facecolor='black', shrink=0.05),
            horizontalalignment='left',
            verticalalignment='bottom',
            )
plt.show()

这里写图片描述


参考文档:http://matplotlib.org/users/index_text.html


注:转载请注明原文出处:
作者:CUG_UESTC
出处:http://blog.csdn.net/qq_31192383/article/details/54380736

猜你喜欢

转载自blog.csdn.net/qq_31192383/article/details/54380736