[ Matplotlib version: 3.2.1 ]
十一、文字与注释
一些场景中,可视化需要辅之以少量文字提示(textual cue)和标签。
(一)在图中添加文字标签
最基本的注释(annotation)类型有坐标轴标题与图标题,此外,可以通过plt.text
/ax.text
命令手动添加注释,它们可以在具体的x/y坐标点上放上文字
ax.text
方法需要一个x轴坐标、一个y轴坐标、一个字符串和一些可选参数,比如文字的颜色、字号、风格、对齐方式以及其他文字属性
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib as mpl
plt.style.use('seaborn-whitegrid')
import numpy as np
import pandas as pd
- 日均出生人数统计图
# 在图上增加文字标签
# ha是水平对齐方式缩写(horizonal alignment)
style = dict(size=10, color='gray')
ax.text('2012-1-1', 3950, "New Year's Day", **style)
ax.text('2012-7-4', 4250, "Independence Day", ha='center', **style)
ax.text('2012-9-4', 4850, "Labor Day", ha='center', **style)
ax.text('2012-10-31', 4600, "Halloween", ha='right', **style)
ax.text('2012-11-25', 4450, "Thanksgiving", ha='center', **style)
ax.text('2012-12-25', 3850, "Christmas", ha='right', **style)
# 设置坐标轴标题
ax.set(title='USA births by day of year (1969-1988)',
ylabel='average daily births')
# 设置x轴刻度值,让月份居中显示
ax.xaxis.set_major_locator(mpl.dates.MonthLocator())
ax.xaxis.set_minor_locator(mpl.dates.MonthLocator(bymonthday=15))
ax.xaxis.