0

I'm trying to use Plotly Scatter to make monthly balance of each branch. Below is my code:

import pandas as pd
import numpy as np
from pandas import ExcelWriter
import plotly.graph_objects as go
import plotly.express as px

df1 = pd.DataFrame({
    'BAS_DT': ['202101','202102','202103','202104','202105','202106',
               '202101','202102','202103','202104','202105','202106',
               '202101','202102','202103','202104','202105','202106'],
    'BR_CD': ['001','001','001','001','001','001',
              '100','100','100','100','100','100',
              '101','101','101','101','101','101'],
    'BAL':[1100,1150,950,1020,999,1025,
           1200,1050,950,1000,950,1075,
           1080,1115,990,898,915,1100]})

df1 = df1.pivot_table(index='BAS_DT', columns='BR_CD', values='BAL').reset_index()
df1.head()

# df1
BR_CD   BAS_DT  001 100 101
0   202101  1100    1200    1200
1   202102  1150    1050    1050
2   202103  950 950 950
3   202104  1020    1000    1000
4   202105  999 950 950
5   202106  1025    1025    1025

fig=go.Figure()
fig.add_trace(go.Scatter(
    x=df1['BAS_DT'],
    y=df1['001'],
    name="001",
    text=df1['001'],
    mode='lines+markers+text',
    textposition='top center',
    line_shape='spline'))

fig.add_trace(go.Scatter(
    x=df1['BAS_DT'],
    y=df1['100'],
    name="100",
    text=df1['100'],
    mode='lines+markers+text',
    textposition='top center',
    line_shape='spline'))

fig.add_trace(go.Scatter(
    x=df1['BAS_DT'],
    y=df1['101'],
    name="101",
    text=df1['101'],
    mode='lines+markers+text',
    textposition='top center',
    line_shape='spline'))

fig.show()

Fig show as below: enter image description here

But my problem is that I will have to add new traces manually if new branches appear. I want to ask is there any way to automatically add new traces based on input dataframe?

Thanks and best regards.

1 Answer 1

2

Iteratively add the traces by looping through the columns you want to use in df1. In this example case you want all the columns that come after column index 0 (BAS_DT) or df1.columns[1:]

fig=go.Figure()

for col in df1.columns[1:]:
    fig.add_trace(go.Scatter(
        x=df1['BAS_DT'],
        y=df1[col],
        name=col,
        text=df1[col],
        mode='lines+markers+text',
        textposition='top center',
        line_shape='spline'))

fig.show()

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, it's worked. Really appreciate.
@hoatran no, problem and good luck with your project.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.