Connect DataTable to ChartLine

Hi guys,

I am trying to connect datatable inputs to plot a linechart but I can’t figure out what should I put in the callbacks as well as in the function.

Here is the code I was using and the csv:

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import numpy as np
import matplotlib.pyplot as plt
import dash
import dash_table
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
import scipy as sp
from scipy.optimize import fsolve
from scipy.interpolate import interp1d

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.SOLAR],
                meta_tags=[{'name': 'viewport',
                            'content': 'width=device-width, initial-scale=1.0'}
                          ]
               )

df = pd.read_csv('Personalise.csv')

app.layout = dbc.Container([
    
    dcc.Graph(
        id='our_graph'),
    
    dash_table.DataTable(
                    id='table',
                    columns=[{"name":i, "id":i} for i in df.columns],
                    data=df.to_dict('records'),
                    editable=True,
                    style_table={'height': '450px', 'overflowY': 'auto'}
    )
]
)

@app.callback(
    Output(component_id='our_graph', component_property='figure'),
    Input(component_id='table', component_property='derived_virtual_data')
)


def update_graph(rows):
    
    dff = df if rows is None else pd.DataFrame(rows)
    x = dff['x']
    y = dff['tCO2 sequestrated']
    fig = go.figure()
    fig.add_trace(go.Scatter(x=x, y=y))
    
    return fig

if __name__ == '__main__':
    app.run_server(debug=False)
    

Thank you so much for your help <3

Hey @marquymarc

Why don’t you use the DataFrame into the callback and then use the columns of the DataFrame directly to the dcc.Graph and to the dcc.Table instead of passing first to the table and then from the table to the graph. :thinking:

Hi Eduardo,

It is because I want to be able to change the values of the Table which will then be projected on to the graph.

I still haven’t find a way to do that.

Here is the CSV I am using if you want to try :wink:

x,tCO2_sequestrated
1,25
2,25
3,25
4,25
5,25
6,25
7,25
8,25
9,25
10,25
11,25
12,25
13,25
14,25
15,25
16,25
17,25
18,25
19,25
20,25
21,25
22,25
23,25
24,25
25,25
26,25
27,25
28,25
29,25
30,25

UPDATE:

Hi Eduardo, I managed to plot a line from the data displayed in the DataTable using the px.line function on a test code to see how it works. Here was the code:

df = pd.read_csv('bijour.csv')

app.layout = dbc.Container([
    
    dcc.Graph(
        id='our_graph'),
    
    dash_table.DataTable(
                    id='table',
                    columns=[{"name":i, "id":i} for i in df.columns],
                    data=df.to_dict('records'),
                    editable=True,
                    style_table={'height': '450px', 'overflowY': 'auto'}
    )
]
)

@app.callback(
    Output(component_id='our_graph', component_property='figure'),
    Input(component_id='table', component_property='data')
)

def update_graph(rows):
    
    dff = pd.DataFrame(rows)
    
    fig = px.line(dff, x=dff.columns[0], y=dff.columns[1])
    
    return fig     


if __name__ == '__main__':
    app.run_server(debug=False)

I now want to integrate it in the main web app I am coding, I also integrated a dropdown component. The app is working well when the dropdown value is on ‘linear’ but not when it is on ‘precise’ which is the position that integrates the Datatable. Do you see any error in my code that would make it work.

df = pd.read_csv('bijour.csv')

