matplotlib Annotation 标注

网友投稿 256 2022-09-25

matplotlib Annotation 标注

画出基本图

当图线中某些特殊地方需要标注时,我们可以使用 ​​annotation​​​. matplotlib 中的 ​​annotation​​​ 有两种方法, 一种是用 plt 里面的 ​​annotate​​​,一种是直接用 plt 里面的 ​​text​​ 来写标注.

首先,我们在坐标轴中绘制一条直线.

import matplotlib.pyplot as pltimport numpy as npx = np.linspace(-3, 3, 50)y = 2*x + 1plt.figure(num=1, figsize=(8, 5),)plt.plot(x, y,)

移动坐标

然后我们挪动坐标轴的位置.

ax = plt.gca()ax.spines['right'].set_color('none')ax.spines['top'].set_color('none')ax.spines['top'].set_color('none')ax.xaxis.set_ticks_position('bottom')ax.spines['bottom'].set_position(('data', 0))ax.yaxis.set_ticks_position('left')ax.spines['left'].set_position(('data', 0))

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

x0 = 1y0 = 2*x0 + 1plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)# set dot stylesplt.scatter([x0, ], [y0, ], s=50, color='b')

添加注释 annotate

接下来我们就对​​(x0, y0)​​这个点进行标注.

plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2"))

其中参数​​xycoords='data'​​​ 是说基于数据的值来选位置, ​​xytext=(+30, -30)​​​ 和 ​​textcoords='offset points'​​​ 对于标注位置的描述 和 xy 偏差值, ​​arrowprops​​是对图中箭头类型的一些设置.

添加注释 text

plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$', fontdict={'size': 16, 'color': 'r'})

其中​​-3.7, 3,​​​是选取text的位置, 空格需要用到转字符​​\​​​,​​fontdict​​设置文本字体.

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:为科创板公司“蹭热点”立规 花式炒作岂能听之任之!
下一篇:Pandas DataFrame设置值
相关文章

 发表评论

暂时没有评论,来抢沙发吧~