Unable to make multiple plotly graphs in for loop

1.1k views Asked by At

See Image Here I am trying to make Plotly graphs for anomaly detection in time series using Isolation Forest. The problem is: only the plot of the last iteration in for loop apprears. Please help.

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()
    
1

There are 1 answers

0
Rob Raymond On BEST ANSWER
  • have coded placeholders for two functions used in your code create_model() and assign_model()
  • you create fig = make_subplots(rows=len(float_range_list), cols=1) then in loop overwrite it with fig = px.line(). Changed to use variable name fig_ for figure created within loop
  • also then added traces from fig_ to fig within loop
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()

enter image description here