錯誤的代碼
from matplotlib import pyplot as plt
from matplotlib import font_manager
import random
yy = range(0,35,5)
y1 = [random.randint(0,35) for i in yy]
y2 = [random.randint(1,35) for i in yy]
x = range(0,35,5)
plt.plot(x,y1,color = 'r'')
plt.plot(x,y2,color = 'g')
mt_font = font_manager.FontProperties(fname = 'C:/Windows/Fonts/SIMYOU.TTF')
x_ticks = ('{}歲'.format(i) for i in x)
plt.xticks(x,x_ticks,rotation = 45,fontproperties=mt_font)
#繪製網格
plt.grid(alpha=0.4)
#添加圖例,這裏要顯示的話要在plt.plot(x,y1,color = 'r',label = '自己')添加label
plt.legend(prop=mt_font,loc='upper right')
plt.show()
運行報錯
No handles with labels found to put in legend.
原因是要在
plt.plot(x,y1,color = 'r',label='自己')
plt.plot(x,y2,color = 'g',label = '同事')
這兩行代碼中添加label要不然他不知道你添加的圖例是什麼