Skip to main content
 首页 » 编程设计

python之如何将多迹线图制作为可重用代码

2024年11月01日13xing901022

我以某种方式试图为 bar_graph 制作可重用的绘图代码:

def bar(x,y,text,marker,orientation,name): 
    barchart=[go.Bar(x=x,y=y,text=text,marker=marker,orientation=orientation,name=name)] 
    ........ 

以类似的方式,我怎样才能为多个跟踪创建可重用的代码?

对于下面的代码,

fig = go.Figure() 
 
# Add Traces 
 
fig.add_trace( 
    go.Scatter(x=list(df.index), 
               y=list(df.High), 
               name="High", 
               line=dict(color="#33CFA5"))) 
 
fig.add_trace( 
    go.Scatter(x=list(df.index), 
               y=[df.High.mean()] * len(df.index), 
               name="High Average", 
               visible=False, 
               line=dict(color="#33CFA5", dash="dash"))) 
 
fig.add_trace( 
    go.Scatter(x=list(df.index), 
               y=list(df.Low), 
               name="Low", 
               line=dict(color="#F06A6A")))fig.update_layout( 
    updatemenus=[ 
        go.layout.Updatemenu( 
            active=0, 
            buttons=list([ 
                dict(label="None", 
                     method="update", 
                     args=[{"visible": [True, False, True, False]}, 
                           {"title": "Yahoo", 
                            "annotations": []}]), 
                dict(label="High", 
                     method="update", 
                     args=[{"visible": [True, True, False, False]}, 
                           {"title": "Yahoo High", 
                            "annotations": high_annotations}]), 
                dict(label="Low", 
                     method="update", 
                     args=[{"visible": [False, False, True, True]}, 
                           {"title": "Yahoo Low", 
                            "annotations": low_annotations}]), 
 
            ]), 
        ) 
    ]) 
 
# Set title 
fig.update_layout(title_text="Yahoo") 
 
fig.show() 

在这里,踪迹可以是任意的,即基于为每个踪迹传递的值的组合,那么我如何才能将其作为可重用代码?

.....

请您参考如下方法:

您可以轻松地遍历数据框的列,并为每个列创建跟踪,如下面的代码片段所示。

# crate traces 
traces={} 
for col in df.columns: 
    traces['trace_' + col]=go.Bar(x=df.index, name=col, y=df[col]) 
 
# convert data to form required by plotly 
data=list(traces.values()) 
 
# build figure 
fig=go.Figure(data) 
fig.show() 

在评论和聊天中与 OP 对话后编辑建议。

如果没有可重现的数据样本,就很难提出完美的解决方案。但这里有一个可重复使用的建议:

(1):它在源数据框中的列数方面很灵活,并使用 for 循环按要求添加跟踪,

(2):它为每一列计算 max() 和 min(),

(3):它被构造为一个函数,可以轻松应用于任何数据框。

我整理了一些示例数据,如下所示:

plotly 1:

代码 1:

# Imports 
import pandas as pd 
import plotly.graph_objs as go 
import matplotlib.pyplot as plt 
import numpy as np 
 
# data 
humid = pd.Series(np.random.uniform(low=25, high=40, size=6).tolist()) 
windy = pd.Series(np.random.uniform(low=40, high=60, size=6).tolist()) 
df = pd.concat([humid,windy], axis = 1) 
df.columns=['Humidity', 'windspeed'] 
df.index = ['Shanghai', 'Houston', 'Venice', 'Munich', 'Milan', 'Turin'] 
 
 
def plotMaxMin(df): 
    for col in df.columns: 
        #print(df[col].max()) 
        df[col+'_max']=df[col].max() 
        df[col+'_min']=df[col].min() 
 
    # crate traces 
    traces={} 
    for col in df.columns: 
        traces['trace_' + col]=go.Scatter(x=df.index, name=col, y=df[col]) 
 
    # convert data to form required by plotly 
    data=list(traces.values()) 
 
    # build figure 
    fig=go.Figure(data) 
    fig.show() 
 
plotMaxMin(df=df) 

使用编辑后的数据框测试可重用性:

plotly 2:

代码 2:

df2=df.copy(deep=True) 
df2['Temperature']=pd.Series(np.random.uniform(low=-5, high=40, size=6).tolist()) 
 
plotMaxMin(df2) 

我们仍然缺少 updatemnu()。事实上,只需单击系列的名称, plotly 仍然非常互动。

用 go.layout.Updatemenu() 测试

这将需要更多调整才能完美,但主要功能似乎已经到位,所以我希望您能够添加一些东西以使其与您的数据集一样精确。

plotly 3:

代码 3:

