Python错误集锦:matplotlib绘图时提示ValueError: x and y must have same first dimension, but have shapes (100,) and (110,)

原文链接:http://www.juzicode.com/python-error-matplotlib-valueerror-x-and-y-must-have-same-first-dimension-but-have-shapes-100-and-110

错误提示:

matplotlib绘图时提示ValueError: x and y must have same first dimension, but have shapes (100,) and (110,)

#VX公众号:桔子code / juzicode.com
import numpy as np
import matplotlib.pyplot as plt 

x = np.arange(100)
y = np.arange(110)
plt.plot(x,y)
plt.show()
==========运行结果:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-1-1d9c907816ec> in <module>
      5 x = np.arange(100)
      6 y = np.arange(110)
----> 7 plt.plot(x,y)
      8 plt.show()

d:\python\python38\lib\site-packages\matplotlib\pyplot.py in plot(scalex, scaley, data, *args, **kwargs)
   2838 @_copy_docstring_and_deprecators(Axes.plot)
   2839 def plot(*args, scalex=True, scaley=True, data=None, **kwargs):
-> 2840     return gca().plot(
   2841         *args, scalex=scalex, scaley=scaley,
   2842         **({"data": data} if data is not None else {}), **kwargs)

d:\python\python38\lib\site-packages\matplotlib\axes\_axes.py in plot(self, scalex, scaley, data, *args, **kwargs)
   1741         """
   1742         kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
-> 1743         lines = [*self._get_lines(*args, data=data, **kwargs)]
   1744         for line in lines:
   1745             self.add_line(line)

d:\python\python38\lib\site-packages\matplotlib\axes\_base.py in __call__(self, data, *args, **kwargs)
    271                 this += args[0],
    272                 args = args[1:]
--> 273             yield from self._plot_args(this, kwargs)
    274 
    275     def get_next_color(self):

d:\python\python38\lib\site-packages\matplotlib\axes\_base.py in _plot_args(self, tup, kwargs)
    397 
    398         if x.shape[0] != y.shape[0]:
--> 399             raise ValueError(f"x and y must have same first dimension, but "
    400                              f"have shapes {x.shape} and {y.shape}")
    401         if x.ndim > 2 or y.ndim > 2:

ValueError: x and y must have same first dimension, but have shapes (100,) and (110,)

错误原因:

1、绘图的x轴的元素个数为100,y轴元素个数为110,二者不相等所以报错“不是相同的维度”。

解决方法:

1、裁剪或修改y轴元素和x轴元素相等

#VX公众号:桔子code / juzicode.com
import numpy as np
import matplotlib.pyplot as plt 

x = np.arange(100)
y = np.arange(100) #修改为相同尺寸
print('x.shape,y.shape:',x.shape,y.shape)#检查x和y的大小
plt.plot(x,y)
plt.show()
==========运行结果:
x.shape,y.shape: (100,) (100,)

扩展内容:

  1. OpenCV-Python教程


如果本文还没有完全解决你的疑惑,你也可以在微信公众号“桔子code”后台给我留言,欢迎一起探讨交流。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注