The Dash Callback - Input, Output, State, and more
Vložit
- čas přidán 21. 07. 2024
- The Callback is the most important element in Dash. You need to know it so you can create interactive dashboard apps. In this tutorial I'll show you how to use the callback to connect between the various components of your app, such as the dropdown, the graph, and the pie chart.
View my book - The Book of Dash:
www.amazon.com/Python-Dash-An...
github.com/DashBookProject/Pl...
Code:
github.com/Coding-with-Adam/D...
Data:
drive.google.com/file/d/1Nzzg...
Dash Documentation:
dash.plotly.com/basic-callbacks
Supporting Document:
drive.google.com/file/d/1iodF...
Video layout:
00:00 - What you will learn
02:37 - Start coding
04:29 - Single Input and Output
11:35 - State, PreventUpdate
17:03 - Multiple Output and Input, Dash.no_update
22:49 - Callback facts you need to remember!
************************************************************************
👉 Your support keeps Charming Data running, which is proudly a 100% member-supported educational channel:
Patreon: / charmingdata
GitHub: github.com/sponsors/Coding-wi...
CZcams: / @charmingdata
Hey Everybody, I hope this tutorial helps you build those beautiful dashboards. Don't forget to download the code ,the data, and the supporting docs, located under the video.
👉If you benefitted from these tutorials & would like to show your appreciation & support the existence of more tutorials: www.patreon.com/charmingdata
Excellent video. I keep coming back to this (and your Dash videos in general) and learning/understanding new things. Thank you for putting in all this work to help other people learn.
So thankful. You are a great and thoughtful teacher. I hope to build my dash app soon.
Your videos are the best, I was trying to find a way to trigger a callback only the button was pressed, and this State (which I didn't know so far) worked perfectly!
Man this was a good video to watch, without that explanation I don't think I would have gotten this for a while. Very good breakdown, thanks. I would love to see something like this but attached to a local database with an API on it. Just best practices on how to put requests into the callbacks
17:18 was the solution to the problem I mailed you about :) I had my single Output inside a list. Thanks for all the content!
You are the sole knowledge provider for plotly dash so far!!
Just dropping by to say that this video has helped me enormously in creating my own Dash app with a complicated callback, thank you!
You're welcome, Marlin. I'm glad it helped. Good luck building your future apps 👍🏼
Everyone needs a teacher like you. Thanks a lot.
You're a life-savior man. Everything was brilliantly explained. You've got a subscriber.
Adam, your tutorial videos are the best. Thanks to them, I got a job at a startup. I was looking for a position as a React developer, but unexpectedly in the test task there was a requirement to write code in Dash Plotly. I opened your channel, repeated a couple of examples and was able to beat the competition.
Thank you! your work and expertise is recognized and appreciated!
Thank you so much! You're giving me a massive help with my college projects, your explanations are SO clean, I can't describe in words how much you're being helpful to me. Cheers from Brazil
You're welcome @Eduardo. I'm happy you're benefiting from my videos..good luck with your app. Greeting from New York City
Greatest channel i ever see in YT! Thankyou very much
This was well-thought and thorough, Thank you Adam :)
You're welcome @Belderchin. Thanks for watching this channel.
Thanks a lot for your efforts in this channel man, the videos are to the point and really helped me learn a lot of concepts much more quickly than reading the docs. Subscribed :)
I'm glad Omar. Good luck with building powerful dashboards. Let me know if you have any questions.
thanks, great video! looking forward for the advanced callbacks tutorial :)
Don't forget to check out the dynamic callback tutorial that was posted several months ago.
great vid thank you! Alot in here very much worth it
My callback with multiple graph outputs and just one line from this video has eased my school project by like 6000%.
Thank you!
You're welcome @Ian. I'm glad it was helpful. Hope you get to watch future charmingdata videos.
excellent video, thanks for sharing Adam!
Thanks a lot, Charming Data was stuck on call backs for a long time, This video really helped. :) Please keep up the good work
Thank you
Thanks. It`s helpful to understand callback usage.
Great tutorial.
Thank you so much. 😊👍
Thank you so much with such detailed video on dash plotly.
An excellent tutorial! Thank you!
This is great stuff brother. Thank You.
Well done, Adam! Really clear explanations! It would be interesting to see a video on dash performance with somewhat large data samples, e.g. 400k rows by 30 columns and ways to speed up the dashboard performance if we use a number of filters/inputs for charts. Cheers!
I know. A big data tutorial would be very good. I was trying to work on one with Vaex but it's still in its infancy, so I'm not sure about it yet. Maybe I'll use PySpark...
Thanks for the video, it helps me a lot!
Fantastic. You are probably one of the best programming teachers out there. Can you please make longer videos with real time data dashboards? I think a weather app would be great
Hi @Shaheer, thank you for your suggestions. I actually have a weather app here:
czcams.com/video/NEMDvIUaI6A/video.html
I'll try to make more real-time videos. If you'd like to support the creation of these tutorials, I'd be very thankful :)
www.patreon.com/charmingdata
These are great! Better than Dash's official examples
Man!!! Thanks a ton. The way u explain is make things super easy
Thank you I appreciate it.
Helped me out a lot...explanation is killer ! Thanks a ton
Your videos are outstanding!! Thank you
Thanks Camilo
Great tutorial! Very helpful
Thank you, man!! You helped me a lot!!! Great job, keep it up!!!
Super duper work you are doing !!
Thank you Mohan. I appreciate it.
Excellent!! This is all i needed, thanks!
You're welcome Rosmery. Good luck with your dashboards 👍🏼
Big help for me in making my graphs interactive as I'm analyzing student data for some research I'm doing. Hopefully I'll continue learning enough about dash so that I can move away from using Google Data Studio for public facing dashboards as well. You've helped open new doors...
Thanks for watching @Robert. I'm glad you're learning a lot.
Great explanation indeed!!
Thank you!
thank you for this valuable instruction
Thank you so much!! You are perfect teacher
Thank you
Great Video , Thank you :)
It's very helping me a lot, thanks so much,
Hi, I'm Japanese.
I study Python & Dash now. I'm not good at English. But I can understand becouse your exploration is very easy to grasp.
Thank you so much.
You are welcome @夢追人. I'm happy you like my tutorials. Thank you for watching.
Great Video!
thank you very much for your kindness teaching the dash
gonna cry T_T
Phenomenal video! Learnt a lot. Thank you
You're welcome, @Ajay. If you'd like to support me in creatimg more phenomenal video tutorials, it's just a couple of coffee cups a month 🤗
I'd love to have you be part of the charming data community.
www.patreon.com/charmingdata
Thank you, and I hope you enjoy the other tutorials as well.
Thank you so much.
Thank you very much
This is gold!
You are amazing !!
helped a lot! thanks
Just subscribed to you. Your explanations are the best among all other videos. Just wanted to say one thing that dash_core_components package and dash_html_components are deprecated and so that imports to be replaced by from dash import html, dcc, Input, Output. right?
Amazing tutorial. Is there a way to have callbacks for dynamically created dropdowns? Think of a table, where a user can add rows via a button that contains dropdowns. I would like to register each value of a dropdown individually.
In dash table when front end page is rendered User can do filtering . I want to let my program know when a user performs filtering . How can I do that ?
Which property I should use?
Note - derived_virtual_data may not work as it provides data even filter is not applied
Enjoyed your Callback tutorial.
The structure of the code appears to have a nice pattern that is rather appealing. Great instruction.
I also liked the video on loading to the Postgres DB. I have a APP idea and would like to see its implementation using DASH. Can we discuss?
Hi Davis, I'm glad you found my tutorials useful, and thank you for watching. I actually offer video conference consultations to my Patreon Community, which is why it would be unfair to offer consultations to anyone. Here's a link to become a Patreon: www.patreon.com/charmingdata
If that is not a possibility and you prefer sending me your idea, thoughts, or questions via email, I'll make sure to find the time to help you.
Sincerely,
Adam
Excelente 3:23, 4:50 inicia callbacks
Thank you, sir. A bit verbose, but very very useful
How to filter the dash table data using the dropdowns?
hi, I am a bit confused about line 45 to 47 in your example. You said whatever returned in the function below the @call_back has to have the same properties as the output. The fig variable in the function update_my_graph is a px piechart, how is that a dictionary. I think I misunderstood your tutorial. Any further support in the reply will be truly appreciated.
Really appreciate your help understand this! If only one Output can update a component, how do you implement a Status bar with Dash were several different buttons (i.e functions of the page) need to update one component. Also a calculator example. How does each number button update a display if the display can only be served by one of them?
Great question Peter. Not everyone thinks of that challenge right after learning about the callback 👍. You can use the dash.callback_context
. See here:
dash.plotly.com/advanced-callbacks
REALLY good video. Thanks! Do you have a video on having multiple callback functions by the way?
Hi Leandre. I honestly can't remember if I made that video. I suggest reviewing my video lists to look for it
Can we populate the dropdown in the callback?
What should I do if a callback isn't getting triggered and I have no idea why? Can this be debugged in a way?
Genius
Hi
I have a doubt on adding the label values in barchart and want to display on the top of the each bar .
Thanks on Advance
Hi Aravinda, this link might help you: plotly.com/python/text-and-annotations/
or this:
plotly.com/python/bar-charts/#bar-chart-with-direct-labels
Hi Adam,
Thank you for all the help you have given to the community so far.
I created an application that runs heavy simulations and shares graphics. I dockerized the application, and run the container. The container memory usage increases for each new tab of my application. However, if I close the tab, the memory usage does not decrease. I have not found any resources about this issue. Does anyone know how to handle the tab/window closing event and how to cut the process?
I'm not sure Benjamin. Sorry. If anybody knows, please share with Benjamin
Great video! Just wondering do you have videos about updating PostgreSQL database using datatables in dash ?
no, but I'd like to make one
May I ask which button did you pressed to get chosen rows to have # before them? It is in minute 17:05. Thank you :)
hi Xuan, thanks for watching. Yes, on my windows PC laptop I pressed Ctrl+?
I'm finding it difficult to use the callback function to display my scraping code (BS4) in a Tabular format.
Abhinav, you would need to use Dash DataTable to display your code in a Tabular format. But if you're new to Dash I would recommend you use regular html.Table() for that. Here's an example:
github.com/Coding-with-Adam/Dash-by-Plotly/blob/master/Dash_More_Advanced_Shit/API/weather/weather_api.py
This is from my weather API tutorial
I was wondering is there any way you could show graphs or keep the visibility hidden unless you select input from the dropdown.
Hi @Mahadi, Try to remove the dcc.Graph(id='graph-output', figure={}), from the latyout section. And include it in line 47 like this:
dcc.Graph(id='graph-output', figure=fig),
Hey, another great video! how to access the properties of components by id? can i do something like document.getElementById().someproperty="" kind of javascript in Dash?
Hi Eshwar, can you give me an exmple of a property you'd like to access?
If you want to access the style property of the dropdown, you can do that within the callback like this:
@app.callback(Output('dropdown-id', 'style'))
Hey Adam, is there a space where we can share and discuss our dash plotly codes with you if we are stuck somewhere?
Hi @Siddharth, i offer very low consultation price for my supporters on CZcams or Patreon. In case you're interested: www.patreon.com/charmingdata
Why do not use original df?
Could you pls advise why would a callback be triggered only once? btw I'm using the same element as output and input and calling callback in API call. Thanks in advance!
Hi Samira , what do you mean? A callback triggers multiple times
Do you know where can I found information about the options for the inputs component property??? Thanks 😁😁
the options for the input component properties are any properties that exist for each component. For example, the radioitems component has many properties you can find here: dash.plotly.com/dash-core-components/radioitems#radioitems-properties
How to get current data points of animation line graph using dbc.Graph id as input whenever a button is clicked?
Hi @Harsh, try the "clickData" prop of dcc.Graph.
@@CharmingData Thank you, that worked. Is there any way we can plot animated race line chart using go.Scatter but not with its "button" attribute which is in "updatemenu" but rather it should start plotting when we click button created using dbc.Button?
Amazing video!! Thanks a lot.i have a doubt/problem, is it possible to use a button inside a card to open a new tab?
Hi @Alba, it's possible and it will be easier with Dash 2.1 or 2.2, as we are working on it right now.
@@CharmingData Thank you! I am trying to do it but i don't know why the button opens another tab that i haven't create.
Great video! I have a question though. what to do if there is more than 1 input? Thanks in advance.
Hi Vishnu,
Then, you just add multiple arguments to the callback function
thanks for the video found the series really helpful however i was wondering if there was a video on multiple inputs/outputs along with a plotly graph, im struggling to get mine to work
thank you in advance!
Hi Abdul, I can't remember in which video I use multiple inputs/outputs, but look through this playlist. You should be able to find one.
czcams.com/play/PLh3I780jNsiSDHCReNVtgPC1WkqduZA5R.html
dont know if people still see comments on this video now, will post a question here though: I have a plot of polygons (made with plotly). I wanted to add a feature such that when I click on a particular polygon, a new scatter plot is created (preferably in the same window). Is there a way to implement this feature in Dash ?
Hi @additya. This is a very specific question. You'll probably have a better chance of finding an answer if you post this question on Plotly forum
I have been trying to return a bar graph developed on the selection of a transaction date in my dashboard.But the value 'figure' is not getting recognized.Could you please help me through
hi Sneha. What do you mean the value figure is not recognized. What's the error message?
@@CharmingData resolved aftr including layout property in my bar chart section.Thank you so much.How to set the edit theme button on the dashboard
This videos are cool. Is it possible to order the videos in stages from basics-----to advanced level? The current arrangement is in random order (sorry if I failed to observe this)
Hi @Getachew. I'll try to make a course this year that has a clear progression of videos to watch from start to end to make easy to learn.
@@CharmingData thanks for your help.
I am trying to create a dashboard where the datatable will be displayed based on the value of dropdown. Using callback I am trying to do that but somehow it's not displaying anything because the dataframe is not defined properly in the code. Can you help me to debug that?
Hi @sawon, I saw someone on Plotly Forum answered your question. Good idea posting your question there. Good luck.
@@CharmingData yeah thanks actually I was bit of clueless so I did that.
Fantastic job. I greatly appreciate your videos as I always learn something. Question for you:
How to tie a callback to the inital get-data function?
In all of your dashboards, you "hard code" a dataframe, meaning the data can't change.
How could one use a input box/callback to reperform the initial API call?
ex. API call
import yfinance as yf
## Initialize Dash
app = dash.Dash(__name__)
## Download & clean data
def update_data(symbol):
symbol='spy'
per='1y'
inter='2h'
sym = yf.Ticker(text)
data = sym.history(period=per, interval=inter)
return data
(yes i realize that the fx input is hardcoded into the function lol, just for reference.)
Hi, I would create an interval component that activates the callback through the input. The callback function will connect to the API and pull new data. And the function will return the new dataframe to the data prop of a store component.
You can then use that data throughput your app. See my latest video tutorial on sharing data between callbacks
Is there anyway to push the button to the centre of the page? Also can you share documentation to add background image to the entire page. Thank you. Love your videos.
Hi Mohammed, try watching my video on introduction to bootstrap or the recent one on introduce to layout. You'll see how to move things around.
@@CharmingData Thank you for replying.
Hey hi, i really liked the way your teaching... I have one question can you help me...
I need to create a submit button,reset button ,close with two inputs like name or anyother
When i press submit then it should open a dialogue box with some msg
When i press reset then the field should be clear
When i press close then the page should close...
Hi Lalitha, You should probably use Dash dynamic callbacks for that. See my tutorial here: czcams.com/video/4gDwKYaA6ww/video.html
@@CharmingData still i am not able to get it.... Can please provide aa code??
1. If i click on reset button then my input fields should be clear.(previous value be cleared )
2. If i click om close then the page should close .... It should not show any field and all
I had a doubt regarding a code I made... I don't know where I am going wrong and would like to send the whole code. Where do I contact you.
Adam@charming-data.com
Hi, These are fantastic tutorial. But that would be fantastic if you provide a playlist which will be easier to follow. Currently the playlist looks random.
Hi, i recommend checking out my patreon membership for more info on your question. Also, my playlists are pretty specific. If you don't did then helpful, I'm open to suggestions.
17:02
how did you commented out all the lines?
Cntrl+? On an English keyboard
Can I get this to work in Spyder?
Yes, @Chris. This should work on Spyder as well. There should be no issue there
¿Is there any way to use PreventUpdate with jupyther_Dash?
Hi Nicole, How are you?
Yes. First, at the beginning of the code:
from dash.exceptions import PreventUpdate
Thank, inside the callback just do:
raise PreventUpdate
@@CharmingData thanks :)
How do you send list as an output?
What do you mean @Kanishk?
You can return anything you want as an Ouput. Just return [ ]
@@CharmingData Actually I wanted to send back some data. I found that in dcc.Store(), we can send the output of type "data" which can be used in other elements
@@kanishkmair2920 good find. Yes, dcc.store is very useful. Have you built your app yet?
@@CharmingData not yet, it's in progress
@@kanishkmair2920 good luck
hi i have this in my layout:
html.Div(style={'display':'flex'},
children=[
html.Button('Ajouter champ',
id='add-fieldtest',
className='button',
style={'width':'250px'}),
html.Button('Retirer champ',
id='remove-fieldtest',
className='button',
style={'width':'250px'}),
html.Button('Recherche',
id='search-buttontest',
className='button',
style={'width':'250px'})
]),
and these two call backs:
@app.callback(
Output('new-form', 'children'),
[Input('remove-fieldtest', 'n_clicks'),
Input('add-fieldtest', 'n_clicks')],
State('new-form', 'children')
)
def add_removefield(rem_n_clicks, add_n_clicks, children):
ctx = dash.callback_context
if not ctx.triggered:
return children
else:
btn_clicked = ctx.triggered[0]['prop_id'].split('.')[0]
if btn_clicked == 'remove-fieldtest':
del children[-1]
return children
else:
return children + [replicable_div]
@app.callback(
Output('footer', 'children'),
[Input('search-buttontest', 'n_clicks')],
State('new-form', 'children')
)
def searchtest(n_clicks, children):
print(get_btn_clicked())
if n_clicks is not None:
q = ""
for i in range(1, len(children)):
v = ''
q = q + children[i]['props']['children'][1]['props']['value']
print(q)
return html.Div()
The callback searchtest is triggered even when i click on "remove-fieldtest" or "add-fieldtest" button, what is wrong ??
That is weird. Given that you have your buttons in separate callbacks, the searchtest callback function should not be triggered when clicking on the other buttons. It might be triggered once when the app first starts but not again, until you click on the search-buttontest button.
@@CharmingData Thank you for you answer, i finally figured it out. Do you see the add_removefield callback ? I has a children as an input, and returns the same children with new inputs field (or remove an input field). Well this output also contains a button which has a button, that's why it triggers another callback associated to the button in the children. It's a weird thing that callbacks are triggered when you return a button in a callback, i wish there was a way to prevent this.
@@fatalmokrane nice catch 🙅