为图像添加图例
a1, = plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
a2, = plt.plot(x, y2, color='blue', linewidth=2.0, linestyle='-')
plt.legend(handles=[a1, a2], labels=['test1', 'test2'], loc='best')
效果图
plt.legend(handles=[a1, a2], labels=['test1', 'test2'], loc='lower right')
完整程序
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1, 1, 100)
y1 = 2*x + 1
y2 = x**2
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
a1, = plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
a2, = plt.plot(x, y2, color='blue', linewidth=2.0, linestyle='-')
plt.legend(handles=[a1, a2], 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()