## Matplotlib 图例与标注

| |
[ 所属分类 开发（python） | 发布者 店小二03 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

from matplotlib import pyplot as plt
plt.figure()
ax = plt.subplot(111) # ax = plt.add_subplot(111)

sin, = ax.plot(x, y1, color='red', label='sin')
cos, = ax.plot(x, y2, color='blue', label='cos')

ax.legend(loc='lower right')

loc即location， lower right即右下角，也可以是upper right等等

sin, = ax.plot(x, y1, color='red')
cos, = ax.plot(x, y2, color='blue')
ax.legend((sin,cos),('sin','cos'),loc='lower right')

x = [10,20,...]
y = [0.5,0.6,0.7...]
bars=ax.bar(x,y,color='green',tick_label=x,width=2)
for j,rect in enumerate(bars):
left = rect.get_x() # 得到这根柱子的横坐标（可以考虑向左位移）
# left,top: 得到柱子左上定点位置并产生个向上0.01的位移
top = rect.get_y() + rect.get_height() + 0.01
ax.text(left,top,'%.3f'%y[j]) # 标注柱子的“值”并且保留三位有效数字

x = [10,20,...]
y = [0.5,0.6,0.7,...]
bars=ax.bar(x,y,color='green',tick_label=x,width=2)
for j,rect in enumerate(bars):
left = rect.get_x()+1
top = rect.get_y()+rect.get_height()+0.01
texts.append(ax.text(left,top,'%.3f'%y[j]))
adjust_text(texts,autoalign='y', only_move={'points':'y', 'text':'y'},force_points=0.5, expand_text=(1.2, 1.3), ha='center')