【问题标题】:ValueError: Argument U has a size 4 which does not match 1, the number of arrow positionsValueError:参数 U 的大小为 4,与 1 不匹配,即箭头位置的数量
【发布时间】:2020-12-05 17:42:50
【问题描述】:

代码:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
import math as mt
from numpy import linalg as LA
from mpl_toolkits.mplot3d import Axes3D
from sklearn.datasets import fetch_olivetti_faces
%matplotlib inline

x=np.array([1,0]) # Original vector
theta = 30 * mt.pi / 180 # 30 degress in radian
A = np.array([[np.cos(theta), -np.sin(theta)],[np.sin(theta), np.cos(theta)]]) # Rotation matrix for theta=30 degrees
B = np.array([[3,0],[0,1]]) # Stretching matrix

Ax = A @ x  # y1 is the rotated vector
Bx = B @ x  # y2 is the stretched vector

# Reshaping and storing both x and Ax in t1 to be plotted as vectors
t1 = np.concatenate([x.reshape(1,2), Ax.reshape(1,2)])
# Reshaping and storing both x and Bx in t2 to be plotted as vectors
t2 = np.concatenate([x.reshape(1,2), Bx.reshape(1,2)])

# origin point
x_pos = 0
y_pos = 0

fig, ax = plt.subplots()


# Plotting t1
ax1.quiver(x_pos, y_pos, t1[:,0], t1[:,1], color=['b', 'g'], width=0.013, angles='xy', scale_units='xy', scale=1)
ax1.set_xlabel('x', fontsize=14)
ax1.set_ylabel('y', fontsize=14)
ax1.set_xlim([-0.5,1.5])
ax1.set_ylim([-0.5,1])
ax1.set_aspect('equal')
ax1.grid(True)
ax1.set_axisbelow(True)
ax1.set_title("Rotation transform")
ax1.axhline(y=0, color='k')
ax1.axvline(x=0, color='k')
ax1.text(1, 0.1, "$\mathbf{x}$", fontsize=16)
ax1.text(0.8, 0.6, "$\mathbf{Ax}$", fontsize=16)


plt.show()

我正在尝试使用 python 和 jupyter notebook 在转换后绘制向量。我都是新手。我的代码在使用ax1.quiver 方法后给了我错误消息。

错误信息:

ValueError                                Traceback (most recent call last)
<ipython-input-20-f96b87a2142a> in <module>
     29 
     30 # Plotting t1
---> 31 ax1.quiver(x_pos, y_pos, t1, t1, color=['b', 'g'], width=0.013, angles='xy', scale_units='xy', scale=1)
     32 ax1.set_xlabel('x', fontsize=14)
     33 ax1.set_ylabel('y', fontsize=14)

~/python-project/linear-algebra/py3env/lib/python3.7/site-packages/matplotlib/__init__.py in inner(ax, data, *args, **kwargs)
   1436     def inner(ax, *args, data=None, **kwargs):
   1437         if data is None:
-> 1438             return func(ax, *map(sanitize_sequence, args), **kwargs)
   1439 
   1440         bound = new_sig.bind(ax, *args, **kwargs)

~/python-project/linear-algebra/py3env/lib/python3.7/site-packages/matplotlib/axes/_axes.py in quiver(self, *args, **kw)
   5019         args = self._quiver_units(args, kw)
   5020 
-> 5021         q = mquiver.Quiver(self, *args, **kw)
   5022 
   5023         self.add_collection(q, autolim=True)

~/python-project/linear-algebra/py3env/lib/python3.7/site-packages/matplotlib/quiver.py in __init__(self, ax, scale, headwidth, headlength, headaxislength, minshaft, minlength, units, scale_units, angles, width, color, pivot, *args, **kw)
    501                                              **kw)
    502         self.polykw = kw
--> 503         self.set_UVC(U, V, C)
    504         self._initialized = False
    505 

~/python-project/linear-algebra/py3env/lib/python3.7/site-packages/matplotlib/quiver.py in set_UVC(self, U, V, C)
    574         for name, var in zip(('U', 'V', 'C'), (U, V, C)):
    575             if not (var is None or var.size == self.N or var.size == 1):
--> 576                 raise ValueError(f'Argument {name} has a size {var.size}'
    577                                  f' which does not match {self.N},'
    578                                  ' the number of arrow positions')

ValueError: Argument U has a size 4 which does not match 1, the number of arrow positions

我在谷歌上搜索了这种类型的错误消息,但没有找到任何有用的解决方案。我不明白是什么信息告诉我要进行更正。

【问题讨论】:

    标签: python numpy matplotlib jupyter-notebook


    【解决方案1】:

    根据docux_posy_pos 必须用[] 括起来(即[x_pos, y_pos])。我正在使用 matplotlib 3.3.2,它可以工作。

    【讨论】:

      【解决方案2】:

      回滚到 matplotlib=3.1.1 将显示您的矢量图。

      对于康达:

      conda remove matplotlib
      conda install matplotlib=3.1.1
      

      注意:在笔记本中,您的绘图可能会出现以下错误(但这与您的代码无关)。

      第 4 行的错误键“text.kerning_factor” /site-packages/matplotlib/mpl-data/stylelib/_classic_test_patch.mplstyle。

      只需转到该文件并注释掉第 4 行。请参阅下面的答案:

      jupyter notebook shows error message for matplotlib Bad key "text.kerning_factor"

      【讨论】:

        【解决方案3】:

        所以我不确定您使用的是旧版还是新版 quiver,它不支持 t1[:,0] 表示法,但它所期望的是每个 t1 的单个值。所以它应该分成两行,看起来像

        ax1.quiver(x_pos, y_pos, t1[0,0], t1[0,1], color=['b','g'], width=0.013, angles='xy', scale_units='xy', scale=1)
        ax1.quiver(x_pos, y_pos, t1[1,0], t1[1,1], color=['b','g'], width=0.013, angles='xy', scale_units='xy', scale=1)
        

        这可以通过更改 quiver 版本来解决。

        【讨论】:

          猜你喜欢
          • 2017-03-04
          • 2018-08-17
          • 2020-01-14
          • 2020-02-20
          • 2018-06-24
          • 1970-01-01
          • 2023-03-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多