如何解决TypeError:“ AxesSubplot”对象不支持索引
问题:
使用seaborn创建散点图,以市场价格显示价格趋势。考虑50种货币,具有最高的市场价值才能看到趋势。将地块大小分别设置为宽度10英寸和高度2英寸。
注意:这是在我们组织中进行的使用Hackerrank进行培训时的实践黑客马拉松问题。
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import pickle
#File name: question.py
#initial try
'''
def draw_scatterplot(df):
plot,ax= plt.subplots(figsize=(10,2))
plot =sns.scatterplot(x="price",y='market_cap',data=df.nlargest(50,'market_cap'),ax=ax)
plot.data = df.nlargest(50,'market_cap')
return plot
'''
#Later after studied post in stackover flow
def draw_scatterplot(df):
plot,ax= plt.subplots(1,1,figsize=(10,2),squeeze=False,sharex=False)
plot =sns.scatterplot(x="price",ax=ax[0,0])
plot.data = df.nlargest(50,'market_cap')
return plot
def serialize_plot(plot,plot_dump_file):
pickle.dump(plot,open(plot_dump_file,'wb'))
def main():
file_name=input() # data_actual.csv
df=pd.read_csv(file_name)
plot = draw_scatterplot(df)
serialize_plot(plot.axes,"plot_axes.pk")
serialize_plot(plot.data,"plot_data.pk")
if __name__ == '__main__':
main()
要测试程序,必须运行tests.py,同时执行以下操作,将出现以下错误:
@classmethod
def setup_class(cls):
cls.aplot = pickle.load(open('data/actual_plots/aplot_axes.pk','rb'))
cls.aplot_ax = cls.aplot[0][0]
cls.gplot = pickle.load(open('plot_axes.pk','rb'))
> cls.gplot_ax = cls.gplot[0][0]
E TypeError: 'AxesSubplot' object does not support indexing
tests.py:93: TypeError
'''
解决方法
似乎pickle.dump()
使2d数组的尺寸缩小:
import matplotlib.pyplot as plt
import pickle
names = ["group_a","group_b","group_c"]
values = [1,10,100]
fig,ax = plt.subplots(2,3,figsize=(10,2),squeeze=False,sharex=False)
ax[0][0].scatter(names,values)
pickle.dump(fig.axes,open('plot_axes.pk','wb'))
print(ax)
print(type(ax))
输出
[[<AxesSubplot:> <AxesSubplot:> <AxesSubplot:>]
[<AxesSubplot:> <AxesSubplot:> <AxesSubplot:>]]
<class 'numpy.ndarray'>
import matplotlib.pyplot as plt
import pickle
gplot = pickle.load(open('plot_axes.pk','rb'))
gplot_ax = gplot[0]
print(gplot)
print(type(gplot))
输出:
[<AxesSubplot:>,<AxesSubplot:>,<AxesSubplot:>]
<class 'list'>
因此,您可能需要改用cls.gplot[0]
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。