3.Matplotlib设置legend图例,设置标注

0 引言

Matplotlib绘图完成后,有时候为了更加完美,会在角落设置图例,或者坐标系中有时候需要标注来说明该曲线。

1 legend图例

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,100)
y1 = 2*x +1
y2 = x**2

# xy范围
plt.xlim(-1,2)
plt.ylim(-2,3)

# xy描述
plt.xlabel('I am X')
plt.ylabel('I am Y')

# 设置l1和l2,并传入到 .legend图例中
l1, = plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
l2, = plt.plot(x,y2,color='blue',linewidth=5.0,linestyle='-')
plt.legend(handles=[l1,l2],labels=['test1','test2'],loc='best')

new_ticks = np.linspace(-2,2,11)
print(new_ticks)

plt.xticks(new_ticks)
plt.yticks([-1,0,1,2,3],
           ['level1','level2','level3','level4','level5'])

plt.show()
[-2.  -1.6 -1.2 -0.8 -0.4  0.   0.4  0.8  1.2  1.6  2. ]

2 标注

主要通过 plt.annotate来设置曲线的标注,调用 plt.text来设置文本标注。

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1,1,100)
y1 = 2*x +1
y2 = x**2

plt.plot(x,y1,color='red',linewidth=1.0,linestyle='-')

# gca  get current axis
ax = plt.gca()
# 把右边和上边的边框去掉
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 把x轴的刻度设置为‘bottom'
# 把y轴的刻度设置为 ’left‘
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# 设置bottom对应到0点
# 设置left对应到0点
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')
# 画虚线
plt.plot([x0,x0],[y0,0],'k--', lw=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.text(-1,2,r'$this\ is\ the\ text$',fontdict={'size':'16','color':'r'})

plt.show()
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZPILOTE

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值