一文识尽matplotlib.pyplot模块(二)

  1. 图例的简单生成
  • 方法1:使用变量存储函数,注意逗号的应用
import matplotlib.pyplot as plt
import  numpy as np
x  = np.linspace(-2,2,100)
y1 = 2*x + 1
y2 = x**2
ax = plt.gca()
ax.spines['right'].set_color(None)
ax.spines['top'].set_color(None)
ax.spines['left'].set_position(('data',0))
ax.spines['bottom'].set_position(('data',0))
p1, = plt.plot(x,y1)
p2, = plt.plot(x,y2)
plt.legend(handles = [p1,p2],labels = ['2x+1','x^2'],loc = 'best') 
plt.show()

其中legend的loc参数可以有这么几个选择:
‘best’,‘upper right’,‘upper left’,‘lower right’,‘lower left’,‘right’,‘center left’,‘center right’,‘lower center’,‘upper center’

  • 方法2: 使用plot时自带label属性,然后再用legend改变位置
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-2,2,100)
y1 = 2*x + 1
y2 = x**2
ax = plt.gca()
ax.spines['right'].set_color(None)
ax.spines['top'].set_color(None)
ax.spines['left'].set_position(('data',0))
ax.spines['bottom'].set_position(('data',0))
plt.plot(x,y1,label = '2x+1')
plt.plot(x,y2,label = 'x^2')
plt.legend(loc = 'best')
plt.show()

  1. 简单的注释
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3,3,100)
y1 = 2*x + 1

ax = plt.gca()
ax.spines['right'].set_color(None)
ax.spines['top'].set_color(None)
ax.spines['left'].set_position(('data',0))
ax.spines['bottom'].set_position(('data',0))
plt.plot(x,y1,color = 'red')

x0 = 0.5
y0 = 2*x0 +1
plt.scatter(x0,y0, s = 50,color = 'k')
plt.plot([x0,x0],[y0,0],'k--')
plt.annotate('zhushi',xy = (x0,y0),xytext = (1.5,0.5),color = 'k',arrowprops = dict(width = 2, color = 'purple',shrink = 0.05))


'''
    xy=(横坐标,纵坐标)  箭头尖端
    xytext=(横坐标,纵坐标) 文字的坐标,指的是最左边的坐标
    arrowprops= dict(
        color= '颜色',
        shrink = '数字' <1  收缩箭头
        width = 2,
    )
'''


plt.show()

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

live_for_myself

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

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

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

打赏作者

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

抵扣说明:

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

余额充值