简体   繁体   中英

Plotting: ValueError: x and y must have same first dimension

ValueError: x and y must have same first dimension, but have shapes (12,) and (6,)

I'm still pretty new to Python and trying to create a simple graph.

Here is my code:

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()

Here is the full trace:

---------------------------------------------------------------------------
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,)
  • The length of the x and y arguments sent to plot , must be the same.
  • You are plotting 6 temperature points versus 12 month points. You have to add 6 more temperature values, or only have 6 months (eg range(1, 13, 2) ).

For this error, you have to add np.unique() . Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM