matplotlib的学习6-annotation的标注

import matplotlib.pyplot as plt
import numpy as np
'''
当图线中某些特殊地方需要标注时,我们可以使用 annotation. matplotlib 中的 annotation 有两种方法
 一种是用 plt 里面的 annotate,一种是直接用 plt 里面的 text 来写标注.
'''
x = np.linspace(-3, 3, 50)
y = 2*x + 1

plt.figure(num=1, figsize=(8, 5),)
plt.plot(x, y,)

#挪动坐标轴的位置
ax = plt.gca()#获取ax的信息
ax.spines['right'].set_color('none')#虚化右边的线
ax.spines['top'].set_color('none')#虚化top的线
ax.xaxis.set_ticks_position('bottom')#设置刻度显示的位置
ax.spines['bottom'].set_position(('data', 0))#设置bottom那根线(也就是x轴),data应该是一个参数要让他靠近0
ax.yaxis.set_ticks_position('left')#调整y轴刻度显示的位置
ax.spines['left'].set_position(('data', 0))#调整左边那条线,也就是y轴线的位置


# 然后标注出点(x0, y0)的位置信息. 用plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5) 画出一条垂直于x轴的虚线.

x0 = 1
y0 = 2*x0 + 1
plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)#画虚线
# set dot styles
plt.scatter([x0, ], [y0, ], s=50, color='b')#标注点


# 添加注释 annotate
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30),#xycoords='data'基于数据的值来选择位置
             textcoords='offset points', fontsize=16,#xytext=(+30, -30) 和 textcoords='offset points' 对于标注位置的描述 和 xy 偏差值,
             arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2"))  #arrowprops是对图中箭头类型的一些设置.

#添加注释text
#-3.7,3是选取text的位置  空格需要用到转字符,fontdict选择文本的字体
plt.text(-3.7, 3, r'$This is the some text. mu sigma_i alpha_t$',
         fontdict={'size': 16, 'color': 'r'})

plt.show()

 能画虚线,能写注释,注释有两种情况第一种为annotate,第二种为text

原文地址:https://www.cnblogs.com/simon-idea/p/9580725.html