Hey, I’m trying to scale down the size of the graphs and tables. I’m using Dashbootstrap to help me accomplish mobile responsiveness. I haven’t been able to figure out how to scale my dashboard elements down. For example, my tables and graphs take up the whole screen, on every device.
Here is my code for reference:
from django_plotly_dash import DjangoDash
import dash
import dash_table as dt
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
import plotly.graph_objs as go
from dash.exceptions import PreventUpdate
import pandas as pd
from .connect import *
from .dash_tables import *
stock_ids = execute_query(conn, "SELECT DISTINCT id FROM security_price;")
stock_ids = [i[0] for i in stock_ids]
options = [{'label': i, 'value': i} for i in stock_ids]
app = DjangoDash('StockBuckets', add_bootstrap_links=True, external_stylesheets=[dbc.themes.LUX], meta_tags=[
{"name": "viewport", "content": "width=device-width, initial-scale=1"}])
body = html.Div(
[dbc.Jumbotron(
[
dbc.Container(dcc.Dropdown(id="dynamic-dropdown", options=options, multi=True, placeholder="Select a Symbol"),
fluid=True
)
],
style = {'background-color': '#69D8AA'}, fluid=True,
)
, dbc.Row(dbc.Col(html.Div(children = [dcc.Graph(id='output-graph', config={'displayModeBar': False}, animate=True)], style={'padding': 10})))
, dbc.Row([
dbc.Col(html.Div(id='table-stats', style={'padding': 5}),width=4)
, dbc.Col(html.Div(id='table-change', style={'padding': 5}),width=8),
], justify="center",)
# , dbc.Row([
# dbc.Col(html.Div(id='table-stats', style={'padding': 50,'display':'blocl', 'width':'33%', 'margin-left':'0', 'margin-right':'0'}), width = 6)], justify="center")
# , dbc.Row([
# dbc.Col(html.Div(id='table-change', style={'padding': 50, 'display':'blocl', 'width':'33%', 'margin-left':'0', 'margin-right':'0'}), width = 6)], justify="center")
, dbc.Row(dbc.Col(html.Div(dbc.Alert("This is one column", color="primary", style={'margin-top' : '25px' ,'margin-bot' : '25px'}))),style={'margin-left' : '25px' ,'margin-right' : '25px'}, justify="center")
,
])
app.layout = html.Div([body])
@app.callback(
dash.dependencies.Output('output-graph', 'figure'),
[dash.dependencies.Input('dynamic-dropdown', 'value')])
def tickers(symbols):
conn.rollback()
if symbols == None:
raise PreventUpdate
elif symbols == '':
raise PreventUpdate
trace1 = [] #lines for stocks
d = {} #dates
p = {} #prices
stock_info = {}
df = pd.DataFrame()
for stock in symbols:
stock_info[stock] = get_dict_resultset(f"SELECT date, close FROM security_price WHERE security_price.id = '{stock}' ;")
d[stock] = [rec['date'] for rec in stock_info[stock]]
p[stock] = [rec['close'] for rec in stock_info[stock]]
trace1.append(go.Scatter(x=d[stock],
y=p[stock],
mode='lines',
opacity=0.7,
name=stock,
textposition='bottom center'))
traces = [trace1]
data = [val for sublist in traces for val in sublist]
figure = {'data': data,
'layout': go.Layout(
colorway=["#5E0DAC", '#FF4F00', '#375CB1', '#FF7400', '#FFF400', '#FF0056'],
paper_bgcolor='rgba(0, 0, 0, 0)',
plot_bgcolor='rgba(0, 0, 0, 0)',
margin={'b': 15},
hovermode='x',
autosize=True,
title={'text': 'Stock Prices', 'font': {'color': 'black'}, 'x': 0.5},
#xaxis={'range': [df_sub.index.min(), df_sub.index.max()]},
),
}
return figure
@app.callback(
dash.dependencies.Output('table-stats', 'children'),
[dash.dependencies.Input('dynamic-dropdown', 'value')])
def statsTable(symbols):
conn.rollback()
if symbols == None:
conn.rollback()
raise PreventUpdate
placeholders = ", ".join(['%s' for _ in symbols])
# PREPARED STATEMENT WITH PARAM PLACEHOLDERS
sql = f"""SELECT id, marketcap, week52high, week52low
, to_char(dividend_yield * 100, '99D99%%')
, pe_ratio, ROUND(beta,2)
FROM security_stats
WHERE security_stats.id IN ({placeholders})
"""
print(sql)
df = postgresql_to_dataframe_v1(conn, sql, symbols, stats_col)
columns =[{"name": i, "id": i} for i in df.columns]
data_dict = df.to_dict('records')
return dt.DataTable(data=data_dict, columns=columns, style_as_list_view=True,
style_cell={'padding': '5px'},
style_header={
'backgroundColor': 'white',
'fontWeight': 'bold'
},
style_cell_conditional=[
{
'if': {'column_id': c},
'textAlign': 'left'
} for c in ['Symbol']
]
)
@app.callback(
dash.dependencies.Output('table-change', 'children'),
[dash.dependencies.Input('dynamic-dropdown', 'value')])
def changeTable(symbols):
print(symbols)
if symbols == None:
conn.rollback()
raise PreventUpdate
conn.rollback()
placeholders = ", ".join(['%s' for _ in symbols])
# PREPARED STATEMENT WITH PARAM PLACEHOLDERS
sql = f"""SELECT id, to_char(100.0*ytd_changepercent,'999D99%%'), to_char(100.0*day5_changepercent,'999D99%%'), to_char(100.0*day30_changepercent,'999D99%%')
, to_char(100.0*month3_changepercent,'999D99%%'), to_char(100.0*month6_changepercent,'999D99%%'), to_char(100.0*year1_changepercent,'999D99%%')
, to_char(100.0*year2_changepercent,'999D99%%'),to_char(100.0*year5_changepercent,'999D99%%')
FROM security_stats
WHERE security_stats.id IN ({placeholders})
"""
print(sql)
df = postgresql_to_dataframe_v1(conn, sql, symbols, change_col)
columns =[{"name": i, "id": i} for i in df.columns]
data_dict = df.to_dict('records')
return dt.DataTable(data=data_dict, columns=columns, style_as_list_view=True,
style_cell={'padding': '5px', 'overflowX': 'hidden', 'textOverflow': 'ellipsis', 'maxWidth': '25px', },
style_header={
'backgroundColor': 'white',
'fontWeight': 'bold'
},
style_cell_conditional=[
{
'if': {'column_id': c},
'textAlign': 'left'
} for c in ['Symbol']
]
)
# ,style_cell={
# 'overflowX': 'hidden',
# 'textOverflow': 'ellipsis',
# 'maxWidth': '25px',
# 'textAlign': 'left'
# }
# , style_table={
# 'maxHeight': '550px'
# #,'maxWidth': '800px'
# ,'overflowY': 'scroll'
# ,'overflowX': 'hidden'
There are many cases in my dashboard why I need the elements smaller than normal. Look at this line of code:
, dbc.Row([
dbc.Col(html.Div(id='table-stats', style={'padding': 5}),width=4)
, dbc.Col(html.Div(id='table-change', style={'padding': 5}),width=8),
], justify="center",)
This row is meant to fit two tables, but instead the tables seem to “overlap” eachother:
How can I scale down my graphs and tables, most importantly to fit other screen?