【发布时间】:2016-10-24 09:08:36
【问题描述】:
如果您试图理解错误消息,以下信息可能是多余的。请先阅读the answer @user707650。
使用 MatPlotLib,我想要一个可通用的脚本,可以从我的数据中创建以下内容。
一个包含 a 个子图的窗口,每列有 b 个子图。我希望能够更改 a 和 b 的值。
如果我有 2a 个子图的数据,我想要 2 个窗口,每个窗口都有前面描述的“a 子图按照 b 每列子图排列”。
我绘制的 x 和 y 数据是存储在 np.arrays 中的浮点数,结构如下:
-
所有图的 x 数据始终相同,长度为 5。
'x_vector': [0.000, 0.005, 0.010, 0.020, 0.030, 0.040] 所有图的 y 数据都存储在 y_vector 中,其中第一个图的数据存储在索引 0 到 5 处。第二个图的数据存储在索引 6 到 5 处11.第三个地块得到12-18,第四个地块得到19-24,依此类推。
对于这个数据集,我总共有 91 个图(即 91*6 = 546 个值存储在 y_vector 中)。
尝试:
import matplotlib.pyplot as plt
# Options:
plots_tot = 14 # Total number of plots. In reality there is going to be 7*13 = 91 plots.
location_of_ydata = 6 # The values for the n:th plot can be found in the y_vector at index 'n*6' through 'n*6 + 6'.
plots_window = 7 # Total number of plots per window.
rows = 2 # Number of rows, i.e. number of subplots per column.
# Calculating number of columns:
prim_cols = plots_window / rows
extra_cols = 0
if plots_window % rows > 0:
extra_cols = 1
cols = prim_cols + extra_cols
print 'cols:', cols
print 'rows:', rows
# Plotting:
n=0
x=0
fig, ax = plt.subplots(rows, cols)
while x <= plots_tot:
ax[x].plot(x_vector, y_vector[n:(n+location_of_ydata)], 'ro')
if x % plots_window == plots_window - 1:
plt.show() # New window for every 7 plots.
n = n+location_of_ydata
x = x+1
我收到以下错误:
cols: 4
rows: 2
Traceback (most recent call last):
File "Script.py", line 222, in <module>
ax[x].plot(x_vector, y_vector[n:(n+location_of_ydata)], 'ro')
AttributeError: 'numpy.ndarray' object has no attribute 'plot'
【问题讨论】:
-
导入 numpy 并不重要:matplotlib (pyplot) 已经在幕后做到了,因为它是 matplotlib 的主要依赖项。
-
matplotlib 和 numpy 真的应该在这里一起工作以抛出更好的错误。这是我希望它是 Matlab 的罕见实例之一。 :)
标签: python numpy matplotlib multidimensional-array subplot