Matlotlib练习5:图像标注

图像标注

画点

plt.scatter(x0, y0, s=50, color='b')

效果图

画虚线

#画虚线 连接点(x0,0)与点(x0 y0),k为black,lw直线宽度
plt.plot([x0, x0], [y0, 0], 'k--', lw=2)

效果图

添加描述和弯箭头

#y0传入%s
#xytext=(+30, -30)以蓝色点xy=(x0,y0)为起点在x方向+30,在y方向-30
#textcoords='offset points'蓝色点作为起点
#arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad=.2')弧度为.2的箭头
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xytext=(+30, -30),
             textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad=.2'))

效果图

添加描述和直箭头

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

效果图

‘$添加任意标注文本$’

plt.annotate(r'$(0.50, 2.0)$', xy=(x0, y0), xytext=(+30, -30),
             textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle='->'))

添加文本描述

#文本描述
#-1,2为文本起始点
plt.text(-1, 2, r'$this\ is\ a\ line\ y=2x+1 $', fontdict={
    
    'size': '16', 'color': 'r'})

效果图

完整程序

import matplotlib.pyplot as plt
import numpy as np

#numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
#在指定的间隔内返回均匀间隔的数字。
x = np.linspace(-1, 1, 100)
y1 = 2*x + 1

plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))

x0 = 0.5
y0 = 2*x0 + 1
#画点
plt.scatter(x0, y0, s=50, color='b')
#画虚线 连接点(x0,0)与点(x0 y0),k为black,lw直线宽度
plt.plot([x0, x0], [y0, 0], 'k--', lw=2)
#添加箭头和描述
#y0传入%s
#xytext=(+30, -30)以蓝色点xy=(x0,y0)为起点在x方向+30,在y方向-30
#textcoords='offset points'蓝色点作为起点
#arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad=.2')弧度为.2的箭头
#arrowprops=dict(arrowstyle='->')加直箭头
plt.annotate('$(0.50, 2.0)$', xy=(x0, y0), xytext=(+30, -30),
             textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle='->'))
#文本描述
#-1,2为文本起始点
plt.text(-1, 2, r'$this\ is\ a\ line\ y=2x+1 $', fontdict={
    
    'size': '16', 'color': 'r'})

plt.show()

猜你喜欢

转载自blog.csdn.net/weixin_48524215/article/details/111798645