主目录
matplotlib.pyplot.text
text(x, y, s, fontdict=None, withdash=False, **kwargs)
-
x、y:坐标数据
s:文本
1、创建数据
import numpy as np
n = 12
x = np.arange(n)
y1 = np.random.uniform(0.5, 1.0, n) * (1 - x / n)
y2 = np.random.uniform(0.5, 1.0, n) * (1 - x / n)
2、绘图
import matplotlib.pyplot as mp
mp.ylim(-1.1, 1.1)
mp.grid(axis='y', linestyle=':')
mp.bar(x, y1, ec='white', fc='dodgerblue', label='Sample 1')
mp.bar(x, -y2, ec='white', fc='dodgerblue', label='Sample 2', alpha=0.5)
3、数据标注
# 数据标注
for _x, _y in zip(x, y1):
mp.text(_x, _y + 0.1, '%.2f' % _y, ha='center', va='bottom', size=8)
for _x, _y in zip(x, y2):
mp.text(_x, -_y - 0.1, '%.2f' % _y, ha='center', va='top', size=8)
4、展示
# 展示
mp.legend()
mp.show()

附:一波流复制代码
import numpy as np
n = 12
x = np.arange(n)
y1 = np.random.uniform(0.5, 1.0, n) * (1 - x / n)
y2 = np.random.uniform(0.5, 1.0, n) * (1 - x / n)
import matplotlib.pyplot as mp
mp.ylim(-1.1, 1.1)
mp.grid(axis='y', linestyle=':')
mp.bar(x, y1, ec='white', fc='dodgerblue', label='Sample 1')
mp.bar(x, -y2, ec='white', fc='dodgerblue', label='Sample 2', alpha=0.5)
for _x, _y in zip(x, y1):
mp.text(_x, _y + 0.1, '%.2f' % _y, ha='center', va='bottom', size=8)
for _x, _y in zip(x, y2):
mp.text(_x, -_y - 0.1, '%.2f' % _y, ha='center', va='top', size=8)
mp.legend()
mp.show()