【问题标题】:TypeError: 'AxesSubplot' object does not support indexingTypeError:“AxesSubplot”对象不支持索引
【发布时间】:2020-08-17 11:17:32
【问题描述】:

问题:

使用 seaborn 创建散点图,显示价格与 Market Capital 的趋势。考虑 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", y='market_cap', data=df.nlargest(50,'market_cap'),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

'''

【问题讨论】:

    标签: python pandas matplotlib pickle axes


    【解决方案1】:

    似乎pickle.dump() 使二维数组尺寸缩小:

    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:>, <AxesSubplot:>, <AxesSubplot:>, <AxesSubplot:>]
    <class 'list'>
    

    因此您可能需要改用cls.gplot[0]

    【讨论】:

      猜你喜欢
      • 2013-08-23
      • 2018-01-07
      • 2013-06-23
      • 2019-04-18
      • 2016-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多