import dash_html_components as html import dash_core_components as dcc from dash.dependencies import Input, Output import pandas as pd from components.builder import ComponentBuilder from screens.bolgeler.get_screen import get_layout as bolgeler_layout from screens.bolgeler.get_callbacks import get_callbacks as bolgeler_callbacks from screens.kategoriler.get_screen import get_layout as kategoriler_layout from screens.kategoriler.get_callbacks import get_callbacks as kategoriler_callbacks DF = pd.read_csv('Sample_Market_Sales.csv', low_memory=False) component_builder = ComponentBuilder() app = Dash(__name__, external_stylesheets=component_builder.EXTERNAL_STYLESHEETS, meta_tags=component_builder.META_TAGS ) app = bolgeler_callbacks(app, DF) app = kategoriler_callbacks(app, DF) TABS = component_builder.get_tabs( tab_items={ 'Bölgeler': 'bolgeler', 'Kategoriler': 'kategoriler' } ) app.layout = html.Div( className=component_builder.LAYOUT_CLASSNAME, children=[ dcc.Location(id="url"),
class DualDashGraph: """ The DualDashGraph class is the inerface for comparing and highlighting the difference between two graphs. Two Graph class objects should be supplied - such as MST and ALMST graphs. """ def __init__(self, graph_one, graph_two, app_display='default'): """ Initialises the dual graph interface and generates the interface layout. :param graph_one: (Graph) The first graph for the comparison interface. :param graph_two: (Graph) The second graph for the comparison interface. :param app_display: (str) 'default' by default and 'jupyter notebook' for running Dash inside Jupyter Notebook. """ # Dash app styling with Bootstrap if app_display == 'jupyter notebook': self.app = JupyterDash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) else: self.app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) # Setting input graphs as objest variables cyto.load_extra_layouts() self.graph_one = graph_one self.graph_two = graph_two # Getting a list of tuples with differnet edge connections difference = graph_one.get_difference(graph_two) # Updating the elements needed for the Dash Cytoscape Graph object self.one_components = None self.two_components = None self._update_elements_dual(self.graph_one, difference, 1) self._update_elements_dual(self.graph_two, difference, 2) self.cyto_one = None self.cyto_two = None # Callback functions to allow simultaneous node selection when clicked self.app.callback(Output('cytoscape_two', 'elements'), [Input('cytoscape', 'tapNode')], [State('cytoscape_two', 'elements')])( DualDashGraph._select_other_graph_node) self.app.callback(Output('cytoscape', 'elements'), [Input('cytoscape_two', 'tapNode')], [State('cytoscape', 'elements')])( DualDashGraph._select_other_graph_node) @staticmethod def _select_other_graph_node(data, elements): """ Callback function to select the other graph node when a graph node is selected by setting selected to True. :param data: (Dict) Dictionary of "tapped" or selected node. :param elements: (Dict) Dictionary of elements. :return: (Dict) Returns updates dictionary of elements. """ if data: for element in elements: element['selected'] = ( data['data']['id'] == element.get('data').get('id')) return elements def _generate_comparison_layout(self, graph_one, graph_two): """ Returns and generates a dual comparison layout. :param graph_one: (Graph) The first graph object for the dual interface. :param graph_two: (Graph) Comparison graph object for the dual interface. :return: (html.Div) Returns a Div containing the interface. """ # Set Graph names graph_one_name = type(graph_one).__name__ graph_two_name = type(graph_two).__name__ # Set the cyto graphs self._set_cyto_graph() # Get different edges between two graphs difference = graph_one.get_difference(graph_two) # Layout components padding = {'padding': '10px 10px 10px 10px'} cards = dbc.CardDeck([ dbc.Card([ dbc.CardHeader(graph_one_name), dbc.CardBody(self.cyto_one), ], ), dbc.Card( [dbc.CardHeader(graph_two_name), dbc.CardBody(self.cyto_two)], ) ], style=padding) summary = dbc.Card([ html.H5("Summary", className="card-title"), html.P("{} nodes in each graph and {} different edge(s) per graph." .format(graph_one.get_graph().number_of_nodes(), int(len(difference) / 2)), className="card-text") ], className="w-50", style={ 'margin': '0 auto', 'padding': '10px 10px 10px 10px' }) layout = html.Div([ dbc.Row(dbc.Col(cards, width=12, align='center')), summary, ], style={'padding-bottom': '10px'}) return layout @staticmethod def _get_default_stylesheet(weights): """ Returns the default stylesheet for initialisation. :param weights: (List) A list of weights of the edges. :return: (List) A List of definitions used for Dash styling. """ stylesheet = \ [ { 'selector': 'node', 'style': { 'label': 'data(label)', 'text-valign': 'center', 'background-color': '#4cc9f0', 'font-family': 'sans-serif', 'font-size': '12', 'font-weight': 'bold', 'border-width': 1.5, 'border-color': '#161615', } }, { "selector": 'edge', "style": { 'label': 'data(weight)', "line-color": "#4cc9f0", 'font-size': '8', } }, { "selector": '[weight => 0]', "style": { "width": "mapData(weight, 0, {}, 1, 8)".format(max(weights)), } }, { "selector": '[weight < 0]', "style": { "width": "mapData(weight, 0, {}, 1, 8)".format(min(weights)), } }, { "selector": '.central', "style": { "background-color": "#80b918" } }, { 'selector': ':selected', "style": { "border-width": 2, 'background-color': '#f72585', "border-color": "black", "border-opacity": 1, "opacity": 1, "label": "data(label)", "color": "black", "font-size": 12, 'z-index': 9999 } }, { "selector": '.different', "style": { "line-color": "#f72585", } } ] return stylesheet def _set_cyto_graph(self): """ Updates and sets the two cytoscape graphs using the corresponding components. """ layout = {'name': 'cose-bilkent'} style = { 'width': '100%', 'height': '600px', 'padding': '5px 3px 5px 3px' } self.cyto_one = cyto.Cytoscape( id="cytoscape", layout=layout, style=style, elements=self.one_components[1], stylesheet=DualDashGraph._get_default_stylesheet( self.one_components[0])) self.cyto_two = cyto.Cytoscape( id="cytoscape_two", layout=layout, style=style, elements=self.two_components[1], stylesheet=DualDashGraph._get_default_stylesheet( self.two_components[0])) def _update_elements_dual(self, graph, difference, graph_number): """ Updates the elements needed for the Dash Cytoscape Graph object. :param graph: (Graph) Graph object such as MST or ALMST. :param difference: (List) List of edges where the two graphs differ. :param graph_number: (Int) Graph number to update the correct graph. """ weights = [] elements = [] for node in graph.get_pos(): # If a node is "central", add the central label as a class if graph.get_graph().degree(node) >= 5: elements.append({ 'data': { 'id': node, 'label': node }, 'selectable': 'true', 'classes': 'central' }) else: elements.append({ 'data': { 'id': node, 'label': node }, 'selectable': 'true', }) for node1, node2, weight in graph.get_graph().edges(data=True): element = { 'data': { 'source': node1, 'target': node2, 'weight': round(weight['weight'], 4) } } # If the edge is a "different" edge, label with class "different" to highlight this edge if (node1, node2) in difference: element = { 'data': { 'source': node1, 'target': node2, 'weight': round(weight['weight'], 4) }, 'classes': 'different' } weights.append(round(weight['weight'], 4)) elements.append(element) # Update correct graph components if graph_number == 1: self.one_components = (weights, elements) if graph_number == 2: self.two_components = (weights, elements) def get_server(self): """ Returns the comparison interface server :return: (Dash) Returns the Dash app object, which can be run using run_server. Returns a Jupyter Dash object if DashGraph has been initialised for Jupyter Notebook. """ # Create an app from a comparison layout self.app.layout = self._generate_comparison_layout( self.graph_one, self.graph_two) # Return the app return self.app
def test_ttbs001_canonical_behavior(dash_dcc): lock = Lock() loading_text = "Waiting for Godot" fig = dict( data=[ dict(x=[11, 22, 33], y=[333, 222, 111], mode="markers", marker=dict(size=40)) ], layout=dict(width=400, height=400, margin=dict(l=100, r=100, t=100, b=100)), ) app = Dash(__name__) app.layout = html.Div( className="container", children=[ dcc.Graph(id="graph", figure=fig, clear_on_unhover=True), dcc.Tooltip(id="graph-tooltip", loading_text=loading_text), ], style=dict(position="relative"), ) # This callback is executed very quickly app.clientside_callback( """ function show_tooltip(hoverData) { if(!hoverData) { return [false, dash_clientside.no_update]; } var pt = hoverData.points[0]; return [true, pt.bbox]; } """, Output("graph-tooltip", "show"), Output("graph-tooltip", "bbox"), Input("graph", "hoverData"), ) # This callback is executed after 1s to simulate a long-running process @app.callback( Output("graph-tooltip", "children"), Input("graph", "hoverData"), ) def update_tooltip_content(hoverData): if hoverData is None: return no_update with lock: # Display the x0 and y0 coordinate bbox = hoverData["points"][0]["bbox"] return [ html.P(f"x0={bbox['x0']}, y0={bbox['y0']}"), ] dash_dcc.start_server(app) until(lambda: not dash_dcc.find_element("#graph-tooltip").is_displayed(), 3) elem = dash_dcc.find_element("#graph .nsewdrag") with lock: # hover on the center of the graph ActionChains(dash_dcc.driver).move_to_element_with_offset( elem, elem.size["width"] / 2, elem.size["height"] / 2).click().perform() dash_dcc.wait_for_text_to_equal("#graph-tooltip", loading_text) dash_dcc.wait_for_contains_text("#graph-tooltip", "x0=") tt_text = dash_dcc.find_element("#graph-tooltip").text coords = [float(part.split("=")[1]) for part in tt_text.split(",")] assert 175 < coords[0] < 185, "x0 is about 200 minus half a marker size" assert 175 < coords[1] < 185, "y0 is about 200 minus half a marker size" ActionChains(dash_dcc.driver).move_to_element_with_offset(elem, 0, 0).perform() until(lambda: not dash_dcc.find_element("#graph-tooltip").is_displayed(), 3)
class DashGraph: """ This DashGraph class creates a server for Dash cytoscape visualisations. """ def __init__(self, input_graph, app_display='default'): """ Initialises the DashGraph object from the Graph class object. Dash creates a mini Flask server to visualise the graphs. :param app_display: (str) 'default' by default and 'jupyter notebook' for running Dash inside Jupyter Notebook. :param input_graph: (Graph) Graph class from graph.py. """ self.graph = None # Dash app styling with Bootstrap if app_display == 'jupyter notebook': self.app = JupyterDash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) else: self.app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) # Graph class object self.graph = input_graph # The dictionary of the nodes coordinates self.pos = self.graph.get_pos() # Colours of nodes self.colour_groups = {} # If colours have been assigned in Graph class, add styling if self.graph.get_node_colours(): colour_map = self.graph.get_node_colours() self._assign_colours_to_groups(list(colour_map.keys())) self.weights = [] self.elements = [] self._update_elements() # Load the different graph layouts cyto.load_extra_layouts() self.layout_options = ['cose-bilkent', 'cola', 'spread'] self.statistics = [ 'graph_summary', 'average_degree_connectivity', 'average_neighbor_degree', 'betweenness_centrality' ] # Load default stylesheet self.stylesheet = None self.stylesheet = self._get_default_stylesheet() # Append stylesheet for colour and size # If sizes have been set in the Graph class self._style_colours() if self.graph.get_node_sizes(): self._assign_sizes() self.cyto_graph = None # Callback functions to hook frontend elements to functions self.app.callback(Output('cytoscape', 'layout'), [Input('dropdown-layout', 'value')])( DashGraph._update_cytoscape_layout) self.app.callback(Output('json-output', 'children'), [Input('dropdown-stat', 'value')])( self._update_stat_json) self.app.callback(Output('cytoscape', 'elements'), [Input('rounding_decimals', 'value')])( self._round_decimals) def _set_cyto_graph(self): """ Sets the cytoscape graph elements. """ self.cyto_graph = cyto.Cytoscape( id="cytoscape", layout={'name': self.layout_options[0]}, style={ 'width': '100%', 'height': '600px', 'padding': '5px 3px 5px 3px' }, elements=self.elements, stylesheet=self.stylesheet) def _get_node_group(self, node_name): """ Returns the industry or sector name for a given node name. :param node_name: (str) Name of a given node in the graph. :return: (str) Name of industry that the node is in or "default" for nodes which haven't been assigned a group. """ node_colour_map = self.graph.get_node_colours() for key, val in node_colour_map.items(): if node_name in val: return key return "default" def _get_node_size(self, index): """ Returns the node size for given node index if the node sizes have been set. :param index: (int) The index of the node. :return: (float) Returns size of node set, 0 if it has not been set. """ if self.graph.get_node_sizes(): return self.graph.get_node_sizes()[index] return 0 def _update_elements(self, dps=4): """ Updates the elements needed for the Dash Cytoscape Graph object. :param dps: (int) Decimal places to round the edge values. """ i = 0 self.weights = [] self.elements = [] for node in self.pos: self.elements.append({ 'data': { 'id': node, 'label': node, 'colour_group': self._get_node_group(node), 'size': self._get_node_size(i) }, 'selectable': 'true', }) i += 1 for node1, node2, weight in self.graph.get_graph().edges(data=True): self.weights.append(round(weight['weight'], dps)) self.elements.append({ 'data': { 'source': node1, 'target': node2, 'weight': round(weight['weight'], dps) } }) def _generate_layout(self): """ Generates the layout for cytoscape. :return: (dbc.Container) Returns Dash Bootstrap Component Container containing the layout of UI. """ graph_type = type(self.graph).__name__ self._set_cyto_graph() layout_input = [ html.H1("{} from {} matrix".format(graph_type, self.graph.get_matrix_type())), html.Hr(), dbc.Row( [ dbc.Col(self._get_default_controls(), md=4), dbc.Col(self.cyto_graph, md=8), ], align="center", ) ] if self.colour_groups: layout_input.append(self._get_toast()) layout = dbc.Container( layout_input, fluid=True, ) return layout def _assign_colours_to_groups(self, groups): """ Assigns the colours to industry or sector groups by creating a dictionary of group name to colour. :param groups: (List) List of industry groups as strings. """ # List of colours selected to match with industry groups colours = [ "#d0b7d5", "#a0b3dc", "#90e190", "#9bd8de", "#eaa2a2", "#f6c384", "#dad4a2", '#ff52a8', '#ffd1e8', '#bd66ff', '#6666ff', '#66ffff', '#00e600', '#fff957', '#ffc966', '#ff8833', '#ff6666', '#C0C0C0', '#008080' ] # Random colours are generated if industry groups added exceeds 19 while len(groups) > len(colours): random_number = random.randint(0, 16777215) hex_number = str(hex(random_number)) hex_number = '#' + hex_number[2:] colours.append(hex_number) # Create and add to the colour map colour_map = {} for i, item in enumerate(groups): colour_map[item] = colours[i].capitalize() self.colour_groups = colour_map def _style_colours(self): """ Appends the colour styling to stylesheet for the different groups. """ if self.colour_groups: keys = list(self.colour_groups.keys()) for item in keys: new_colour = { "selector": "node[colour_group=\"{}\"]".format(item), "style": { 'background-color': '{}'.format(self.colour_groups[item]), } } self.stylesheet.append(new_colour) def _assign_sizes(self): """ Assigns the node sizing by appending to the stylesheet. """ sizes = self.graph.get_node_sizes() max_size = max(sizes) min_size = min(sizes) new_sizes = { 'selector': 'node', 'style': { "width": "mapData(size, {min}, {max}, 25, 250)".format(min=min_size, max=max_size), "height": "mapData(size, {min}, {max}, 25, 250)".format(min=min_size, max=max_size), } } self.stylesheet.append(new_sizes) def get_server(self): """ Returns a small Flask server. :return: (Dash) Returns the Dash app object, which can be run using run_server. Returns a Jupyter Dash object if DashGraph has been initialised for Jupyter Notebook. """ self.app.layout = self._generate_layout() return self.app @staticmethod def _update_cytoscape_layout(layout): """ Callback function for updating the cytoscape layout. The useful layouts for MST have been included as options (cola, cose-bilkent, spread). :return: (Dict) Dictionary of the key 'name' to the desired layout (e.g. cola, spread). """ return {'name': layout} def _update_stat_json(self, stat_name): """ Callback function for updating the statistic shown. :param stat_name: (str) Name of the statistic to display (e.g. graph_summary). :return: (json) Json of the graph information depending on chosen statistic. """ switcher = { "graph_summary": self.get_graph_summary(), "average_degree_connectivity": nx.average_degree_connectivity(self.graph.get_graph()), "average_neighbor_degree": nx.average_neighbor_degree(self.graph.get_graph()), "betweenness_centrality": nx.betweenness_centrality(self.graph.get_graph()), } if type(self.graph).__name__ == "PMFG": switcher["disparity_measure"] = self.graph.get_disparity_measure() return json.dumps(switcher.get(stat_name), indent=2) def get_graph_summary(self): """ Returns the Graph Summary statistics. The following statistics are included - the number of nodes and edges, smallest and largest edge, average node connectivity, normalised tree length and the average shortest path. :return: (Dict) Dictionary of graph summary statistics. """ summary = { "nodes": len(self.pos), "edges": self.graph.get_graph().number_of_edges(), "smallest_edge": min(self.weights), "largest_edge": max(self.weights), "average_node_connectivity": nx.average_node_connectivity(self.graph.get_graph()), "normalised_tree_length": (sum(self.weights) / (len(self.weights))), "average_shortest_path": nx.average_shortest_path_length(self.graph.get_graph()) } return summary def _round_decimals(self, dps): """ Callback function for updating decimal places. Updates the elements to modify the rounding of edge values. :param dps: (int) Number of decimals places to round to. :return: (List) Returns the list of elements used to define graph. """ if dps: self._update_elements(dps) return self.elements def _get_default_stylesheet(self): """ Returns the default stylesheet for initialisation. :return: (List) A List of definitions used for Dash styling. """ stylesheet = \ [ { 'selector': 'node', 'style': { 'label': 'data(label)', 'text-valign': 'center', 'background-color': '#65afff', 'color': '', 'font-family': 'sans-serif', 'font-size': '12', 'font-weight': 'bold', 'border-width': 1.5, 'border-color': '#161615', } }, { "selector": 'edge', "style": { 'label': 'data(weight)', "line-color": "#a3d5ff", 'font-size': '8', } }, { "selector": '[weight => 0]', "style": { "width": "mapData(weight, 0, {}, 1, 8)".format(max(self.weights)), } }, { "selector": '[weight < 0]', "style": { "width": "mapData(weight, 0, {}, 1, 8)".format(min(self.weights)), } } ] return stylesheet def _get_toast(self): """ Toast is the floating colour legend to display when industry groups have been added. This method returns the toast component with the styled colour legend. :return: (html.Div) Returns Div containing colour legend. """ list_elements = [] for industry, colour in self.colour_groups.items(): span_styling = \ { "border": "1px solid #ccc", "background-color": colour, "float": "left", "width": "12px", "height": "12px", "margin-right": "5px" } children = [industry.title(), html.Span(style=span_styling)] list_elements.append(html.Li(children)) toast = html.Div([ dbc.Toast( html.Ul(list_elements, style={ "list-style": "None", "padding-left": 0 }), id="positioned-toast", header="Industry Groups", dismissable=True, # stuck on bottom right corner style={ "position": "fixed", "bottom": 36, "right": 10, "width": 350 }, ), ]) return toast def _get_default_controls(self): """ Returns the default controls for initialisation. :return: (dbc.Card) Dash Bootstrap Component Card which defines the side panel. """ controls = dbc.Card( [ html.Div([ dbc.FormGroup([ dbc.Label("Graph Layout"), dcc.Dropdown( id="dropdown-layout", options=[{ "label": col, "value": col } for col in self.layout_options], value=self.layout_options[0], clearable=False, ), ]), dbc.FormGroup([ dbc.Label("Statistic Type"), dcc.Dropdown( id="dropdown-stat", options=[{ "label": col, "value": col } for col in self.statistics], value="graph_summary", clearable=False, ), ]), html.Pre(id='json-output', style={ 'overflow-y': 'scroll', 'height': '100px', 'border': 'thin lightgrey solid' }), dbc.FormGroup([ dbc.Label("Decimal Places"), dbc.Input(id="rounding_decimals", type="number", value=4, min=1), ]), ]), dbc.CardBody(html.Div(id="card-content", className="card-text")), ], body=True, ) return controls
import dash import dash_core_components as dcc import dash_html_components as html from dash import Dash from dash.dependencies import Input, Output from sklearn import datasets from sklearn.cluster import KMeans import numpy as np import pandas as pd import plotly.plotly as py from plotly.graph_objs import * app = Dash(__name__) server = app.server app.title = 'Iris Data Dashboard' # do all the machine learning iris = datasets.load_iris() colors = ["#E41A1C", "#377EB8", "#4DAF4A", \ "#984EA3", "#FF7F00", "#FFFF33", \ "#A65628", "#F781BF", "#999999"] number_of_clusters = range(6) df = pd.DataFrame(iris.data, columns=iris.feature_names) df['target'] = iris.target col = [ 'sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)'
from dash import Dash from dash.components import * from userguide import app, const dash = Dash(server=app, url_namespace='/{}'.format(const['dash.react'])) dash.layout = div([ h2('making dash apps interactive'), h4('binding python callbacks to user inputs'), div([ p([ 'Some ', code('dash.components'), ' objects respond to user input. ', 'Dash provides a callback API to bind custom interactivity to ', 'these changes in user input. ' 'This is exposed as a function decorator: ', code('dash.react(id_of_component_to_update, list_of_component_ids_to_respond_to)'), '. ', p(["Let's look at a simple example. ", 'When you update the user dropdown, the ', code('<pre id="display-dropdown-value"></pre>'), ' on the page updates with the value of the selected item.']) ]), hr() ]), div([ div([ Highlight(id='layout-1', style={'overflowY': 'scroll'}, className="python") ], className="eight columns",
# For scaling realized_vol volatility later import math # external CSS stylesheets external_stylesheets = [ 'https://codepen.io/chriddyp/pen/bWLwgP.css', { 'href': 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css', 'rel': 'stylesheet', 'integrity': 'sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO', 'crossorigin': 'anonymous' } ] app_une = Dash('USStateUnemployment', external_stylesheets=external_stylesheets) # Get a list of all US states # Get the FRED ticker for unemployment rate in each us_states = [ "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DC", "DE", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY" ] us_states_fred = [x + 'UR' for x in us_states] # Either set API keys as an environment variable (preferred for security reasons) # or replace these below, with your own keys (I can give you a FRED key because it's by application)
# style_table={'maxWidth': '230px','backgroundColor':'black','tableAlign':'center'}, # selected_rows=[0], # style_cell = {"fontFamily": "Arial", "size": 10, 'textAlign': 'center','fill_color':'lavender'}) # #dcc.Graph(figure=fig5) # ] # ), # ] # fig9 = go.Figure(data=[go.Table(header=dict(values=['State','Total Cases', 'Deaths', 'Active Cases'], # fill_color='lightgrey',font_size=20,height=50), # cells=dict(values=[df2["State"],df2["Total_confirmed_cases"],df2["Cured_Discharged_Migrated"],df2["Active_cases"]],height=50,font_size=18)) # ,'min_height':400]) server = flask.Flask(__name__) dash_app1 = Dash(__name__, server=server, url_base_pathname='/dashboard/', external_stylesheets=external_stylesheets) dash_app2 = Dash(__name__, server=server, url_base_pathname='/reports/') dash_app1.layout = html.Div( [ html.H1(children=html.Strong("India Covid-19 Updates"), style={ 'textAlign': 'center', 'color': 'black', 'font-family': 'Comic Sans MS', 'fontsize': '20px', 'backgroundColor': colors['area'], 'text-decoration': 'underline' }), html.Br(style={'backgroundColor': colors['area']}), html.Br(),
def init_dash(server): external_stylesheets = [dbc.themes.BOOTSTRAP] app = Dash('__main__', server=server, url_base_pathname='/data/', assets_folder='static', external_stylesheets=external_stylesheets) data = pd.read_csv('static/Sun.txt') df = data[data['ACCEPT'] == True] rv_figure = scatter(df, x="MJD", y="V") rv_figure.update_layout(clickmode='event') rand_x = np.random.randn(500) rand_y = np.random.randn(500) fig = scatter( x=rand_x, y=rand_y, ) app.layout = html.Div([ navbar, html.Br(className='pb-5'), dcc.Store(id='test', data=[{ 'x': df[['MJD']].to_json(), 'y': df[['V']].to_json() }]), html.Div(id='data', children=df.to_json(), className='d-none'), html.Div(id='json', ), dcc.Graph(id='rv-plot', figure=rv_figure, className="pt-5"), dcc.RangeSlider(id='range-slider', min=59000, max=59110, step=10, value=[59010, 59100]), html.Div([ dcc.Markdown(""" **Click Data** Click on points in the graph. """), html.Pre(id='click-data'), ]), html.Div([], id='spec-container'), html.Div([ dt.DataTable(id='rv-table', columns=[{ "name": i, "id": i } for i in df.columns][1::], data=df.to_dict('records')), ], className=''), html.Br(className='pb-5'), ]) app.clientside_callback( output=Output('click-data', 'children'), inputs=[Input('rv-plot', 'clickData'), State('rv-table', 'data')], clientside_function=ClientsideFunction(namespace='graphing', function_name='clickData')) app.clientside_callback( output=Output('rv-plot', 'figure'), inputs=[Input('range-slider', 'value'), State('data', 'children')], clientside_function=ClientsideFunction(namespace='graphing', function_name='zoomfunc')) # @app.callback( # Output('json', 'children'), # Input('rv-plot', 'figure') # ) # def teststuff(figure): # return dumps([fig], cls=plotly.utils.PlotlyJSONEncoder) @app.callback(Output('spec-container', 'children'), Input('click-data', 'children')) def getGraph(children): if (children == None): return return [ dcc.Graph(id='spec-plot', figure=rv_figure, className="pt-5"), children ]
def test_graph_does_not_resize_in_tabs(dash_dcc, is_eager): app = Dash(__name__, eager_loading=is_eager) app.layout = html.Div( [ html.H1("Dash Tabs component demo"), dcc.Tabs( id="tabs-example", value="tab-1-example", children=[ dcc.Tab(label="Tab One", value="tab-1-example", id="tab-1"), dcc.Tab(label="Tab Two", value="tab-2-example", id="tab-2"), dcc.Tab( label="Tab Three", value="tab-3-example", id="tab-3", disabled=True, disabled_className="disabled-tab", ), ], ), html.Div(id="tabs-content-example"), ] ) @app.callback( Output("tabs-content-example", "children"), [Input("tabs-example", "value")], ) def render_content(tab): if tab == "tab-1-example": return html.Div( [ html.H3("Tab content 1"), dcc.Graph( id="graph-1-tabs", figure={ "data": [{"x": [1, 2, 3], "y": [3, 1, 2], "type": "bar"}] }, ), ] ) elif tab == "tab-2-example": return html.Div( [ html.H3("Tab content 2"), dcc.Graph( id="graph-2-tabs", figure={ "data": [{"x": [1, 2, 3], "y": [5, 10, 6], "type": "bar"}] }, ), ] ) dash_dcc.start_server(app) tab_one = dash_dcc.wait_for_element("#tab-1") tab_two = dash_dcc.wait_for_element("#tab-2") # wait for disabled tab with custom className dash_dcc.wait_for_element("#tab-3.disabled-tab") WebDriverWait(dash_dcc.driver, 10).until( EC.element_to_be_clickable((By.ID, "tab-2")) ) # wait for Graph to be ready WebDriverWait(dash_dcc.driver, 10).until( EC.visibility_of_element_located((By.CSS_SELECTOR, "#graph-1-tabs .main-svg")) ) is_eager = "eager" if is_eager else "lazy" dash_dcc.percy_snapshot( f"Tabs with Graph - initial (graph should not resize) ({is_eager})" ) tab_two.click() # wait for Graph to be ready WebDriverWait(dash_dcc.driver, 10).until( EC.visibility_of_element_located((By.CSS_SELECTOR, "#graph-2-tabs .main-svg")) ) dash_dcc.percy_snapshot( f"Tabs with Graph - clicked tab 2 (graph should not resize) ({is_eager})" ) WebDriverWait(dash_dcc.driver, 10).until( EC.element_to_be_clickable((By.ID, "tab-1")) ) tab_one.click() # wait for Graph to be loaded after clicking WebDriverWait(dash_dcc.driver, 10).until( EC.visibility_of_element_located((By.CSS_SELECTOR, "#graph-1-tabs .main-svg")) ) dash_dcc.percy_snapshot( f"Tabs with Graph - clicked tab 1 (graph should not resize) ({is_eager})" ) assert dash_dcc.get_logs() == []
from dash import Dash import flask from flask_app import flask_app import os app = Dash( 'app', server=flask_app, url_base_pathname='/', meta_tags=[{ "charset": "utf-8" }, { "name": "description", "content": 'US has thousands of colleges and universities. At CollegeScoreCard.io you can find out more on their cost, graduation rate, average debt incurred by students, admission rate, and so on. Built on official DoE data. Easier to compare and make sense.' }, { "http-equiv": "X-UA-Compatible", "content": "IE=edge" }, { "name": "viewport", "content": "width=device-width, initial-scale=1" }, { "property": "og:image", "content": "/assets/csc_to_img.jpg" }]) #app = Dash('app', server=flask_app, url_base_pathname='/',) app.title = "CollegeScoreCard.io" app.index_string = ''' <!DOCTYPE html>
def test_tabs_render_without_selected(dash_dcc, is_eager): app = Dash(__name__, eager_loading=is_eager) menu = html.Div([html.Div("one", id="one"), html.Div("two", id="two")]) tabs_one = html.Div( [dcc.Tabs([dcc.Tab(dcc.Graph(id="graph-one"), label="tab-one-one")])], id="tabs-one", style={"display": "none"}, ) tabs_two = html.Div( [dcc.Tabs([dcc.Tab(dcc.Graph(id="graph-two"), label="tab-two-one")])], id="tabs-two", style={"display": "none"}, ) app.layout = html.Div([menu, tabs_one, tabs_two]) for i in ("one", "two"): @app.callback(Output(f"tabs-{i}", "style"), [Input(i, "n_clicks")]) def on_click_update_tabs(n_clicks): if n_clicks is None: raise PreventUpdate if n_clicks % 2 == 1: return {"display": "block"} return {"display": "none"} @app.callback(Output(f"graph-{i}", "figure"), [Input(i, "n_clicks")]) def on_click_update_graph(n_clicks): if n_clicks is None: raise PreventUpdate return { "data": [{"x": [1, 2, 3, 4], "y": [4, 3, 2, 1]}], "layout": {"width": 700, "height": 450}, } dash_dcc.start_server(app) button_one = dash_dcc.wait_for_element("#one") button_two = dash_dcc.wait_for_element("#two") button_one.click() # wait for tabs to be loaded after clicking WebDriverWait(dash_dcc.driver, 10).until( EC.visibility_of_element_located((By.CSS_SELECTOR, "#graph-one .main-svg")) ) is_eager = "eager" if is_eager else "lazy" time.sleep(1) dash_dcc.percy_snapshot(f"Tabs-1 rendered ({is_eager})") button_two.click() # wait for tabs to be loaded after clicking WebDriverWait(dash_dcc.driver, 10).until( EC.visibility_of_element_located((By.CSS_SELECTOR, "#graph-two .main-svg")) ) time.sleep(1) dash_dcc.percy_snapshot(f"Tabs-2 rendered ({is_eager})") # do some extra tests while we're here # and have access to Graph and plotly.js check_graph_config_shape(dash_dcc) assert dash_dcc.get_logs() == []
def test_dada002_external_files_init(dash_duo): js_files = [ "https://www.google-analytics.com/analytics.js", {"src": "https://cdn.polyfill.io/v2/polyfill.min.js"}, { "src": "https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js", "integrity": "sha256-43x9r7YRdZpZqTjDT5E0Vfrxn1ajIZLyYWtfAXsargA=", "crossorigin": "anonymous", }, { "src": "https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js", "integrity": "sha256-7/yoZS3548fXSRXqc/xYzjsmuW3sFKzuvOCHd06Pmps=", "crossorigin": "anonymous", }, ] css_files = [ "https://codepen.io/chriddyp/pen/bWLwgP.css", { "href": "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css", "rel": "stylesheet", "integrity": "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO", "crossorigin": "anonymous", }, ] app = Dash( __name__, external_scripts=js_files, external_stylesheets=css_files ) app.index_string = """<!DOCTYPE html> <html> <head> {%metas%} <title>{%title%}</title> {%css%} </head> <body> <div id="tested"></div> <div id="ramda-test"></div> <button type="button" id="btn">Btn</button> {%app_entry%} <footer> {%config%} {%scripts%} {%renderer%} </footer> </body> </html>""" app.layout = html.Div() dash_duo.start_server(app) js_urls = [x["src"] if isinstance(x, dict) else x for x in js_files] css_urls = [x["href"] if isinstance(x, dict) else x for x in css_files] for fmt, url in itertools.chain( (("//script[@src='{}']", x) for x in js_urls), (("//link[@href='{}']", x) for x in css_urls), ): dash_duo.driver.find_element_by_xpath(fmt.format(url)) assert ( dash_duo.find_element("#btn").value_of_css_property("height") == "18px" ), "Ensure the button style was overloaded by reset (set to 38px in codepen)" # ensure ramda was loaded before the assets so they can use it. assert dash_duo.find_element("#ramda-test").text == "Hello World"
def start_streaming(inlets, channels = ['TP9', 'AF7', 'AF8', 'TP10'], debug = False): '''Convert recordings to MNE format. Args: inlets : array LSL streams captured. channels : array Channels to draw in graphs. debug : bool Dash debugging. See also: search_streams ''' global df, data_shown, playpause, expand_graphs cols = [] df = [] for inlet in inlets: channel = inlet.info().desc().child('channels').first_child() all_channels = [channel.child_value('label')] while len(all_channels) != inlet.info().channel_count(): channel = channel.next_sibling() all_channels.append(channel.child_value('label')) cols.append(all_channels) df.append(pd.DataFrame(columns=all_channels)) data_shown = 1400 playpause = True expand_graphs = False app = Dash(__name__) app.title = 'Muse streaming' app.layout = serve_layout(channels) @app.callback( Output('interval_component', 'interval'), Input('interval_modifier', 'value') ) def update_interval(value): return value @app.callback( Output('graphs', 'children'), Input('interval_component', 'n_intervals'), Input('channels_selected', 'value'), Input('zoom_in', 'n_clicks'), Input('zoom_out', 'n_clicks'), Input('reset', 'n_clicks'), Input('playstop', 'n_clicks'), Input('expand_graphs', 'on') ) def draw_graph(in_interval, in_channels_selected, in_zoom_in, in_zoom_out, in_reset, in_playstop, in_expand_graphs): global df, data_shown, playpause, expand_graphs changed_id = [p['prop_id'] for p in callback_context.triggered][0] if 'zoom_in' in changed_id: if data_shown != 200: data_shown = data_shown - 200 if 'zoom_out' in changed_id: data_shown = data_shown + 200 if 'reset' in changed_id: data_shown = 1400 if 'playstop' in changed_id: playpause = True if playpause == False else False graphs = [] for index, inlet in enumerate(inlets): if playpause == True: samples, timestamps = inlet.pull_chunk(timeout=0.0, max_samples=1024) utc = [datetime.utcfromtimestamp(timestamp).replace(tzinfo=timezone.utc).astimezone(tz=None).strftime('%H:%M:%S.%f') for index, timestamp in enumerate(timestamps)] df_aux = pd.DataFrame(samples, columns=cols[index], index=utc) df[index] = df[index].append(df_aux) df_to_show = df[index].tail(data_shown) df_to_show = df_to_show[in_channels_selected] else: df_to_show = df[index].tail(data_shown) df_to_show = df_to_show[in_channels_selected] channel_qualities = [] for i in in_channels_selected: if abs(df_to_show[i].tail(200).max() - df_to_show[i].tail(200).min()) < 300: channel_qualities.append(i + ' - GOOD ' + u'\u2713') else: channel_qualities.append(i + ' - BAD ' + u'\u2716') if in_expand_graphs == False: if len(df_to_show.columns) % 2 == 0: fig = make_subplots(rows=int(len(df_to_show.columns) / 2), cols=2, subplot_titles=channel_qualities) else: fig = make_subplots(rows=int((len(df_to_show.columns) / 2) + 0.5), cols=2, subplot_titles=channel_qualities) j = [1, 1, 2, 2, 3] k = [1, 2, 1, 2, 1] for index2, column in enumerate(df_to_show.columns): fig.add_trace( Scatter({ 'x': df_to_show.index2, 'y': df_to_show[column] }), row=j[index2], col=k[index2] ) heights = [500, 500, 800, 800, 1100] fig.update_layout(height=heights[len(df_to_show.columns)-1], showlegend=False) else: fig = make_subplots(rows=len(df_to_show.columns), cols=1, subplot_titles=channel_qualities) j = 1 for i in df_to_show.columns: fig.add_trace( Scatter({ 'x': df_to_show.index, 'y': df_to_show[i] }), row=j, col=1 ) j += 1 heights = [500, 900, 1200, 1500, 1600] fig.update_layout(height=heights[len(df_to_show.columns)-1], showlegend=False) graphs.append( html.Div([ html.H3(inlet.info().name()), Graph( id='muse_livestream', config={ 'displaylogo': False, 'modeBarButtonsToRemove': ['pan2d','lasso2d'] }, figure=fig ) ], style={'margin': 'auto', 'text-align': 'center'}) ) return(html.Div(graphs)) app.run_server(debug=debug)
from dash import Dash from dash.components import * from userguide import app, const dash = Dash(server=app, url_namespace="/{}".format(const["click-and-hover"])) dash.layout = div( [div(id="app"), hr(), Highlight(id="code", className="python")], style={"width": "90%"}, className="container" ) app_template = """from dash import Dash from dash.components import Dropdown, div, pre {} dash = Dash(__name__) dash.layout = {} {} if __name__ == "__main__": dash.server.run(debug=True) """ preamble = """import plotly.plotly as py from copy import deepcopy import json # Download the contour plot from https://plot.ly py.sign_in("PlotBot", "da05144j7i") fig = py.get_figure("https://plot.ly/~chris/5496")
def init_dash(app): global dash_histograms dash_histograms = Dash(__name__, server=app, url_base_pathname='/dash_histograms/') dash_histograms.layout = html.Div([ dcc.Location( id="id-location", refresh=False ), # to potrzebuję aby wyciągnąć z URLa identyfikator zadania html.Div(id="my-debug-before", children=f"proszę czekać...!"), dcc.Store(id="my-store", data={'task_id': 'none'}), # tutaj będę przechowywać zmienne dcc.Interval( id='my-interval', interval=1 * 1000 ), # in milliseconds - co jaki czas odświeżamy w celu sprawdzenia, czy zadanie obliczeniowe się skończyło html.Div(id="my-debug-after", children=f"Proszę czekać...!"), ]) dash_histograms.config.suppress_callback_exceptions = True @dash_histograms.callback( [ dash.dependencies.Output('my-debug-before', 'children'), dash.dependencies.Output('my-store', 'data') ], [ dash.dependencies.Input('id-location', 'pathname'), dash.dependencies.Input('id-location', 'search') ], state=[dash.dependencies.State('my-store', 'data')]) def display_page(pathname, search, data): logger.debug( f"pathname: {pathname} search: {search} my-store.data before: {data}" ) # obcinam '/' z początku search = search[1:] if search.startswith("?") else search # Data are returned as a dictionary. The dictionary keys are the unique query # variable names and the values are lists of values for each name. args = urllib.parse.parse_qs(search) if "task_id" in args: print(f'Otrzymałem task_id: {args["task_id"][0]}') else: print(f'pusto....') data['task_id'] = args["task_id"][0] print(f'data after: {data}') return f"Witaj świecie {args['task_id']}", data def buildLog(taskLog): return html.Div(children=[ f"Postęp obliczeń: {taskLog['progress_percent']}", html.Ul(children=list( map(lambda msg: html.Li(children=[msg]), taskLog['messages']))) ]) @dash_histograms.callback( [dash.dependencies.Output('my-debug-after', 'children')], [dash.dependencies.Input('my-interval', 'n_intervals')], state=[dash.dependencies.State('my-store', 'data')]) def display_interval(value, data): msg = "" if data['task_id'] != 'none': #logger.debug(f"Szukam joba: {data['task_id']}") ############ Pytam się o joba... ######## job = hworker.get_job(data['task_id']) ######################################### print(f"Oto job: {job['args']}") if job is not None: print(job['taskLogs']) if job['status'] == 'finished': with open(f"{job['args'][0]}/histogram.json") as f: histogram = json.load(f) plots = [] sc = histogram['scale'] df = pd.DataFrame( [], columns=['ROI', 'D_min', 'D_avg', 'D_max']) for k in histogram["original"].keys(): h = histogram["original"][k] hdata = np.array(h[0]) plots.append( go.Scatter(x=hdata[:, 0], y=hdata[:, 1], name=k, mode='lines+markers')) df = df.append([{ 'ROI': k, 'D_min': h[1] * sc, 'D_avg': h[2] * sc, 'D_max': h[3] * sc }]) fig = go.Figure(data=plots) plot = dcc.Graph(id='histogram-graph', figure=fig) table = dash_table.DataTable( id='table', columns=[{ "name": i, "id": i } for i in df.columns], data=df.to_dict('records'), ) msg = html.Div(children=[plot, table]) else: msg = html.Div(children=[ html.Div(children=[ f"Status zadania o identyfikatorze {data['task_id']} to ", html.Span(job['status'], style={"color": "red"}), f", zwrócona wartość zadania: {job['job']}" ]), buildLog(job['taskLogs']) ]) else: msg = f"Nie mogę odnaleźć zadania o identyfikatorze {data['task_id']}" else: return f"Czekam na rozpoczęcie zadania. (Brak parametru 'task_id' w lokalnym stanie.)", return msg,
import requests from dash import Dash from dash.components import * from userguide import app, const dash = Dash(server=app, url_namespace='') dash.layout = div([ h1('dash'), blockquote(''' dash is a framework for creating interactive web-applications in pure python.'''), h3('quickstart'), Highlight('\n'.join([ '$ pip install dash.ly --upgrade', '$ git clone -b skeleton https://github.com/chriddyp/messin.git', '$ cd messin', '$ pip install -r requirements.txt', '$ cd helloworld', '$ python helloworld.py', ' * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)']), className="bash"), hr(), div(className="row", content=[
# Dash from dash import Dash import dash_bootstrap_components as dbc ####################################################################################### # APP, SERVER ####################################################################################### # Custom CSS ionicons = { 'href': 'https://unpkg.com/[email protected]/dist/css/ionicons.min.css', 'rel': 'stylesheet' } bootstrap = dbc.themes.BOOTSTRAP external_css = [bootstrap, ionicons] # Meta tags meta_tags = [{ "name": "viewport", "content": "width=device-width, initial-scale=1" }] # Init server server = Flask(__name__) # Init App app = Dash(__name__, external_stylesheets=external_css, meta_tags=meta_tags, server=server) app.title = 'Parser' app.config.suppress_callback_exceptions = True # Todo: Fix suppression?
from dash import Dash from dash_html_components import Div, H1, P, H3 from dash_core_components import Graph, Dropdown, Slider, Checklist from dash.dependencies import Input, Output from random import randint app = Dash(__name__) N = 20 database = { 'index': list(range(N)), 'maiores': [randint(1, 1000) for _ in range(N)], 'menores': [randint(1, 1000) for _ in range(N)], 'bebes': [randint(1, 1000) for _ in range(N)], } app.layout = Div(children=[ H1('Evento X'), H3('idade das pessoas que foram ao evento'), Dropdown(options=[{ 'label': 'Menores de Idade', 'value': 'menores' }, { 'label': 'Bebes', 'value': 'bebes' }, { 'label': 'Maiores de idade', 'value': 'maiores' }], value='menores'),
def test_ldcp006_children_identity(dash_dcc): lock = Lock() app = Dash(__name__) app.layout = html.Div([ html.Button("click", id="btn"), dcc.Loading(dcc.Graph(id="graph"), className="loading"), ]) @app.callback(Output("graph", "figure"), [Input("btn", "n_clicks")]) def update_graph(n): with lock: bars = list(range(2, (n or 0) + 5)) return { "data": [{ "type": "bar", "x": bars, "y": bars }], "layout": { "width": 400, "height": 400 }, } def get_graph_visibility(): return dash_dcc.driver.execute_script( "var gd_ = document.querySelector('.js-plotly-plot');" "return getComputedStyle(gd_).visibility;") with lock: dash_dcc.start_server(app) dash_dcc.find_element(".loading .dash-spinner") dash_dcc.find_element("#graph .js-plotly-plot") dash_dcc.driver.execute_script( "window.gd = document.querySelector('.js-plotly-plot');" "window.gd.__test__ = 'boo';") assert get_graph_visibility() == "hidden" test_identity = ("var gd_ = document.querySelector('.js-plotly-plot');" "return gd_ === window.gd && gd_.__test__ === 'boo';") wait.until( lambda: len(dash_dcc.find_elements(".js-plotly-plot .bars path")) == 3, 3) assert dash_dcc.driver.execute_script(test_identity) assert get_graph_visibility() == "visible" with lock: dash_dcc.find_element("#btn").click() dash_dcc.find_element(".loading .dash-spinner") assert len(dash_dcc.find_elements(".js-plotly-plot .bars path")) == 3 assert dash_dcc.driver.execute_script(test_identity) assert get_graph_visibility() == "hidden" wait.until( lambda: len(dash_dcc.find_elements(".js-plotly-plot .bars path")) == 4, 3) assert dash_dcc.driver.execute_script(test_identity) assert get_graph_visibility() == "visible" assert dash_dcc.get_logs() == []
getNumOfInstances = staticmethod(getNumOfInstances) dt0 = dt.DataTable(rows=[{ 0: 0 }], row_selectable=False, filterable=False, sortable=False, selected_row_indices=[], id=str(hash('dt0'))) print("start servers...") flask_app = Flask(__name__) dash_app = Dash(__name__, server=flask_app, url_base_pathname='/d/') print("start dash...") dash_app.title = 'HydroOpt2.0 Dev Tools' dash_app.layout = html.Div( id='page-content', children=[dcc.Location(id='url', refresh=False), dt0]) dash_app.css.config.serve_locally = False dash_app.scripts.config.serve_locally = False dash_app.config.supress_callback_exceptions = True #copy css and js files to static folder STATIC_FOLDER = os.path.join( os.getcwd(), 'static' ) #'/cygdrive/c/Users/Aleksandr Proskurin/Documents/work/MyDashFiles/static/' #todo temporäres verzeichnis ("with tempfile.TemporaryDirectory() as dirpath:")
def add_slide2_callbacks(dash: Dash) -> None: """Add routing callback""" dash.callback(Output("slide2-plot", "children"), [Input("url", "pathname")])(update_plot)
def __init__(self, input_graph, app_display='default'): """ Initialises the DashGraph object from the Graph class object. Dash creates a mini Flask server to visualise the graphs. :param app_display: (str) 'default' by default and 'jupyter notebook' for running Dash inside Jupyter Notebook. :param input_graph: (Graph) Graph class from graph.py. """ self.graph = None # Dash app styling with Bootstrap if app_display == 'jupyter notebook': self.app = JupyterDash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) else: self.app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP]) # Graph class object self.graph = input_graph # The dictionary of the nodes coordinates self.pos = self.graph.get_pos() # Colours of nodes self.colour_groups = {} # If colours have been assigned in Graph class, add styling if self.graph.get_node_colours(): colour_map = self.graph.get_node_colours() self._assign_colours_to_groups(list(colour_map.keys())) self.weights = [] self.elements = [] self._update_elements() # Load the different graph layouts cyto.load_extra_layouts() self.layout_options = ['cose-bilkent', 'cola', 'spread'] self.statistics = [ 'graph_summary', 'average_degree_connectivity', 'average_neighbor_degree', 'betweenness_centrality' ] # Load default stylesheet self.stylesheet = None self.stylesheet = self._get_default_stylesheet() # Append stylesheet for colour and size # If sizes have been set in the Graph class self._style_colours() if self.graph.get_node_sizes(): self._assign_sizes() self.cyto_graph = None # Callback functions to hook frontend elements to functions self.app.callback(Output('cytoscape', 'layout'), [Input('dropdown-layout', 'value')])( DashGraph._update_cytoscape_layout) self.app.callback(Output('json-output', 'children'), [Input('dropdown-stat', 'value')])( self._update_stat_json) self.app.callback(Output('cytoscape', 'elements'), [Input('rounding_decimals', 'value')])( self._round_decimals)
import dash_core_components as dcc import dash_html_components as html from dash import Dash import plotly.graph_objs as go import random as r q = lambda i: r.randint(0,i) a = [[q(10001) for i in range(1000)] for j in range(10)] b = [[i-10001*2 for i in j] for j in a] c = [[i+10001*2 for i in j] for j in a] z=[go.Surface(z=a), go.Surface(z=b,showscale=False,opacity=0.9), go.Surface(z=c,showscale=False,opacity=0.3)] layout= go.Layout(title="Surface",xaxis=dict(title="X"),yaxis=dict(title="Y"),hovermode="closest") app=Dash() app.layout = html.Div([ dcc.Graph(id="Surface",figure=dict(data=z,layout=layout)) ]) if __name__ == "__main__": app.run_server()
def vxv(cfg, data): app = Dash(csrf_protect=False) server = app.server colors = {'background': '#000000', 'text': '#D3D3D3'} # Load config (with mappings) with open(cfg) as config: cfg = json.load(config, object_pairs_hook=OrderedDict) # Get the first key (random) from mappings, and load contrast/func #global_func, global_contrast, global_design global_contrast_name = list(cfg['mappings'].keys())[0] global_func, global_contrast = load_data(op.join(data, global_contrast_name), load_func=True) global_design = read_design_file(op.join(data, global_contrast_name)) # Kind of an hack: save on disk which contrast we've loaded # (to avoid reloading the func-data every callback) with open("current_contrast.txt", "w") as text_file: text_file.write(global_contrast_name) # timeseries or subjects? grouplevel = global_func.shape[:3] == (91, 109, 91) # Use the mean as background if grouplevel: global_bg = nib.load( op.join(op.dirname(__file__), 'data', 'standard.nii.gz')).get_data() else: global_bg = global_func.mean(axis=-1) if cfg['standardize']: global_func = standardize(global_func) # Start layout of app app.layout = html.Div(children=[ html.Div( className='ten columns offset-by-one', children=[ html.H1(children= 'VoxelViz: An interactive viewer for BOLD-fMRI data', style={ 'textAlign': 'center', 'color': colors['text'] }, id='title'), html.Div( className='row', children=[ dcc.Markdown( """Developed for the [TransIP](https://www.transip.nl/) VPS-competition""" ) ], style={ 'textAlign': 'center', 'color': colors['text'], 'padding-bottom': '20px' }) ]), html.Div( className='five columns', children=[ html.Div( className='row', children=[ html.Div( className='five columns', children=[ dcc.Dropdown(options=[{ 'value': key, 'label': val } for key, val in cfg['mappings'].items()], value=global_contrast_name, id='contrast') ]), html.Div( className='three columns', children=[ dcc.RadioItems( id='direction', options=[{ 'label': 'X', 'value': 'X' }, { 'label': 'Y', 'value': 'Y' }, { 'label': 'Z', 'value': 'Z' }], labelStyle={'display': 'inline-block'}, value='X') ], style={ 'color': colors['text'], 'padding-top': '5px' }), html.Div(className='four columns', children=[ dcc.Slider(min=0, step=1, value=50 if grouplevel else 30, id='slice'), ], style={'padding-top': '5px'}), ], style={'padding-bottom': '20px'}), html.Div(className='row', children=[ dcc.Graph(id='brainplot', animate=False, config={'displayModeBar': False}) ]), html.Div(className='row', children=[ html.Div(className='two columns', children=[html.P('Threshold:')], style={ 'textAlign': 'center', 'color': colors['text'] }), html.Div(className='ten columns', children=[ dcc.Slider(id='threshold', min=0, max=10, step=0.1, value=2.3, marks={ i: i for i in np.arange( 0, 10.5, 0.5) }) ], style={'padding-top': '5px'}) ]), ]), html.Div( className='six columns', children=[ html.Div( className='row', children=[ html.Div( className='five columns', children=[ dcc.RadioItems( id='datatype', options=[{ 'label': 'time', 'value': 'time' }, { 'label': 'frequency', 'value': 'freq' }], labelStyle={'display': 'inline-block'}, value='time') ], style={ 'color': colors['text'], 'padding-left': '50px' }), html.Div(className='four columns', children=[ dcc.Checklist(options=[{ 'label': 'Voxel', 'value': 'voxel' }, { 'label': 'Model', 'value': 'model' }], values=['voxel'], id='voxel_disp', labelStyle={ 'display': 'inline-block' }) ], style={ 'padding-left': '0px', 'color': colors['text'] }) ]), html.Div( className='row', children=[dcc.Graph(id='brainplot_time', animate=False)]), html.Div(className='row', children=[ html.Div(className='ten columns', children=[html.P(id='parameter_value')], style={ 'textAlign': 'center', 'color': colors['text'], 'padding-top': '5px', 'font-size': '120%' }) ]), ]) ]) external_css = ["https://codepen.io/lukassnoek/pen/Kvzmzv.css"] for css in external_css: app.css.append_css({"external_url": css}) @app.callback( Output(component_id='parameter_value', component_property='children'), [ Input(component_id='brainplot_time', component_property='figure'), Input(component_id='voxel_disp', component_property='values') ]) def update_parameter_statistics(figure, voxel_disp): if 'model' in voxel_disp and len(figure['data']) > 1: y = np.array(figure['data'][0]['y']) y_hat = np.array(figure['data'][1]['y']) n_pred = global_design.shape[1] stat_txt = calculate_statistics(y, y_hat, n_pred, grouplevel) else: stat_txt = '' return stat_txt @app.callback( Output(component_id='slice', component_property='max'), [Input(component_id='direction', component_property='value')]) def update_slice_slider(direction): # To fix! srange = { 'X': global_contrast.shape[0], 'Y': global_contrast.shape[1], 'Z': global_contrast.shape[2] } return srange[direction] @app.callback(Output( component_id='brainplot', component_property='figure'), [ Input(component_id='threshold', component_property='value'), Input(component_id='contrast', component_property='value'), Input(component_id='direction', component_property='value'), Input(component_id='slice', component_property='value') ]) def update_brainplot(threshold, contrast, direction, sslice): with open("current_contrast.txt", "r") as text_file: current_contrast = text_file.readlines()[0] if contrast != current_contrast: nonlocal global_contrast, global_bg, global_func if global_contrast.shape == (91, 109, 91): global_contrast = load_data(contrast, load_func=False) else: global_func, global_contrast = load_data(op.join( data, contrast), load_func=True) global_bg = global_func.mean(axis=-1) with open("current_contrast.txt", "w") as text_file: text_file.write(contrast) bg_slice = index_by_slice(direction, sslice, global_bg) img_slice = index_by_slice(direction, sslice, global_contrast) bg_map = go.Heatmap(z=bg_slice.T, colorscale='Greys', showscale=False, hoverinfo="none", name='background') tmp = np.ma.masked_where(np.abs(img_slice) < threshold, img_slice) func_map = go.Heatmap(z=tmp.T, opacity=1, name='Activity map', colorbar={ 'thickness': 20, 'title': 'Z-val', 'x': -.1 }) layout = go.Layout(autosize=True, margin={ 't': 50, 'l': 5, 'r': 5 }, plot_bgcolor=colors['background'], paper_bgcolor=colors['background'], font={'color': colors['text']}, title='Activation pattern: %s' % cfg['mappings'][contrast], xaxis=dict(autorange=True, showgrid=False, zeroline=False, showline=False, autotick=True, ticks='', showticklabels=False), yaxis=dict(autorange=True, showgrid=False, zeroline=False, showline=False, autotick=True, ticks='', showticklabels=False)) return {'data': [bg_map, func_map], 'layout': layout} @app.callback( Output(component_id='brainplot_time', component_property='figure'), [ Input(component_id='threshold', component_property='value'), Input(component_id='contrast', component_property='value'), Input(component_id='direction', component_property='value'), Input(component_id='slice', component_property='value'), Input(component_id='brainplot', component_property='hoverData'), Input(component_id='voxel_disp', component_property='values'), Input(component_id='datatype', component_property='value') ]) def update_brainplot_time(threshold, contrast, direction, sslice, hoverData, voxel_disp, datatype): if datatype == 'time': if grouplevel: xtitle = 'Subjects' else: xtitle = 'Time' ytitle = 'Activation (contrast estimate)' else: xtitle = 'Frequency (Hz)' ytitle = 'Power' with open("current_contrast.txt", "r") as text_file: current_contrast = text_file.readlines()[0] if contrast != current_contrast: nonlocal global_contrast, global_func, global_design global_func, global_contrast = load_data(contrast, load_func=True) global_design = read_design_file(op.join(data, contrast)) if cfg['standardize']: global_func = standardize(global_func) with open("current_contrast.txt", "w") as text_file: text_file.write(contrast) if hoverData is None: if grouplevel: x, y = 40, 40 else: x, y = 20, 20 else: x = hoverData['points'][0]['x'] y = hoverData['points'][0]['y'] img = index_by_slice(direction, sslice, global_func) signal = img[x, y, :].ravel() if np.all(np.isnan(signal)): signal = np.zeros(signal.size) if 'model' in voxel_disp and not np.all(signal == 0): betas = np.linalg.lstsq(global_design, signal)[0] signal_hat = betas.dot(global_design.T) fitted_model = go.Scatter(x=np.arange(1, global_func.shape[-1] + 1), y=signal_hat, name='Model fit') if grouplevel: datatype = 'time' plottitle = 'Activation across subjects' bcolors = [ 'rgb(225,20,20)' if sig > 0 else 'rgb(35,53,216)' for sig in signal ] bdata = go.Bar(x=np.arange(1, global_func.shape[-1] + 1), y=signal, name='Activity', marker=dict(color=bcolors, line=dict(color='rgb(211,211,211)', width=0.2))) else: plottitle = 'Activation across time' bdata = go.Scatter(x=np.arange(global_func.shape[-1]), y=signal, name='Activity') layout = go.Layout( autosize=True, margin={ 't': 50, 'l': 50, 'r': 5 }, plot_bgcolor=colors['background'], paper_bgcolor=colors['background'], font={'color': colors['text']}, xaxis=dict( #autorange=False, showgrid=True, zeroline=True, showline=True, autotick=True, #ticks='', showticklabels=True, title=xtitle), yaxis=dict( autorange=True, showgrid=True, zeroline=True, showline=True, autotick=True, #ticks='', showticklabels=True, title=ytitle), title=plottitle) if 'model' in voxel_disp and not np.all(signal == 0): figure = {'data': [bdata, fitted_model], 'layout': layout} else: figure = {'data': [bdata], 'layout': layout} if datatype == 'freq': for i, element in enumerate(figure['data']): from scipy.signal import periodogram dat = element['y'] freq, power = periodogram(dat, 0.5, return_onesided=True) element['y'] = power element['x'] = freq figure['data'][i] = element return figure app.run_server()
def set_layout( app: dash.Dash, df: pd.DataFrame, ) -> None: departments = df["Department"].unique() products = df["Product"].unique() fig = create_pnl_chart(monthly_totals(df)) app.layout = dbc.Container( html.Div( [ dbc.NavbarSimple( [ dbc.NavItem( dbc.NavLink("Log out", href="/logout", external_link=True) ), ], brand="Insight | Business Analytics", brand_href="#", color="primary", dark=True, ), dbc.Row( dbc.Col( html.Div( [ dcc.Graph(id="bar-chart", figure=fig), ] ) ) ), dbc.Row( [ dbc.Col( dbc.FormGroup( [ dcc.Dropdown( id="department-filter", options=[ {"label": d, "value": d} for d in departments ], placeholder="Filter by department", ), ], ) ), dbc.Col( dbc.FormGroup( [ dcc.Dropdown( id="product-filter", options=[ {"label": p, "value": p} for p in products ], placeholder="Filter by product", ), ], ) ), dbc.Col( [ dbc.Button("Export", id="download-button"), Download(id="download"), ] ), ], ), dbc.Row( [ dbc.Col( DataTable( id="sales-table", columns=table_columns, data=df.to_dict("records"), page_size=20, style_cell_conditional=[ { "if": {"column_id": c}, "textAlign": "left", } for c in ["Date", "Department", "Product"] ], style_as_list_view=True, ) ) ] ), ] ) )
machine_choice_dict = { 'swach-micro': 5700, 'swach-1.3': 17000, 'swach-3.2': 30000, 'swach-4.2': 132000, 'swach-5.0': 285000, } target_population = [x / 10 for x in range(1, 11)] india_map = IndiaMap(create_map=True) state_map = StateMap() selection = Selections() app = Dash(__name__) app.layout = html.Div([ html.Div([ dcc.Graph(id='map', style={'width': '120'}, figure={}), ], style={ 'width': '100%', 'float': 'center', 'display': 'inline-block' }), html.Div([ html.P(""), ], style={ 'width': '5%', 'display': 'inline-block'
import time import dash_bootstrap_components as dbc from dash import Dash from flask import Flask from flask_login import LoginManager from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() login_manager = LoginManager() log_time = time.strftime('%d%b%y %H:%M:%S') FONT_AWESOME = "https://use.fontawesome.com/releases/v5.7.2/css/all.css" card_style = { "box-shadow": "0 4px 5px 0 rgba(0,0,0,0.14), 0 1px 10px 0 rgba(0,0,0,0.12), 0 2px 4px -1px rgba(0,0,0,0.3)" } # TODO: move all style information to css file server = Flask(__name__) app = Dash(__name__, server=server, external_stylesheets=[dbc.themes.BOOTSTRAP, FONT_AWESOME]) app.config.suppress_callback_exceptions = True app.scripts.config.serve_locally = True login_manager.init_app(server)
import pandas as pd import numpy as np import plotly.graph_objects as go import plotly.offline as pyo from dash import Dash import dash_core_components as dcc import dash_html_components as html app = Dash() colors = {'bg': '#111111', 'text': '#7FDBFF'} app.layout = html.Div(children=[ html.H1('hello world', style={ 'textAlign': 'center', 'color': colors['text'] }), dcc.Graph(id='example', figure={ 'data': [{ 'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF' }, { 'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'NYC'
__author__ = 'CountingChickens' from dash import Dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import dash_table import pandas as pd from flask import Flask, render_template, request, session, make_response app = Flask(__name__) # '__main__' app_dash = Dash(__name__, server=app, url_base_pathname='/') path = 'data/' df_tpc = pd.read_csv(f'{path}AI_topics.csv', index_col=0) selected_topics = [tpc.lower() for tpc in df_tpc.index.values] df_aut = pd.read_csv(f'{path}AI_authors.csv', index_col=0) df_tim = pd.read_csv(f'{path}AI_time.csv', index_col=0) df_txt = pd.read_csv(f'{path}AI_body.csv', index_col=0) df_txt = df_txt.rename(columns={ 'Favorite Count': 'Favs', 'Retweet Count': 'RT' }) cols_from_txt = list(df_txt.columns.values) cols_from_txt.remove('Place')
from flask import Flask from dash import Dash import re from django.http.response import HttpResponse URL_BASE_PATHNAME = '/' + 'dash_within_django/' server = Flask(__name__) app = Dash(server=server, url_base_pathname=URL_BASE_PATHNAME) # if setting this app locally then some features may not display properly e.g. dropdown menus didnt display properly for me # so I placed css content from the dash_core_components folder in dash_styles.css in static. # on Windows, the css for other components can be found in e.g.: # C:\Users\{your_username}\AppData\Local\Continuum\anaconda3\Lib\site-packages\dash_core_components app.css.config.serve_locally = True app.scripts.config.serve_locally = True app.config.suppress_callback_exceptions = True # this is called from views.py to get the response data from the Dash/Flask instance: def dash_dispatcher(request, ): ''' Main function @param request: Request object ''' params = { 'data': request.body, 'method': request.method, 'content_type': request.content_type
from dash import Dash import dash_html_components as html import dash_ui as dui app = Dash() my_css_urls = ["https://codepen.io/rmarren1/pen/mLqGRg.css"] for url in my_css_urls: app.css.append_css({"external_url": url}) grid = dui.Grid(_id="grid", num_rows=12, num_cols=12, grid_padding=0) grid.add_element(col=1, row=1, width=3, height=4, element=html.Div(style={ "background-color": "red", "height": "100%", "width": "100%" })) grid.add_element(col=4, row=1, width=9, height=4, element=html.Div(style={ "background-color": "blue", "height": "100%", "width": "100%" }))
from dash import Dash from dash.components import * from userguide import app, const dash = Dash(server=app, url_namespace='/{}'.format(const['text-input'])) dash.layout = div([ div(id="app"), hr(), Highlight(id="code", className="python") ], className="container") app_template = '''from dash import Dash from dash.components import * {} dash = Dash(__name__) dash.layout = {} {} if __name__ == "__main__": dash.server.run(debug=True) ''' preamble = '''import pandas as pd import pandas_datareader.data as web import datetime as dt import traceback
from dash import Dash, Input, State, Output, dcc, html import time from multiprocessing import Value from tests.integration.long_callback.utils import get_long_callback_manager long_callback_manager = get_long_callback_manager() handle = long_callback_manager.handle app = Dash(__name__, long_callback_manager=long_callback_manager) app._cache_key = Value("i", 0) # Control return value of cache_by function using multiprocessing value def cache_fn(): return app._cache_key.value long_callback_manager.cache_by = [cache_fn] app.layout = html.Div([ dcc.Input(id="input", value="AAA"), html.Button(id="run-button", children="Run"), html.Div(id="status", children="Finished"), html.Div(id="result", children="No results"), ]) @app.long_callback( Output("result", "children"), [Input("run-button", "n_clicks"),
from dash import Dash from dash.components import * from userguide import app, const dash = Dash(server=app, url_namespace='/' + const['layout']) complaint_text = "Each week thousands of consumers' complaints about financial products are sent to companies for response." import pandas as pd df = pd.read_csv('https://raw.githubusercontent.com/chriddyp/' 'messin/master/examples/consumer_complaints_50k.csv', index_col='Date sent to company', parse_dates=True) most_common_complaints = df['Company'].value_counts() component_list = [ Dropdown(id='dropdown', options=[{'val': v, 'label': l} for (v, l) in [ ('oranges', 'Oranges'), ('apples', 'Apples'), ('pineapple', 'Pineapple')] ]), TextInput( id='textinput', label='Name', placeholder='James Murphy' ), Slider(id='slider', min=-5, max=5, value=3, step=0.2, label='time'),
import pandas.io.data as web from dash import Dash from dash.components import div, h2, PlotlyGraph, Dropdown, label, Highlight from datetime import datetime as dt df = web.DataReader("aapl", 'yahoo', dt(2007, 10, 1), dt(2009, 4, 1)) dash = Dash(__name__) dash.layout = div([ h2('hello dash'), Highlight('import blah', className='python'), div(className='row', content=[ div(className='two columns', content=[ div([ label('select x data'), Dropdown(id='xdata', options=[{'val': c, 'label': c} for c in df.columns]) ]), div([ label('select y data'), Dropdown(id='ydata', options=[{'val': c, 'label': c} for c in df.columns]) ]), ]), div(className='ten columns', content=[ PlotlyGraph(id='graph') ]) ]) ])