matplotlib学习笔记【2】:添加图示图例,添加标注
一. 添加图示图例
1. 代码:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2
plt.figure()
# set x limits
plt.xlim((-1, 2))
plt.ylim((-2, 3))
# set new sticks
new_sticks = np.linspace(-1, 2, 5)
plt.xticks(new_sticks)
# set tick labels
plt.yticks([-2, -1.8, -1, 1.22, 3],
[r$really bad$, r$bad$, r$normal$, r$good$, r$really good$])
l1, = plt.plot(x, y1, label=linear line)
l2, = plt.plot(x, y2, color=red, linewidth=1.0, linestyle=--, label=square line)
plt.legend(loc=lower right) # 图例显示在右下角
# plt.legend(handles=[l1, l2], labels=[up, down], loc=best) 这是对于参数的介绍,主要有三个参数,handles是线段,labels是给线取的名字,loc是图例所在位置
# the "," is very important in here l1, = plt... and l2, = plt... for this step
"""legend( handles=(line1, line2, line3),
labels=(label1, label2, label3),
upper right)
The *loc* location codes are::
best : 0, (currently not supported for figure legends)
upper right : 1,
upper left : 2,
lower left : 3,
lower right : 4,
right : 5,
center left : 6,
center right : 7,
lower center : 8,
upper center : 9,
center : 10,"""
plt.show()
运行结果:
二. 添加标注
1. 代码:
import matplotlib.pyplot as plt
import numpy as np
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.spines[right].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 = 1
y0 = 2*x0 + 1
plt.plot([x0, x0,], [0, y0,], k--, linewidth=2.5) # [x0,x0],[0,y0]相当于传了两个点的x坐标以及y坐标,k--定义了颜色为black,线条的形式是虚线
plt.scatter([x0, ], [y0, ], s=50, color=b)
# method 1:
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"))
# method 2:
plt.text(-3.7, 3, this is my tag,
fontdict={size: 16, color: r})
plt.show()
