Python 循环生成子图时出错
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19953348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error when looping to produce subplots
提问by Ashleigh Clayton
I have a question about an error I receive when looping to plot multiple subplots from a data frame.
我有一个关于在循环绘制数据框中的多个子图时收到的错误的问题。
My data frame has many columns, of which I loop over to have a subplot of each column.
我的数据框有很多列,我循环其中的每一列都有一个子图。
This is my code
这是我的代码
def plot(df):
channels=[]
for i in df:
channels.append(i)
fig, ax = plt.subplots(len(channels), sharex=True, figsize=(50,100))
plot=0
for j in df:
ax[plot].plot(df["%s" % j])
ax[plot].set_xlabel('%s' % j)
plot=plot+1
plt.tight_layout()
plt.show()
I get the plot produced fine, but also an empty frame and the error:
我得到的情节很好,但也有一个空帧和错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\AClayton\WinPython-64bit-2.7.5.3\python-2.7.5.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 538, in runfile
execfile(filename, namespace)
File "C:/Users/AClayton/Desktop/Data/TS.py", line 67, in <module>
plot(all_data)
File "C:/Users/AClayton/Desktop/Data/TS.py", line 49, in plot
ax[plot].plot(reader["%s" % j])
TypeError: 'AxesSubplot' object does not support indexing
I can't see where this error comes from if the first plot is produced fine, or why the second figure is produced?
如果第一个图生成得很好,或者为什么生成第二个图,我看不出这个错误来自哪里?
Thanks for any insight
感谢您的任何见解
采纳答案by Rutger Kassies
If you plot multiple subplots, the plt.subplots()
returns the axes in an array, that array allows indexing like you do with ax[plot]
. When only 1 subplot is created, by default it returns the axes itself, not the axes within an array.
如果绘制多个子图,则plt.subplots()
返回数组中的轴,该数组允许像使用ax[plot]
. 当只创建 1 个子图时,默认情况下它返回轴本身,而不是数组中的轴。
So your error occurs when len(channels)
equals 1. You can suppress this behavior by setting squeeze=False
in the .subplots()
command. This forces it to always return a 'Rows x Cols' sized array with the axes, even if its a single one.
因此,当len(channels)
等于 1时会发生错误。您可以通过squeeze=False
在.subplots()
命令中设置来抑制此行为。这迫使它始终返回一个带有轴的“行 x 列”大小的数组,即使它是单个数组。
So:
所以:
def plot(df):
channels=[]
for i in df:
channels.append(i)
fig, ax = plt.subplots(len(channels),1, sharex=True, figsize=(50,100), squeeze=False)
plot=0
for j in df:
ax[plot,0].plot(df["%s" % j])
ax[plot,0].set_xlabel('%s' % j)
plot=plot+1
plt.tight_layout()
plt.show()
By adding the squeeze
keyword you always get a 2D array in return, so the indexing for a subplot changes to ax[plot,0]
. I have also specifically added the amount of columns (1 in this case).
通过添加squeeze
关键字,您总是会得到一个二维数组作为回报,因此子图的索引更改为ax[plot,0]
. 我还特别添加了列数(在这种情况下为 1)。