【发布时间】:2018-01-07 13:45:36
【问题描述】:
我很难理解pyplot.plot 的工作原理。
我举一个简单的例子:我想绘制pyplot.plot(lst2, lst2),其中 lst2 是一个列表。
困难在于 lst2 的每个元素都是一个形状为 (1,1) 的数组。如果元素是浮动的而不是数组,就没有问题。
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
V2 = np.array([[1]])
W2 = np.array([[2]])
print('The shape of V2 is', V2.shape)
print('The shape of W2 is', W2.shape)
lst2 = [V2, W2]
plt.plot(lst2, lst2)
plt.show
以下是我收到的错误消息的结尾:
~\Anaconda3\lib\site-packages\matplotlib\axes\_base.py in _xy_from_xy(self,x, y)
245 if x.ndim > 2 or y.ndim > 2:
246 raise ValueError("x and y can be no greater than 2-D, but have "
--> 247 "shapes {} and {}".format(x.shape, y.shape))
248
249 if x.ndim == 1:
ValueError: x and y can be no greater than 2-D, but have shapes (2, 1, 1) and (2, 1, 1)
错误消息中让我惊讶的是提到了一个维度为 (2,1,1) 的数组。看起来数组np.array([V2,W2]) 是在我们调用pyplot.plot 时构建的。
我的问题是,当我们使用 x 和 y 列表调用 pyplot.plot(x,y) 时,幕后会发生什么?似乎构建了一个包含 x 元素的数组(对于 y 也是如此)。并且这些数组必须有最大 2 个轴。我对么?
我知道如果我在 V2 和 W2 上使用 numpy.squeeze,它会起作用。但我想了解在我给出的示例中pyplot.plot 内部发生了什么。
【问题讨论】:
标签: python arrays numpy matplotlib plot