无法在for循环中制作多个绘图

Unable to make multiple plotly graphs in for loop

See Image Here 我正在尝试使用 Isolation Forest 在时间序列中制作用于异常检测的 Plotly 图。问题是:只有 for 循环中最后一次迭代的情节出现。请帮忙

import plotly.express as px
import plotly.graph_objs as go
from plotly.subplots import make_subplots
start = 0.01
stop = 0.26
step = 0.05
float_range_array = np.arange(start, stop, step)
float_range_list = list(float_range_array)
fig = make_subplots(
    rows=len(float_range_list), cols=1)
for x1,i in enumerate(float_range_list):
    iforest1 = create_model('pca', fraction = i)
    iforest_results = assign_model(iforest1)
    fig = px.line( iforest_results, x="timestamp", y="value", 
    title='Principal Component Analysis: Fraction={}'.format(round(i,2)),template = 
    'plotly',labels={"timestamp": "Stay Date","value": "Number of Bookings"})
    outlier_dates = iforest_results[iforest_results['Anomaly'] == 1].index
    outlier_dates1=iforest_results.iloc[outlier_dates]['timestamp']
    y_values = [iforest_results.loc[i]['value'] for i in outlier_dates]
    fig.add_trace(go.Scatter(x=outlier_dates1, y=y_values, mode = 'markers',
    name = 'Anomaly', marker=dict(color='red',size=10)),row=x1+1,col=1)
fig.show()
    
  • 已为代码中使用的两个函数编码占位符 create_model()assign_model()
  • 你创建 fig = make_subplots(rows=len(float_range_list), cols=1) 然后在循环中用 fig = px.line() 覆盖它。已更改为在循环
  • 中创建的图形使用变量名称 fig_
  • 然后在循环
  • 中添加了从fig_fig的跟踪
import plotly.express as px
import plotly.graph_objs as go
from plotly.subplots import make_subplots
import pandas as pd
import numpy as np

def create_model(a,fraction=.1):
    return 1

def assign_model(n):
    return pd.DataFrame({"timestamp":pd.date_range("1-mar-2022", freq="1H", periods=100),
                        "value":np.random.uniform(1,10,100),
                        "Anomaly":np.full(100, 1)})

start = 0.01
stop = 0.26
step = 0.05
float_range_array = np.arange(start, stop, step)
float_range_list = list(float_range_array)
fig = make_subplots(rows=len(float_range_list), cols=1)
for x1, i in enumerate(float_range_list):
    iforest1 = create_model("pca", fraction=i)
    iforest_results = assign_model(iforest1)
    fig_ = px.line(
        iforest_results,
        x="timestamp",
        y="value",
        title="Principal Component Analysis: Fraction={}".format(round(i, 2)),
        template="plotly",
        labels={"timestamp": "Stay Date", "value": "Number of Bookings"},
    )
    outlier_dates = iforest_results[iforest_results["Anomaly"] == 1].index
    outlier_dates1 = iforest_results.iloc[outlier_dates]["timestamp"]
    y_values = [iforest_results.loc[i]["value"] for i in outlier_dates]
    fig.add_trace(
        go.Scatter(
            x=outlier_dates1,
            y=y_values,
            mode="markers",
            name="Anomaly",
            marker=dict(color="red", size=6),
        ),
        row=x1 + 1,
        col=1,
    )
    for t in fig_.data:
        fig.add_trace(t, row=x1+1,col=1)


fig.show()