# Imports 
import pandas as pd 
import matplotlib.pyplot as plt 
import numpy as np 
 
# data 
humid = pd.Series(np.random.uniform(low=25, high=40, size=6).tolist()) 
windy = pd.Series(np.random.uniform(low=40, high=60, size=6).tolist()) 
df = pd.concat([humid,windy], axis = 1) 
df.columns=['Humidity', 'windspeed'] 
df.index = ['Shanghai', 'Houston', 'Venice', 'Munich', 'Milan', 'Turin'] 
 
 
def plotMaxMin(df): 
    for col in df.columns: 
        #print(df[col].max()) 
        df[col+'_max']=df[col].max() 
        df[col+'_min']=df[col].min() 
 
    # crate traces 
    traces={} 
    for col in df.columns: 
        traces['trace_' + col]=go.Scatter(x=df.index, name=col, y=df[col]) 
 
    # convert data to form required by plotly 
    data=list(traces.values()) 
 
    # build figure 
    fig=go.Figure(data) 
 
    # add dropdown functionality 
 
    fig.update_layout( 
    updatemenus=[ 
        go.layout.Updatemenu( 
            active=0, 
            buttons=list([ 
                dict(label="None", 
                     method="update", 
                     args=[{"visible": [True, False, True, False]}, 
                           {"title": "Yahoo", 
                            "annotations": []}]), 
                dict(label="High", 
                     method="update", 
                     args=[{"visible": [True, True, False, False]}, 
                           {"title": "Yahoo High", 
                            "annotations": high_annotations}]), 
                dict(label="Low", 
                     method="update", 
                     args=[{"visible": [False, False, True, True]}, 
                           {"title": "Yahoo Low", 
                            "annotations": high_annotations}]), 
 
            ]), 
        ) 
    ]) 
 
 
 
    fig.show() 
 
plotMaxMin(df=df) 

编辑 2:有关如何使用更多参数扩展函数以自定义您的绘图的示例

plotly 4:

代码 4:

# Imports 
import pandas as pd 
import matplotlib.pyplot as plt 
import numpy as np 
 
# data 
humid = pd.Series(np.random.uniform(low=25, high=40, size=6).tolist()) 
windy = pd.Series(np.random.uniform(low=40, high=60, size=6).tolist()) 
df = pd.concat([humid,windy], axis = 1) 
df.columns=['Humidity', 'Windspeed'] 
df.index = ['Shanghai', 'Houston', 'Venice', 'Munich', 'Milan', 'Turin'] 
 
 
def plotMaxMin(df, colors): 
    """Adds max and min for all df columns and plots the data using plotly 
 
    Arguments: 
    ========== 
    df - pandas dataframe 
    colors - dictionary with single word to identify line category and assign color 
 
    Example call: 
    ============= 
    plotMaxMin(df=df, colors={'wind':'#33CFA5', 'humidity':'#F06A6A'}) 
 
    """ 
 
 
    # add max and min for each input column 
    for col in df.columns: 
        df[col+'_max']=df[col].max() 
        df[col+'_min']=df[col].min() 
 
    # sort df columns by name 
    df = df.reindex(sorted(df.columns), axis=1) 
 
    # crate traces 
    traces={} 
    for col in df.columns: 
 
        # format traces 
        if 'Humid' in col: 
            linecolor = colors['humidity'] 
 
        if 'Wind' in col: 
            linecolor = colors['wind'] 
 
        traces['trace_' + col]=go.Scatter(x=df.index, name=col, y=df[col], line=dict(color=linecolor)) 
 
    # convert data to form required by plotly 
    data=list(traces.values()) 
 
    # build figure 
    fig=go.Figure(data) 
 
    # uncomment bloew section to add dropdown functionality 
 
    #fig.update_layout( 
    #updatemenus=[ 
    #    go.layout.Updatemenu( 
    #        active=0, 
    #        buttons=list([ 
    #            dict(label="None", 
    #                 method="update", 
    #                 args=[{"visible": [True, False, True, False]}, 
    #                       {"title": "Yahoo", 
    #                        "annotations": []}]), 
    #            dict(label="High", 
    #                 method="update", 
    #                 args=[{"visible": [True, True, False, False]}, 
    #                       {"title": "Yahoo High", 
    #                        "annotations": high_annotations}]), 
    #            dict(label="Low", 
    #                 method="update", 
    #                 args=[{"visible": [False, False, True, True]}, 
    #                       {"title": "Yahoo Low", 
    #                        "annotations": high_annotations}]), 
    #        ]), 
    #    ) 
    #]) 
 
 
 
    fig.show() 
 
plotMaxMin(df=df, colors={'wind':'#33CFA5', 'humidity':'#F06A6A'})