Learning Dash - How to Add Traces

Hello Everyone and sorry for such a simple question.

My goal is to be more functional in Dash to display results of data science applications that I am trying to build - for this application I would like to view some data from one of my data repositories. The tutorial I am following is here - I am trying to alter the code and understand how to add a trace to the top scatter chart which is in the Singapore.py file. The link to the tutorial is here: https://towardsdatascience.com/beginners-guide-to-building-a-multi-page-dashboard-using-dash-5d06dbfc7599

I have attempted two changes:
1)
data = go.Scatter()
data.add_trace[go.scatter(x=dff[‘Date’], y=dff[‘total’],
mode=‘lines+markers’, name=‘Daily confirmed’)]

and 2)
data = [go.Scatter(x=dff[‘Date’], y=dff[‘total’],
mode=‘lines+markers’,name=‘Daily confirmed’)]
data.add_trace[go.Scatter(x=dff[‘Date’], y=dff[‘Daily Imported’],
mode=‘lines+markers’,name=‘Daily confirmed’)]

The code which does work but only includes 1 trace and not multiple traces is:
data = [go.Scatter(x=dff[‘Date’], y=dff[‘total’],
mode=‘lines+markers’,name=‘Daily confirmed’)]

The error I get is:
AttributeError: ‘Scatter’ object has no attribute ‘add_trace’

I am sure there is more information needed - this is my first app and experience with Python so please, if you could reach out and let me know what more to include - I would love to collaborate and use your help to solve my issue.

Thank you,
Chris

Hi,

Welcome to the community, Chris! :slightly_smiling_face:

Your code number one can be fixed by changing the first line to:

fig = go.Figure()
fig.add_trace(...) # and so on

I changed data to fig because that’s usually how the object gets initialized (so it can be less confusing for you).

You can add traces to fig using fig,add_traces(), of course. Another approach is to pass the traces in a list on initialization using the data argument:

fig = go.Figure(
     data=[
          go.Scatter(...),
          go.Scatter(...),
          # and whatever traces you need...
     ]
)

I guess this is closer to the method 2 you mentioned.

Link to the docs: Creating And Updating Figures

Hope this helps! :slightly_smiling_face:

3 Likes

Oh great, thank you so much. I used the second example you gave me and it worked great - now I will go learn how to format the legend and the line colors … etc…

Thanks again and also, thanks for the link - it was very useful.

1 Like