绘制不同条件的两条折线想用图例说明,但是不成功,图例不会正常显示。报错代码如下:
import matplotlib.pyplot as plt
import numpy as np
import pylab as pl
x=[1,2,3,4,5,6,7]
labels=['S1(25%)','S1(50%)','S1(75%)','S2','S3(25%)','S3(50%)','S3(75%)']
y1=[0.328,0.320,0.313,0.738,0.259,0.258,0.254]
y2=[0.230,0.234,0.232,0.738,0.233,0.233,0.253]
plot1=pl.plot(x,y1,'r')
plot2=pl.plot(x,y2,'b')
pl.xticks(x,labels)
pl.title('the loss percentage of T=7&T=14')
pl.ylabel('average losses(%)')
pl.ylim(0.0,1.0)
pl.legend([plot1,plot2],('T=14','T=7'),'best',numpoints=1)
pl.show()
查找之后发现是这样解释的:
plot1=pl.plot(x,y1,'r')
plot2=pl.plot(x,y2,'b')
需要改成
plot1,=pl.plot(x,y1,'r')
plot2,=pl.plot(x,y2,'b')
再运行就不会报错图例也正常显示了~~但是不明白这个逗号是干吗的
解释如下:
The comma is Python syntax that denotes either a single-element tuple. E.g.,
>>> tuple([1])
(1,)
In this case, it is used for argument unpacking: plot
returns a single-element list, which is unpacked into line
:
>>> x, y = [1, 2]
>>> x
1
>>> y
2
>>> z, = [3]
>>> z
3
An alternative, perhaps more readable way of doing this is to use list-like syntax:
>>> [z] = [4]
>>> z
4
though the z, =
is more common in Python code.