绘图:ValueError:x 和 y 必须具有相同的第一维度

ron*_*962 6 python matplotlib

ValueError:x 和 y 必须具有相同的第一维度,但具有形状 (12,) 和 (6,)

我对 Python 还很陌生,正在尝试创建一个简单的图表。

这是我的代码:

import matplotlib.pyplot as plt

months = range(1, 13)

nyc_temp_2000 = [20.0, 30.5, 80.1, 80.3, 56.5, 99.6]

nyc_temp_2006 = [44.9, 6.4, 92.4, 69.8, 25.5, 12.5]

nyc_temp_2012 = [60.5, 60.9, 66.2, 25.0, 10.0, 78.0]

plt.plot(months, nyc_temp_2000)

plt.plot(months, nyc_temp_2006)

plt.plot(months, nyc_temp_2012)
show()
Run Code Online (Sandbox Code Playgroud)

这是完整的跟踪:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_34116/1667745297.py in <module>
     10 nyc_temp_2012 = [60.5, 60.9, 66.2, 25.0, 10.0, 78.0]
     11 
---> 12 plt.plot(months, nyc_temp_2000)
     13 
     14 plt.plot(months, nyc_temp_2006)

D:\anaconda3\envs\py39\lib\site-packages\matplotlib\pyplot.py in plot(scalex, scaley, data, *args, **kwargs)
   3017 @_copy_docstring_and_deprecators(Axes.plot)
   3018 def plot(*args, scalex=True, scaley=True, data=None, **kwargs):
-> 3019     return gca().plot(
   3020         *args, scalex=scalex, scaley=scaley,
   3021         **({"data": data} if data is not None else {}), **kwargs)

D:\anaconda3\envs\py39\lib\site-packages\matplotlib\axes\_axes.py in plot(self, scalex, scaley, data, *args, **kwargs)
   1603         """
   1604         kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
-> 1605         lines = [*self._get_lines(*args, data=data, **kwargs)]
   1606         for line in lines:
   1607             self.add_line(line)

D:\anaconda3\envs\py39\lib\site-packages\matplotlib\axes\_base.py in __call__(self, data, *args, **kwargs)
    313                 this += args[0],
    314                 args = args[1:]
--> 315             yield from self._plot_args(this, kwargs)
    316 
    317     def get_next_color(self):

D:\anaconda3\envs\py39\lib\site-packages\matplotlib\axes\_base.py in _plot_args(self, tup, kwargs, return_kwargs)
    499 
    500         if x.shape[0] != y.shape[0]:
--> 501             raise ValueError(f"x and y must have same first dimension, but "
    502                              f"have shapes {x.shape} and {y.shape}")
    503         if x.ndim > 2 or y.ndim > 2:

ValueError: x and y must have same first dimension, but have shapes (12,) and (6,)
Run Code Online (Sandbox Code Playgroud)

Roh*_*nil 10

  • xy发送到 , 的参数的长度plot必须相同。
  • 您正在绘制 6 个温度点与 12 个月的点。您必须再添加 6 个温度值,否则只有 6 个月(例如range(1, 13, 2))。