✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
⚾️ It's finally Baseball season! Root for the home team... & Register for our Sports Analytics Webinar!

Plot behaves differently in dash

Hi all, I have two graphs to render but one always rendered as black with randoms axis, BUT the same code works just fine in plotly. I’m pretty new to Dash, and thanks in advance.

  1 **strong text**
  2 import dash
  3 import dash_core_components as dcc
  4 import dash_html_components as html
  5 from dash.dependencies import Input, Output
  6 
  7 import plotly
  8 import plotly.plotly as py
  9 import plotly.figure_factory as ff
 10 import plotly.graph_objs as go
 11 from plotly import tools 
 12 
 13 import pandas as pd
 14 import numpy as np
 15 import json
 16 from database import basedb
 17 from arctic import Arctic
 18 from arctic.date import DateRange
 19 
 20 app = dash.Dash(__name__)
 21 app.layout = html.Div(
 22     className='here',
 23     children= [
 24         html.Div(),
 25         html.Div([
 26             html.H4("est"),
 27             dcc.Graph(id='graph-15'),
 28             dcc.Interval(
 29                 id='trigger-15',
 30                 interval=2 * 1000, # in milliseconds
 31                 n_intervals=0
 32             )   
 33         ]), 
 34         html.Div(),
 35         html.Div([
 36             html.H4("test"),
 37             dcc.Graph(id='graph-16'),
 38             dcc.Interval(
 39                 id='trigger-16',
 40                 interval=3 * 1000, # in milliseconds
 41                 n_intervals=0
 42             )   
 43         ])  
 44     #     html.Div([
 45     #         html.H4('XBT Trades Minitor'),
 46     #         html.Div(id='table-15min'),
 47     #         dcc.Graph(id='graph-15min'),
 48     #         dcc.Interval(
 49     #             id='interval-15min',
 50     #             interval=10 * 1000, # in milliseconds
 51     #             n_intervals=0
 52     #         )
 53     #     ])
 54     ]
 55 )   
 56 
 57 cli = basedb.BaseDB()
 58 cli.load_config('../docs/config/my_db.json')
 59 conn, db, auth = cli.connect_server()
 60 store = Arctic(conn)
 61 lib = store['trades']
 62 
 63 # @app.callback(Output('text-15', 'children')
 64 #               [Input('cache', 'children')])
 65 # def update_metrics(n):
 66 #     style = {'padding': '5px', 'fontSize': '16px'}
 67 #     rng = DateRange(start=pd.Timestamp("now") - pd.Timedelta(minutes=15))
 68 #     df = lib.read('XBT', rng)
 69 #     # df_json = json.loads(jsonfied_data)
 70 #     # df = pd.read_json(df_json)[df.index > pd.Timestamp("now") - pd.Timedelta(minutes=15)]
 71 #     sell_vol = df['s'].resample("1min").sum()
 72 #     total_vol = df['v'].resample("1min").sum()
 73 #     vol_to_12ma = total_vol.rolling(12).mean()
 74 #     sell_to_12ma = sell_vol.rolling(12).mean()
 75 #     return [
 76 #             html.Span('Volume / Volume 12MA: {0:.2f}'.format(total_vol/vol_to_12ma), style=style),
 77 #             html.Span('Sell / Sell 12MA: {0:.2f}'.format(sell_vol/ sell_to_12ma), style=style),
 78 #     ]
 79 
 80 configs = {
 81         '300s' : {
 82             'length' :   300,
 83             'resample' : '1s',
 84         },
 85         '15min' : {
 86             'length' :   15,
 87             'resample' : '5s',
 88         },
 89         '60min' : {
 90             'length' :   60,
 91             'resample' : '1min',
 92         },
 93         '240min' : {
 94             'length' :   240,
 95             'resample' : '5min',
 96         },
 97 }
 98 def compose_graph(conf_key):
 99     rng = DateRange(start=pd.Timestamp("now") - pd.Timedelta(seconds=conf_key['length']))
