plotly-express-3-Dash_callback

2020-07-05  本文已影响0人  皮皮大

dash callbacks

The dash_html_components library provides classes for all of the HTML tags, and the keyword arguments describe the HTML attributes like style, className, and id.

The dash_core_components library generates higher-level components like controls and graphs.

第一个demo

代码示例

在使用回调函数的时候需要引入一个模块:

from dash.dependencies import Input, Output
image.png image.png

代码解释
The “inputs” and “outputs” of our application interface are described declaratively through the app.callback decorator.

In Dash, the inputs and outputs of our application are simply the properties of a particular component. In this example, our input is the “value” property of the component that has the ID “my-id”. Our output is the “children” property of the component with the ID “my-div”.

Whenever an input property changes, the function that the callback decorator wraps will get called automatically. Dash provides the function with the new value of the input property as an input argument and Dash updates the property of the output component with whatever was returned by the function.

The component_id and component_property keywords are optional (there are only two arguments for each of those objects). I have included them here for clarity but I will omit them from here on out for brevity and readability.

Notice how we don’t set a value for the children property of the my-div component in the layout. When the Dash app starts, it automatically calls all of the callbacks with the initial values of the input components in order to populate the initial state of the output components. In this example, if you specified something like html.Div(id='my-div', children='Hello world'), it would get overwritten when the app starts.

第二个demo

另一个例子:通过dcc.Silder来更新dcc.Graph,将滑动条和图形相结合的例子

image.png image.png

代码解释

  1. the "value" property of the Slider is the input of the app and the output of the app is the "figure" property of the Graph.
  1. Whenever the value of the Slider changes, Dash calls the callback function update_figure with the new value. The function filters the dataframe with this new value, constructs a figure object, and returns it to the Dash application.
  1. We load our dataframe at the start of the app: df = pd.read_csv('...'). This dataframe df is in the global state of the app and can be read inside the callback functions.
  1. The callback does not modify the original data, it just creates copies of the dataframe by filtering through pandas filters. This is important: your callbacks should never mutate variables outside of their scope.
  1. We are turning on transitions with layout.transition to give an idea of how the dataset evolves with time: transitions allow the chart to update from one state to the next smoothly, as if it were animated.

可视化效果

image.png
上一篇 下一篇

猜你喜欢

热点阅读