Here's a basic setup:
dcc.Checklist(
id = "display_columns",
options = [{
"label": col + ' ',
"value": col
}
for col in df.columns
],
value = [df.columns[0]],
labelStyle = {
'display': 'inline-block',
'width': '12em',
'line-height': '0.5em'
}
Along with, among other things, the following few lines, the dcc.Checklist()
component will let you turn the Prediction
trace on and off as you please.
# main trace y = 'Prices' fig = make_subplots(specs = [ [{ "secondary_y": True }] ]) if 'Prices' in display_columns: fig.add_trace(go.Scatter(name = y, x = df.index, y = df[y], mode = 'lines'), secondary_y = False) # prediction trace if 'Predicted_prices' in display_columns: fig.add_trace(go.Scatter(name = 'predictions', x = df.index, y = df['Predicted_prices'], mode = 'lines'), secondary_y = False
Everywhere in this page that you see fig.show(), you can display the same figure in a Dash application by passing it to the figure argument of the Graph component from the built-in dash_core_components package like this:,Click Events With FigureWidget ,Plotly is a free and open-source graphing library for Python. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.,Dash is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.
import plotly.graph_objects as go import numpy as np np.random.seed(1) x = np.random.rand(100) y = np.random.rand(100) f = go.FigureWidget([go.Scatter(x = x, y = y, mode = 'markers')]) scatter = f.data[0] colors = ['#a3a7e4'] * 100 scatter.marker.color = colors scatter.marker.size = [10] * 100 f.layout.hovermode = 'closest' # create our callback function def update_point(trace, points, selector): c = list(scatter.marker.color) s = list(scatter.marker.size) for i in points.point_inds: c[i] = '#bae2be' s[i] = 20 with f.batch_update(): scatter.marker.color = c scatter.marker.size = s scatter.on_click(update_point) f
import plotly.graph_objects as go
f = go.FigureWidget([go.Scatter()])
help(f.data[0].on_click)
Help on method on_click in module plotly.basedatatypes: on_click(callback, append = False) method of plotly.graph_objs._scatter.Scatter instance Register function to be called when the user clicks on one or more points in this trace. Note: Callbacks will only be triggered when the trace belongs to a instance of plotly.graph_objs.FigureWidget and it is displayed in an ipywidget context.Callbacks will not be triggered on figures that are displayed using plot / iplot. Parameters -- -- -- -- -- callback Callable function that accepts 3 arguments - this trace - plotly.callbacks.Points object - plotly.callbacks.InputDeviceState object append: bool If False(the default), this callback replaces any previously defined on_click callbacks for this trace.If True, this callback is appended to the list of any previously defined callbacks. Returns -- -- -- - None Examples -- -- -- -- >>> import plotly.graph_objects as go >>> from plotly.callbacks import Points, InputDeviceState >>> points, state = Points(), InputDeviceState() >>> def click_fn(trace, points, state): ...inds = points.point_inds ...# Do something >>> trace = go.Scatter(x = [1, 2], y = [3, 0]) >>> trace.on_click(click_fn) Note: The creation of the `points` and `state` objects is optional, it 's simply a convenience to help the text editor perform completion on the arguments inside `click_fn`
import plotly.graph_objects as go # or plotly.express as px fig = go.Figure() # or any Plotly Express function e.g.px.bar(...) # fig.add_trace(...) # fig.update_layout(...) import dash import dash_core_components as dcc import dash_html_components as html app = dash.Dash() app.layout = html.Div([ dcc.Graph(figure = fig) ]) app.run_server(debug = True, use_reloader = False) # Turn off reloader if inside Jupyter
If I understand correctly, you do not want the graph to refresh if the user selects a new start_date or end_date on the date picker, but only when he clicks the button, correct?,I have a dash DatePickerRange component and a refresh button in my dash app. I want the graphs to be updated as per the new dates from the DatePickerRange input only after the user clicks the refresh button. I wrote a callback function for this which takes the start_date, end_date from the DateRangePicker as Input and also the n_clicks from the refresh button.,Now, changes to start_date or end_date won’t trigger your callback, only clicks on the refresh button will.,This works fine when the app is loaded for the first time and the graph isn’t updated until the n_clicks value changes from None. But after that the graphs are updated continuously whenever the dates inputs are changed which makes sense as the n_clicks are not None now. Is it possible to save the last value of the n_clicks and update the graph only after the last value is changed.
Code:
@app.callback(
Output(component_id = 'newusers bar graph', component_property = 'figure'),
Input(component_id = 'date picker', component_property = 'start_date'),
Input(component_id = 'date picker', component_property = 'end_date'),
Input(component_id = 'refresh button', component_property = 'n_clicks')
)
def update_graph(start_date, end_date, n):
if n is None:
return dash.no_update
else:
return bar_graph(start_date, end_date)
If so, use a State instead of an Input for the date picker. Your callback would then start like this (you may need to import State from dash.dependencies):
@app.callback(
Output(component_id = 'newusers bar graph', component_property = 'figure'),
Input(component_id = 'refresh button', component_property = 'n_clicks'),
State(component_id = 'date picker', component_property = 'start_date'),
State(component_id = 'date picker', component_property = 'end_date'),
)
def update_graph(n, start_date, end_date):
As mentioned above, value of type key in Updatemenu() method is assigned dropdown to display dropdown list of buttons. The plot appears as below −,Click on Violin button to display corresponding Violin plot.,Value of type property is buttons by default. To render a dropdown list of buttons, change type to dropdown. A Box trace added to Figure object before updating its layout as above. The complete code that renders boxplot and violin plot depending on button clicked, is as follows −,Plotly provides high degree of interactivity by use of different controls on the plotting area – such as buttons, dropdowns and sliders etc. These controls are incorporated with updatemenu attribute of the plot layout. You can add button and its behaviour by specifying the method to be called.
The restyle method should be used when modifying the data and data attributes of the graph. In the following example, two buttons are added by Updatemenu() method to the layout with restyle method.
go.layout.Updatemenu(
type = "buttons",
direction = "left",
buttons = list([
dict(args = ["type", "box"], label = "Box", method = "restyle"),
dict(args = ["type", "violin"], label = "Violin", method = "restyle")
]))
Value of type property is buttons by default. To render a dropdown list of buttons, change type to dropdown. A Box trace added to Figure object before updating its layout as above. The complete code that renders boxplot and violin plot depending on button clicked, is as follows −
import plotly.graph_objs as go
fig = go.Figure()
fig.add_trace(go.Box(y = [1140, 1460, 489, 594, 502, 508, 370, 200]))
fig.layout.update(
updatemenus = [
go.layout.Updatemenu(
type = "buttons", direction = "left", buttons = list(
[
dict(args = ["type", "box"], label = "Box", method = "restyle"),
dict(args = ["type", "violin"], label = "Violin", method = "restyle")
]
),
pad = {
"r": 2,
"t": 2
},
showactive = True,
x = 0.11,
xanchor = "left",
y = 1.1,
yanchor = "top"
),
]
)
iplot(fig)
The update method should be used when modifying the data and layout sections of the graph. Following example demonstrates how to update and which traces are displayed while simultaneously updating layout attributes, such as, the chart title. Two Scatter traces corresponding to sine and cos wave are added to Figure object. The trace with visible attribute as True will be displayed on the plot and other traces will be hidden.
import numpy as np import math #needed for definition of pi xpoints = np.arange(0, math.pi * 2, 0.05) y1 = np.sin(xpoints) y2 = np.cos(xpoints) fig = go.Figure() # Add Traces fig.add_trace( go.Scatter( x = xpoints, y = y1, name = 'Sine' ) ) fig.add_trace( go.Scatter( x = xpoints, y = y2, name = 'cos' ) ) fig.layout.update( updatemenus = [ go.layout.Updatemenu( type = "buttons", direction = "right", active = 0, x = 0.1, y = 1.2, buttons = list( [ dict( label = "first", method = "update", args = [{ "visible": [True, False] }, { "title": "Sine" }] ), dict( label = "second", method = "update", args = [{ "visible": [False, True] }, { "title": Cos "}] )] ) ) ] ) iplot(fig)
In the following example, a scatter curve trace is first plotted. Then add frames which is a list of 50 Frame objects, each representing a red marker on the curve. Note that the args attribute of button is set to None, due to which all frames are animated.
import numpy as np
t = np.linspace(-1, 1, 100)
x = t + t ** 2
y = t - t ** 2
xm = np.min(x) - 1.5
xM = np.max(x) + 1.5
ym = np.min(y) - 1.5
yM = np.max(y) + 1.5
N = 50
s = np.linspace(-1, 1, N)
#s = np.arange(0, math.pi * 2, 0.1)
xx = s + s ** 2
yy = s - s ** 2
fig = go.Figure(
data = [
go.Scatter(x = x, y = y, mode = "lines", line = dict(width = 2, color = "blue")),
go.Scatter(x = x, y = y, mode = "lines", line = dict(width = 2, color = "blue"))
],
layout = go.Layout(
xaxis = dict(range = [xm, xM], autorange = False, zeroline = False),
yaxis = dict(range = [ym, yM], autorange = False, zeroline = False),
title_text = "Moving marker on curve",
updatemenus = [
dict(type = "buttons", buttons = [dict(label = "Play", method = "animate", args = [None])])
]
),
frames = [go.Frame(
data = [
go.Scatter(
x = [xx[k]], y = [yy[k]], mode = "markers", marker = dict(
color = "red", size = 10
)
)
]
)
for k in range(N)
]
)
iplot(fig)