100     df = lib.read('XBT', rng)
101     sell_vol = df['s'].resample(conf_key['resample']).sum()
102     total_vol = df['v'].resample(conf_key['resample']).sum()
103     st = df['s'].sum()
104     vt = df['v'].sum()
105     low = df.p.min()
106     high = df.p.max()
107     dd = df.groupby(pd.cut(df['p'], np.linspace(low, high, num=50))).sum()
108     return
109     {
110             'data': [
111             go.Bar(
112                 x = dd['v'].values,
113                 y = np.linspace(low, high, num=50),
114                 name = 'Volume',
115                 orientation = 'h',
116                 opacity = 0.6,
117                 marker = dict(
118                     color = 'rgba(22, 166, 166)'
119                 )
120             ),
121             go.Bar(
122                 x = dd['s'].values,
123                 y = np.linspace(low, high, num=50),
124                 name = 'Sell Volume',
125                 orientation = 'h',
126                 opacity = 1,
127                 marker = dict(
128                     color = 'rgba(255, 0, 0)'
129                 )
130             ),
131             go.Bar(
132                 x = total_vol.index,
133                 y = total_vol,
134                 name = 'Volume',
135                 opacity = 0.6,
136                 marker = dict(
137                     color = 'rgba(22, 166, 166)'
138                 ),
139                 xaxis = "x2",
140                 yaxis = "y2"
141             ),
142             go.Bar(
143                 x = sell_vol.index,
144                 y = sell_vol,
145                 name = 'Sell Volume',
146                 opacity = 1,
147                 marker = dict(
148                     color = 'rgba(255, 0, 0)'
149                 ),
150                 xaxis = "x2",
151                 yaxis = "y2"
152             ),
153             go.Pie(
154                 name = "exchange volume",
155                 labels=['gdax', 'bitfinex', 'binance', 'huobi', 'okex'],
156                 values = [
157                     df[df['e'] == 0]['v'].sum(),
158                     df[df['e'] == 1]['v'].sum(),
159                     df[df['e'] == 2]['v'].sum(),
160                     df[df['e'] == 3]['v'].sum(),
161                     df[df['e'] == 5]['v'].sum()
162 
163                 ],
164                 domain = {
165                     'x':[0.7, 1],
166                     'y':[0.5, 1]
167                 }
168             ),
169             go.Pie(
170                 name = "SVR",
171                 labels=['Sell', 'Toval'],
172                 values = [
173                     st, vt
174                 ],
175                 domain = {
176                     'x':[0.7, 1],
177                     'y':[0, 0.5]
178                 }
179             )
180         ],
181         'layout' : {
182             title= 'SVR 300 seconds',
183             height = 480,
184             width= 1440,
185             xaxis= {
186                 'title': 'Size XBT',
187                 "anchor": "x",
188                 "domain": [0, 0.35]
189             },
190             yaxis= {
191                 'title': 'Price',
192                 "anchor": "x",
193                 "domain": [0, 1],
194             },
195             xaxis2= {
196                 'title': 'Time',
197                 "anchor": "x",
198                 "domain": [0.35, 0.7]
199             },
200             yaxis2= {
201                 'title': 'Size XBT',
202                 "anchor": "x2",
203                 "domain": [0, 1],
204             },
205             barmode= 'overlay'
206         }
207     }
208 
209 def draw(yr):
210     df = pd.read_csv(
211         'https://raw.githubusercontent.com/plotly/'
212         'datasets/master/gapminderDataFiveYear.csv')
213     filtered_df = df[df.year == yr]
214     traces = []
215     for i in filtered_df.continent.unique():
216         df_by_continent = filtered_df[filtered_df['continent'] == i]
217         traces.append(go.Scatter(
218             x=df_by_continent['gdpPercap'],
219             y=df_by_continent['lifeExp'],
220             text=df_by_continent['country'],
221             mode='markers',
222             opacity=0.7,
223             marker={
224                 'size': 15,
225                 'line': {'width': 0.5, 'color': 'white'}
226             },
227             name=i
228         ))
229 
230     return {
231         'data': traces,
232         'layout': go.Layout(
233             xaxis={'type': 'log', 'title': 'GDP Per Capita'},
234             yaxis={'title': 'Life Expectancy', 'range': [20, 90]},
235             margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
236             legend={'x': 0, 'y': 1},
237             hovermode='closest'
238         )
239     }
240 
241 @app.callback(Output('graph-16', 'figure'),
242               [Input('trigger-16', 'n_intervals')])
243 def update_graph_live(n):
244     return compose_graph(configs['300s'])
245 
246 @app.callback(Output('graph-15', 'figure'),
247               [Input('trigger-15', 'n_intervals')])
248 def update_graph_live(n):
249     return draw(1977)
250                     
251 if __name__ == '__main__':
252     app.run_server(
253             debug=True,
254             host='0.0.0.0',
255             threaded=True)
256