app.layout = dbc.Container([
    
    html.H1("Reforestation Project and VCUs",
            className='text-center mb-3'),
    
    html.Br(),
    
    
   
        
    dbc.Row(
        [
            dbc.Col(
                [
                    html.Label('Crediting Period'),

                    dcc.Slider(
                        id='Crediting_period',
                        marks={
                            10: '10 years',
                            30: '30 years',
                            },
                        step=1,
                        tooltip= {'always_visible': True},
                        min=10,
                        max=30,
                        value=15,
                        dots=False,
                        vertical = True,
                        updatemode='drag'
                    )                            
                ],
                width={'size':1}
            ),


            dbc.Col(
                dcc.Graph(
                    id='our_graph'),
                width={'size':5}
            ),
            
            dbc.Col(
                dcc.Dropdown(
                    id='dropdown',
                    options=[
                        {'label': 'linear', 'value': 'linear'},
                        {'label': 'precise', 'value': 'precise'}
                    ],
                    value='linear'
                ),
                width={'size':1}
            
            ),
            
            dbc.Col(
                dash_table.DataTable(
                    id='table',
                    columns=[{"name":i, "id":i} for i in df.columns],
                    data=df.to_dict('records'),
                    editable=True,
                    style_table={'height': '450px', 'overflowY': 'auto'}
                ),
                width={'size': 2, 'offset': 1}
            )
            
        ],
        justify='start',
        no_gutters=True
    ),
    

    
    html.Br(),
    html.Br(),
            
    
            
    dbc.Row(
        [

            dbc.Col(
                [
                    html.H4("Turnover Varibables", style={'text-align': 'center'}),
                    html.Label('Estimated Annual Volume of CO2 sequestrated'),
                    dcc.Slider(
                        id='Estimated_Annual_tCO2',
                        marks={
                            0: '0',
                            5000: '5 000',
                            10000: '10 000',
                            15000: '15 000',
                        },
                        step=100,
                        tooltip= {'always_visible': True},
                        min=0,
                        max=15000,
                        value=7500,
                        dots=False,
                        updatemode='drag'),
                    html.Label('Price of Carbon Credits "$/tCO2"'),
                    dcc.Slider(
                        id='Price_tCO2',
                        marks={
                            0: '$0',
                            20: '$20'
                        },
                        step=0.5,
                        tooltip= {'always_visible': True},
                        min=0,
                        max=20,
                        value=10,
                        dots=False,
                        updatemode='drag'),
                    html.H4("Break Even Point", className='text-center'),
                    html.Div(id='intersection')                    

        ],
                width={'size':3}
                
    ),

            dbc.Col(
                [
                    html.H4("Cost Varibables", style={'text-align': 'center'}),
                    html.Label('Hectares of Land'),
                    dcc.Slider(
                        id='Hectares_of_land',
                        marks={
                            0: '0 ha',
                            50: '50 ha',
                            100: '100 ha',
                            150: '150 ha',
                            200: '200 ha',
                            250: '250 ha',
                            300: '300 ha',
                        },
                        step=10,
                        tooltip= {'always_visible': True},
                        min=0,
                        max=300,
                        value=150,
                        dots=False,
                        updatemode='drag'),
                    html.Label('Variables Costs/Hectare'),
                    dcc.Slider(
                        id='Variables_costs_ha',
                        marks={
                            0: '$ 0',
                            1000: '$ 1000',
                            2000: '$ 2000',
                            3000: '$ 3000',
                            4000: '$ 5000',
                            5000: '$ 5000',
                        },
                        step=50,
                        tooltip= {'always_visible': True},
                        min=0,
                        max=5000,
                        value=2500,
                        dots=False,
                        updatemode='drag'),
                    html.Label('Gap Analysis Fee'),
                    dcc.Slider(
                        id='Gap_analysis_fee',
                        marks={
                            0: '$ 0',
                            20000: '$ 20 000',
                        },
                        step=100,
                        tooltip= {'always_visible': True},
                        min=0,
                        max=20000,
                        value=10000,
                        dots=False,
                        updatemode='drag'),
                    html.Label('Audit Fee'),
                    dcc.Slider(
                        id='Audit_fee',
                        marks={
                            0: '$ 0',
                            20000: '$ 20 000',
                        },
                        step=100,
                        tooltip= {'always_visible': True},
                        min=0,
                        max=20000,
                        value=10000,
                        dots=False,
                        updatemode='drag'),
                ],
                width={'size':3},
                
            )
        ],
        justify='start'
        
    )
        
],
    fluid=True,
    
    
    

)



@app.callback(
    [Output(component_id='our_graph', component_property='figure'),
    Output(component_id='intersection', component_property='children')],
    [Input(component_id='Estimated_Annual_tCO2', component_property='value'),
    Input(component_id='Price_tCO2', component_property='value'),
    Input(component_id='Hectares_of_land', component_property='value'),
    Input(component_id='Variables_costs_ha', component_property='value'),
    Input(component_id='Gap_analysis_fee', component_property='value'),
    Input(component_id='Audit_fee', component_property='value'),
    Input(component_id='Crediting_period', component_property='value'),
    Input(component_id='table', component_property='data'),
    Input(component_id='dropdown', component_property='value')]  
)
    
def update_graph(Est_ann_emissions, Price, Hectares_of_land, Var_costs_ha, Gap_fee, Audit_fee, Cred_period, rows, dropdown):
    m= Cred_period
    x=np.arange(0, m+1)
    b= 8375 + Est_ann_emissions*0.1*x + 0.05*Est_ann_emissions*x + 0.02*Est_ann_emissions*x + 2500*x + Gap_fee + Audit_fee + Hectares_of_land*Var_costs_ha
    dff = pd.DataFrame(rows)
    
    if dropdown=='linear':
        y=x*Est_ann_emissions*Price
        fig = go.Figure()
        fig.add_trace(go.Scatter(x=x, y=y, name='Turnover'))
        fig.add_trace(go.Scatter(x=x, y=b, name='Costs'))
        
    else :
        y = dff.columns[1]
        x = [dff.columns[0] for x in range(np.arange(0, m+1))]
        fig = go.Figure()
        fig.add_trace(px.line(dff, x=x, y=y, name='Turnover'))
        fig.add_trace(go.Scatter(x=x, y=b, name='Costs'))

    bep = interp1d(y - b, x)(0)
        

    return fig, bep

Thank you so much for your help :wink:

Hey @marquymarc

Glad to know you solved your issue :smiley:

Two tips:

  • If you want to say something to any of the community, use the @ to find the name and add it like @marquymarc , and the system will notify them.

  • Use debug= True in your development, then you can access to the error message:

app.run_server(debug=True)

And with then you will access to something like this:
image

Apparently the figure you are building needs integers numbers to work :thinking: :woozy_face:

:slightly_smiling_face:

Unfortunately, when I am setting “debug=True”, the web application won’t load…