ValueError: x和y必须大小相同在Matplotlib中
如果我想用matplotlib画一个散点图,像这样:
import matplotlib as plt
x = [float(1) for x in xrange(2)]
y = [float(2) for x in xrange(2)]
plt.scatter(x,y)
plt.show()
我总是会遇到上面的错误。
但是如果我这样做:
import matplotlib as plt
x = [1.0, 1.0]
y = [2.0, 2.0]
plt.scatter(x,y)
plt.show()
就能成功。为什么会这样呢?
1 个回答
4
你在给 y
赋值的时候,把 x
的值给覆盖了
x = [float(1) for x in xrange(2)] # x = [1, 1]
y = [float(2) for x in xrange(2)] # x = 1; y = [2, 2]
^
与其用 x
,不如用 _
(这是在Python中表示“我不在乎这个值”的变量,正如 @kroolik 所建议的)
x = [float(1) for _ in xrange(2)]
y = [float(2) for _ in xrange(2)]