首页 > 解决方案 > 如何将多轨迹图制作为可重用代码?

问题描述

我以某种方式尝试为例如 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()

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

......

标签: pythonpython-3.xplotly

解决方案


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

# 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):它被构造为一个函数,可以很容易地应用于任何数据帧。

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

在此处输入图像描述

情节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)

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

情节2:

在此处输入图像描述

代码 2:

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

plotMaxMin(df2)

我们仍然缺少updatemnu(). 事实上,只需单击系列的名称,情节仍然非常具有互动性。

使用 go.layout.Updatemenu() 进行测试

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

情节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:有关如何使用更多参数扩展函数以自定义绘图图形的示例

情节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'})

推荐阅读