簡體   English   中英

如何返回帶有軸和數據的散點圖?

[英]How can I return scatterplot with axes and data?

這個問題來自我的訓練 class,我只能在方法 def draw_scatterplot(df) 中添加代碼。 Using Anaconda Spyder, Python 3.8.3, Seaborn 0.10.1, Matplotlib 3.1.3. 如何返回 plot 以及來自我的 function 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'

我也嘗試返回軸:

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'

對於返回的圖形和軸, serialize_plot(plot2.axes, "plot2_axes.pk")正在工作,因為軸是從 function 返回的,我看到文件"plot2_axes.pk"已創建。

要從 function 返回整個圖表,您可以返回您的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 筆記本。因此調用 main 而沒有plot2.show

Output:

輸出示例

我知道最終你想把你的身材丟進泡菜里。 為此,您可以直接轉儲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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM