The ring that dash_daq.Gauge outputs is too thin, as you can see from the picture below.
I would like to have thicker ring. I couldn’t find css element under ‘inspect element’ to increase the thickness of ring. How do i go about doing this?
Just create an assets folder and place there your css file e.g. "styles.css" and it works fine (Dash v1.6.0)
styles.css:
circle {
stroke-width: 20px;
}
app.py:
import dash
import dash_daq as daq
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash(__name__, assets_folder = 'assets', include_assets_files = True)
app.layout = html.Div([
daq.Gauge(
id='my-gauge',
label="Default",
value=6,
style={'display': 'block' }
),
dcc.Slider(
id='my-gauge-slider',
min=0,
max=10,
step=1,
value=5
),
])
#app.callback(
dash.dependencies.Output('my-gauge', 'value'),
[dash.dependencies.Input('my-gauge-slider', 'value')]
)
def update_output(value):
return value
if __name__ == '__main__':
app.run_server(debug=True)
gauge meter is made up of svg tag. To get an idea i will show the screen shot
Try changing the stroke-width attr value to change the thinkness. i hope this will help you to get inital idea.
Related
I created a huge Graphviz Network, which I now want to spice up with some interactivity. For this goal I discovered the package dash_interactive_graphviz. From my understanding I can simple provide my existing graph, but I'm already failing to execute the provided sample (see below):
import dash_interactive_graphviz
dot_source = """
digraph {
node[style="filled"]
a ->b->d
a->c->d
}
"""
dash_interactive_graphviz.DashInteractiveGraphviz(
id="graph",
dot_source=dot_source
)
The package itself and all requirements are fulfilled. I run the sample code from above in Visual Studio Code, but nothing happens (no output, no message, no error).
Anybody who can point me in the right direction? Thanks.
You are in the right direction, just need a few steps. I think you can check out this example here to run your file:
https://github.com/BusinessOptics/dash_interactive_graphviz/blob/master/usage.py
import dash_interactive_graphviz
import dash
from dash.dependencies import Input, Output
import dash_html_components as html
import dash_core_components as dcc
app = dash.Dash(__name__)
initial_dot_source = """
digraph {
node[style="filled"]
a ->b->d
a->c->d
}
"""
app.layout = html.Div(
[
html.Div(
dash_interactive_graphviz.DashInteractiveGraphviz(id="gv"),
style=dict(flexGrow=1, position="relative"),
),
html.Div(
[
html.H3("Selected element"),
html.Div(id="selected"),
html.H3("Dot Source"),
dcc.Textarea(
id="input",
value=initial_dot_source,
style=dict(flexGrow=1, position="relative"),
),
html.H3("Engine"),
dcc.Dropdown(
id="engine",
value="dot",
options=[
dict(label=engine, value=engine)
for engine in [
"dot",
"fdp",
"neato",
"circo",
"osage",
"patchwork",
"twopi",
]
],
),
],
style=dict(display="flex", flexDirection="column"),
),
],
style=dict(position="absolute", height="100%", width="100%", display="flex"),
)
#app.callback(
[Output("gv", "dot_source"), Output("gv", "engine")],
[Input("input", "value"), Input("engine", "value")],
)
def display_output(value, engine):
return value, engine
#app.callback(Output("selected", "children"), [Input("gv", "selected")])
def show_selected(value):
return html.Div(value)
if __name__ == "__main__":
app.run_server(debug=True)
I have a 2D plotly graph with a hover feature. When you hover over each point, the label (e.g. 'image 2, cluster 1') associated with that point appears. I'd like for label to be appended onto an existing list if I were to click on the point (rather than just hover over it). The reason why is that I'd later like to use the data of this point to perform another task. Is there an example online that demonstrates how to do this-- have looked through the documentation but haven't found something for this yet. Thanks!
The hoverData that is available to you by default, with some sample data, is this:
{
"points": [
{
"curveNumber": 1,
"pointNumber": 7,
"pointIndex": 7,
"x": 1987,
"y": 74.32,
"bbox": {
"x0": 420.25,
"x1": 426.25,
"y0": 256,
"y1": 262
}
}
]
}
I'm not quite sure what you mean by 'label', so I can only assume that it would be the name of a trace or something similar, like in this example from the Plotly docs:
But as you can see, that's not readily available in the hoverData dict. This means that you'll have to use this information to reference your figure structure as well, so that you end up with something like this:
[['New Zealand', 2002, 79.11]]
And that's not a problem as long as you're willing to use Plotly Dash. I've made a complete setup for you that should meet your requirements. In the app in the image below you'll find a figure along with two output fields for strings. The first field shows the info from that last point you've clicked in the figure. On every click, a new element is added to a list named store. The last fields shows the complete information from the same click.
The answer to your question is, yes, there is a way to save the data of a clicked point in a list. And one way to do so is through the following callback that uses clickdata to reference your figure object, store those references in a list, and append new elements every time you click a new element.
App
Complete code:
import json
from textwrap import dedent as d
import pandas as pd
import plotly.graph_objects as go
import numpy as np
import dash
from dash import dcc
import dash_html_components as html
import plotly.express as px
from dash.dependencies import Input, Output
from jupyter_dash import JupyterDash
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
# app info
app = JupyterDash(__name__)
styles = {
'pre': {
'border': 'thin lightgrey solid',
'overflowX': 'scroll'
}
}
# data
df = px.data.gapminder().query("continent=='Oceania'")
# plotly figure
fig = px.line(df, x="year", y="lifeExp", color="country", title="No label selected")
fig.update_traces(mode="markers+lines")
app.layout = html.Div([
dcc.Graph(
id='figure1',
figure=fig,
),
html.Div(className
='row', children=[
html.Div([
dcc.Markdown(d("""Hoverdata using figure references""")),
html.Pre(id='hoverdata2', style=styles['pre']),
], className='three columns'),
html.Div([
dcc.Markdown(d("""
Full hoverdata
""")),
html.Pre(id='hoverdata1', style=styles['pre']),
], className='three columns')
]),
])
# container for clicked points in callbacks
store = []
#app.callback(
Output('figure1', 'figure'),
Output('hoverdata1', 'children'),
Output('hoverdata2', 'children'),
[Input('figure1', 'clickData')])
def display_hover_data(hoverData):
if hoverData is not None:
traceref = hoverData['points'][0]['curveNumber']
pointref = hoverData['points'][0]['pointNumber']
store.append([fig.data[traceref]['name'],
fig.data[traceref]['x'][pointref],
fig.data[traceref]['y'][pointref]])
fig.update_layout(title = 'Last label was ' + fig.data[traceref]['name'])
return fig, json.dumps(hoverData, indent=2), str(store)
else:
return fig, 'None selected', 'None selected'
app.run_server(mode='external', port = 7077, dev_tools_ui=True,
dev_tools_hot_reload =True, threaded=True)
You need to use callbacks to perform this type of action (register on_click()). Have defined clicked as a list of clicked points. Demonstrated how this can be achieved with ipwidgets or dash
ipwidgets
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import ipywidgets as widgets
from pathlib import Path
import json
x = np.random.uniform(-10, 10, size=50)
y = np.sin(x)
clicked = []
# construct figure that has holders for points, interpolated line and final lines
fig = go.FigureWidget(
[
go.Scatter(x=x, y=y, mode="markers", name="base_points"),
]
)
fig.update_layout(template="simple_white")
out = widgets.Output(layout={"border": "1px solid black"})
out.append_stdout("Output appended with append_stdout\n")
# create our callback function
#out.capture()
def base_click(trace, points, selector):
global clicked
clicked.append(points.__dict__)
fig.data[0].on_click(base_click)
widgets.HBox([fig, out])
dash
from jupyter_dash import JupyterDash
import dash
from dash.dependencies import Input, Output, State
import numpy as np
import json
clicked = []
# Build App
app = JupyterDash(__name__)
app.layout = dash.html.Div(
[
dash.dcc.Graph(
id="fig",
figure=go.Figure(go.Scatter(x=x, y=y, mode="markers", name="base_points")),
),
dash.html.Div(id="debug"),
]
)
#app.callback(
Output("debug", "children"),
Input("fig", "clickData"),
)
def point_clicked(clickData):
global clicked
clicked.append(clickData)
return json.dumps(clickData)
# Run app and display result inline in the notebook
app.run_server(mode="inline")
I have a map created using Folium saved as an HTML file. It contains a few markers.
Now I would like to insert this map as an IFrame element in my Plotly-Dash layout. I managed to do that using:
app.layout = html.Div(children=[
html.Iframe(id='map', srcDoc=open('index.html', 'r').read())
], style={'padding': 10, 'flex': 1})
but the markers don't appear when embedded in the Dash layout. Why are they not appearing in Dash?
An alternative to Folium is dash-leaflet. While both components are leaflet-based, dash-leaflet provides tighter integration with Dash. Here is a small example with a few markers,
import dash_html_components as html
import dash_leaflet as dl
from dash import Dash
# A few cities in Denmark.
cities = [dict(title="Aalborg", position=[57.0268172, 9.837735]),
dict(title="Aarhus", position=[56.1780842, 10.1119354]),
dict(title="Copenhagen", position=[55.6712474, 12.5237848])]
# Create example app.
app = Dash()
app.layout = html.Div([
dl.Map(children=[dl.TileLayer()] + [dl.Marker(**city) for city in cities],
style={'width': '100%', 'height': '50vh', 'margin': "auto", "display": "block"}, id="map"),
])
if __name__ == '__main__':
app.run_server()
You can see a lot more examples in the documentation.
When a dash app is started, all callbacks should be fired according to the dash documentation. But when callbacks are linked (ones output is the other ones input) the initial callback of the latter is prevented when the first raises a dash.exceptions.PreventUpdate or returns a dash.no_update.
Although I can somehow follow that logic, it was not clear for me that this would happen, and I am interested in reading somewhere the reasons behind this, although I have no idea where.
More practical, I would like to fire the initial callback nevertheless, is this possible? The code below is a minimal example of the problem:
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import plotly.graph_objects as go
import numpy as np
from time import sleep
app = dash.Dash(__name__)
app.layout = html.Div([
html.Button('test', id='button'),
dcc.Dropdown(id='super', options=[{'label':x, 'value':x} for x in ['test1', 'test2']]),
dcc.Dropdown(id='under', options=[{'label':x, 'value':x} for x in ['under1', 'under2']]),
dcc.Graph(id='graph'),
])
#app.callback(
Output('super', 'value'),
Input('button', 'n_clicks'),
prevent_initiall_call=True
)
def set_super_value(nclicks):
if nclicks is None:
return dash.no_update
return 'test2'
#app.callback(
Output('under', 'value'),
Input('super', 'value')
)
def set_under_value(val):
sleep(5)
return 'under1'
#app.callback(
Output('graph', 'figure'),
Input('under', 'value'),
)
def make_figure(val):
sleep(5)
if val == 'under1':
return go.Figure(go.Scatter(x=np.arange(0,1000), y=np.sin(np.arange(0,1000)/100)))
else:
return go.Figure(go.Scatter(x=np.arange(0,1000), y=np.cos(np.arange(0,1000)/100)))
if __name__ == '__main__':
app.run_server(debug=True)
This is the initial state:
And this is how I would like it to be:
In this simple example I can always set this initial value as the 'value' option in the initial app.layout variable, but the problem in my actual application makes this a suboptimal solution in my eyes.
* Edits made to the code to make specify the problem a little more specific. Code still works and screenshots still apply (but
I want to change the language of dash's core components and the toolbar in plots (to german). I thought that defining external_scripts would be sufficient, but its still showing everything in english. Here is a minimal example of my code:
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
from datetime import datetime as dt
external_scripts = ["https://cdn.plot.ly/plotly-locale-de-latest.js"]
app = dash.Dash(__name__, external_scripts=external_scripts)
data_canada = px.data.gapminder().query("country == 'Canada'")
fig = px.bar(data_canada, x='year', y='pop')
app.layout = html.Div(children=[
html.H1(children='Dashboard'),
dcc.DatePickerRange(
id="date_range_picker",
min_date_allowed=dt(2018,1,1),
max_date_allowed=dt(2020,12,31),
display_format="MMM, YYYY"
),
dcc.Graph(
id='example-graph',
figure=fig
)
])
if __name__ == '__main__':
app.run_server(debug=True)
What else do I have to do to change the language?
You must add:
config_plots = dict(locale='de')
to:
dcc.Graph(
id='example-graph',
figure=fig,
config=config_plots
)