我如何 return 使用轴和数据绘制散点图?

How can I return scatterplot with axes and data?

这个问题来自我的培训 class,我只能在 def draw_scatterplot(df) 方法中添加代码。 使用 Anaconda Spyder,Python 3.8.3,Seaborn 0.10.1,Matplotlib 3.1.3。 我怎样才能 return 从我的函数 def draw_scatterplot(df) 绘制坐标轴和数据?

import pandas as pd
import matplotlib 
matplotlib.use('Agg') 
import seaborn as sns 
import pickle 

def draw_scatterplot(df): 
    '''
    Returns a scatter plot.  
    '''
    # Create a scatter plot using Seaborn showing trend of A with B
    # for C.  Set the plot size to 10 inches in width and 2 inches 
    # in height respectively.

    # add your code below
    fig, ax1 = matplotlib.pyplot.subplots(figsize=(10,2))
    ax2 = sns.scatterplot(x='A', y='B', data=df, ax=ax1, hue='C')
    return fig

def serialize_plot(plot, plot_dump_file): 
    with open(plot_dump_file, mode='w+b') as fp: 
        pickle.dump(plot, fp) 

def main(): 
    df = pd.DataFrame(...) 
    plot2 = draw_scatterplot(df) 
    serialize_plot(plot2.axes, "plot2_axes.pk") 
    serialize_plot(plot2.data, "plot2_data.pk") 


> Error: Traceback (most recent call last):
> 
>   File "myscatterplot.py", line 265, in <module>
>     main()
> 
>   File "myscatterplot.py", line 255, in main
>     serialize_plot(plot2.data, "plot2_data.pk")
> 
> AttributeError: 'Figure' object has no attribute 'data'

我也试过 returning 坐标轴:

def draw_scatterplot(df): 
    '''
    Returns a scatter plot
    '''
    fig, ax1 = matplotlib.pyplot.subplots(figsize=(10,2))
    ax2 = sns.scatterplot(x='A', y='B', data=df, ax=ax1, hue='C')
    return ax2

Error:
AttributeError: 'AxesSubplot' object has no attribute 'data'

对于 returning 图和轴,serialize_plot(plot2.axes, "plot2_axes.pk") 正在工作, 因为轴是 return 从函数编辑的,我看到文件 "plot2_axes.pk" 已创建。

从一个函数 return 整个图表,您可以 return 您的 fig 变量。它包含所有需要的信息。

import pandas as pd
import matplotlib 
import seaborn as sns 
import pickle 

def draw_scatterplot(df): 
    '''
    Returns a scatter plot
    '''
    fig, ax1 = matplotlib.pyplot.subplots(figsize=(10,2))
    ax2 = sns.scatterplot(x='A', y='B', data=df, ax=ax1, hue='C')
#     return ax2
    return fig

def serialize_plot(plot, plot_dump_file): 
    with open(plot_dump_file, mode='w+b') as fp: 
        pickle.dump(plot, fp) 

def main(): 
    df = pd.DataFrame({"A":[1,2,3], "B":[6,2,7], "C":[1,0,1]}) 
    plot2 = draw_scatterplot(df) 

main()

(我正在使用 juypter notebook。因此调用了 main 而没有 plot2.show

输出:

我知道你最终想把你的身材扔进泡菜里。为此,您可以直接转储 plot2(图),不需要 plot2.data 或类似的东西。

def main(): 
    df = pd.DataFrame(...) 
    plot2 = draw_scatterplot(df) 
    serialize_plot(plot2, "plot2.pk")

我更新了下面的方法,现在没有收到错误。

def draw_scatterplot(df): 
'''
Returns a scatter plot
'''
fig, ax1 = matplotlib.pyplot.subplots(figsize=(10,2))
ax2 = sns.scatterplot(x='A', y='B', data=df, ax=ax1, hue='C')
# return ax2
fig.data = df
return fig