值误差x和y必须大小相同,但它们是?

时间:2016-05-20 10:25:40

标签: python numpy matplotlib

我试图绘制长度为10的numpy数组:

mass_frac_plot = plt.figure()
mass_frac = mass_frac_plot.add_subplot(1, 1, 1)
mass_frac.scatter(mass_frac, homogen_frac)

我明白了:

Traceback (most recent call last):
  File "./plot.py", line 58, in <module>
    mass_frac.scatter(mass_frac, homogen_frac)
  File "/usr/local/lib/python3.5/site-packages/matplotlib/__init__.py", line 1811, in inner
    return func(ax, *args, **kwargs)
  File "/usr/local/lib/python3.5/site-packages/matplotlib/axes/_axes.py", line 3836, in scatter
    raise ValueError("x and y must be the same size")

帮助!它们实际上都是数组,长度为10 ......

print(type(mass_frac), len(mass_frac))
print(mass_frac)
print(type(homogen_frac), len(homogen_frac))
print(homogen_frac)

给出这个:

<class 'numpy.ndarray'> 10
[ 3.67  3.6   4.45  3.74  4.93  4.35  3.89  5.62  4.73  3.83]
<class 'numpy.ndarray'> 10
[  98.02982123   96.82921968   88.8207858    83.37174016   75.55236146
87.71156752   91.95410515   66.34245085   77.63112123  119.74640558]

1 个答案:

答案 0 :(得分:1)

  

帮助!它们实际上都是数组,长度为10 ......

不,他们不是:

mass_frac_plot = plt.figure()
mass_frac = mass_frac_plot.add_subplot(1, 1, 1)
^^^^^^^^^
mass_frac.scatter(mass_frac, homogen_frac)
                  ^^^^^^^^^

执行第二行后,mass_frac显然不再是一个数组。相反,它将是

类型
>>> type(mass_frac)
<class 'matplotlib.axes._subplots.AxesSubplot'>

更改变量名称,这样您就不会破坏阵列。