问题描述
为什么这个matplotlib代码给我一个怪异的异常?我要去两排地块.顶行应该显示 true 与 pred,底行应该显示百分比错误.
Why is this matplotlib code giving me a weird exception? I'm going for two rows of plots. The top row is supposed to show true vs. pred and the bottom row is supposed to show percent error.
yy = func(*X)
fig, axes = plt.subplots(1, len(X))
for ax,_x in zip(axes,X):
ax.plot(_x, y, 'b.')
ax.plot(_x, yy, 'r.')
fig, axes = plt.subplots(2, len(X))
for ax,_x in zip(axes,X):
ax.plot(_x, yy/y-1, 'r.')
plt.show()
追溯:
File "pysr.py", line 235, in main
ax.plot(_x, yy/y-1, 'r.')
AttributeError: 'numpy.ndarray' object has no attribute 'plot'
推荐答案
如果 len(X)
是 >1,axes
将是 的二维数组AxesSubplot
实例.因此,当您遍历 axes
时,您实际上会沿着 axes
数组的一个维度得到一个切片.
If len(X)
is >1, axes
will be a 2D array of AxesSubplot
instances. So when you loop over axes
, you actually get a slice along one dimension of the axes
array.
要解决此问题,您可以使用 axes.flat
:
To overcome this, you could use axes.flat
:
for ax,_x in zip(axes.flat,X):
此外,如果您尝试将所有这些绘制在一个图形上,则无需调用 plt.subplots
两次,因为这样会创建两个图形.
Also if you are trying to plot all these on one figure, you don't need to call plt.subplots
twice, as that will create two figures.
像这样索引 axes
数组可能更容易:
It may be easier to index the axes
array like this:
yy = func(*X)
fig, axes = plt.subplots(2, len(X))
for i,_x in enumerate(X):
axes[0, i].plot(_x, y, 'b.')
axes[0, i].plot(_x, yy, 'r.')
axes[1, i].plot(_x, yy/y-1, 'r.')
plt.show()
这篇关于AttributeError:"numpy.ndarray"对象没有属性"plot"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!