Save chart as image from dash at start - python-3.x

I have some charts generated through Dash and I would like these charts to be saved at Dash server start.
app.layout = html.Div(
children=[
dcc.Graph(
id='serious-chart',
style={
"width": '1000px',
'height': '500px',
}
),
],style={'position':'absolute',
'width':'160vh',
'height':'55vh',
'top': '142%',
'left': '50%',
'border': '1px solid black',
'border-radius':'10px',
"transform": "translate(-50%, -50%)",
}
)
#app.callback(
Output(component_id='serious-chart',component_property='figure'),
Input(component_id='input-bar',component_property='value'),
)
def returnCharts(value):
""" some code here """
if __name__ == '__main__':
app.run_server(debug=True)
Need some code to save Figure 'serious-chart' as jpeg or Png.

Related

Python Altair, query for current axis limits

I know how to set axis limits and whatnot, but how do I query for currently used axis limits?
I don't think this is possible unless you specifically set an axis limit first:
import altair as alt
from vega_datasets import data
source = data.cars.url
chart = alt.Chart(source).mark_circle().encode(
x='Horsepower:Q',
y='Miles_per_Gallon:Q',
)
chart.to_dict()
{'config': {'view': {'continuousWidth': 400, 'continuousHeight': 300}},
'data': {'url': 'https://cdn.jsdelivr.net/npm/vega-datasets#v1.29.0/data/cars.json'},
'mark': 'circle',
'encoding': {'x': {'field': 'Horsepower', 'type': 'quantitative'},
'y': {'field': 'Miles_per_Gallon', 'type': 'quantitative'}},
'$schema': 'https://vega.github.io/schema/vega-lite/v5.2.0.json'}
If you set the domain, you can see it in the spec:
chart = alt.Chart(source).mark_circle().encode(
x=alt.X('Horsepower:Q', scale=alt.Scale(domain=[0, 250])),
y='Miles_per_Gallon:Q',
)
chart.to_dict()
{'config': {'view': {'continuousWidth': 400, 'continuousHeight': 300}},
'data': {'url': 'https://cdn.jsdelivr.net/npm/vega-datasets#v1.29.0/data/cars.json'},
'mark': 'circle',
'encoding': {'x': {'field': 'Horsepower',
'scale': {'domain': [0, 250]},
'type': 'quantitative'},
'y': {'field': 'Miles_per_Gallon', 'type': 'quantitative'}},
'$schema': 'https://vega.github.io/schema/vega-lite/v5.2.0.json'}
and get it via chart.to_dict()['encoding']['x']['scale']['domain'].

How to pass the dataframe along list in dash framework?

I'm trying to pass the data frame and selected property of a dropdown to the different calling function in dash. I'm able to pass selected value but i don't get data frame. Here is my code.
"""Visualization graph"""
import os
from flask import Flask
import dash
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 pandas as pd
DIRECTORY_PATH = 'C:/Users/fortu/Desktop/Zuhair/'
directories = [
d for d in (os.path.join(DIRECTORY_PATH, directories) for directories in
os.listdir(DIRECTORY_PATH))
if os.path.isdir(d)
]
external_stylesheets = [
'https://js.api.here.com/v3/3.1/mapsjs-ui.css'
]
# Normally, Dash creates its own Flask server internally. By creating our own,
# we can create a route for downloading files directly:
server = Flask(__name__)
app = dash.Dash(__name__,
external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = html.Div(
[
dbc.Row(dbc.Col(
html.Div("Ground truth visualization",
style={'textAlign': 'center',
'color': 'red', 'fontSize': '40px'}),
md=12)),
dbc.Row(
dbc.Col(
html.Div([
dbc.Row([
dbc.Col(html.Div(dbc.Row(dcc.Dropdown(
id='selected-dir',
options=[{'label': i, 'value': i}
for i in directories],
placeholder="Select the directory"),
style={
'marginLeft': '25px',
'display': 'inline-block',
'width': '90%'
}
)), width=2),
dbc.Col(children=[
html.Div(dbc.Row(dcc.Dropdown(
id='selected-csv-fields',
placeholder="Select the field"),
style={
'display': 'inline-block',
'width': '90%'
}
)),
html.Div(dbc.Row(id='intermediate-value'), style={'display': 'none'})
], width=2),
]),
dbc.Row([
dbc.Col(html.Div([
dbc.Row(
[dbc.Col(html.Div(
dcc.Graph(id='line-graph'),
className='bg-dark badge-dark'))]),
dbc.Row([dbc.Col(html.Div(
dcc.Graph(id='stack-graph'),
className='bg-warning'))],
className="row mt-3")]), width=5)
], className="row mt-3")]))
)
]
)
#app.callback(
[Output("selected-csv-fields", "options"),
Output("intermediate-value", "data")],
[Input("selected-dir", "value")]
)
def get_all_csv(selector):
"""Get all the csv from the folder"""
if selector is not None:
csv_files = list(filter(lambda x: '.csv' in x, os.listdir(selector)))
_DF = pd.concat([pd.read_csv(os.path.join(selector, f))
for f in csv_files])
demo = [{'label': i, 'value': i} for i in _DF]
return demo, _DF
return []
#app.callback(
Output("line-graph", "figure"),
Output("stack-graph", "figure"),
[Input("selected-csv-fields", "value"), Input("intermediate-value", "data")]
)
def update_graph(selector, done):
"""display the graph based on selected value."""
if selector is not None:
fig = px.line(done, x="Time", y=selector)
stack = px.histogram(done, x="Time", y=selector, marginal="box",
hover_data=done)
return fig, stack
return {}, {}
if __name__ == "__main__":
app.run_server(debug=True)
When I remove the Output("intermediate-value", "data")] from get_all_csv() and Input("intermediate-value", "data") from update_graph(a, b) respectively it works fine. but when try to pass this parameters it gives me error
ERROR :
Callback error updating selected-csv-fields.options, intermediate-value.data

Create a modal when clicking on barchart with dash plotly

I have a bar chart and I would like to create a Modal when I click on them. Do you know how I can handle that? I tried something but nothing appears.
I knew how to do it with a datatable. But here I have a bar chart, I added a Modal object at the end of the design but I can't make it appear despite.
Here is a minimal reproducible example:
import dash
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd
from dash.dependencies import Input, Output
df = pd.read_excel("https://github.com/chris1610/pbpython/blob/master/data/salesfunnel.xlsx?raw=True")
pv = pd.pivot_table(df, index=['Name'], columns=["Status"], values=['Quantity'], aggfunc=sum, fill_value=0)
trace1 = go.Bar(x=pv.index, y=pv[('Quantity', 'declined')], name='Declined')
trace2 = go.Bar(x=pv.index, y=pv[('Quantity', 'pending')], name='Pending')
trace3 = go.Bar(x=pv.index, y=pv[('Quantity', 'presented')], name='Presented')
trace4 = go.Bar(x=pv.index, y=pv[('Quantity', 'won')], name='Won')
app = dash.Dash()
app.layout = html.Div(children=[
html.H1(children='Sales Funnel Report'),
html.Div(children='''National Sales Funnel Report.'''),
dcc.Graph(
id='graph',
figure={
'data': [trace1, trace2, trace3, trace4],
'layout':
go.Layout(title='Order Status by Customer', barmode='stack')
}),
dbc.Modal(
[
dbc.ModalHeader("Header"),
dbc.ModalBody("This is the content of the modal"),
dbc.ModalFooter(
dbc.Button("Close", id="close", className="ml-auto")
),
],
size="xl",
id="modal",
)
])
#app.callback(
Output('modal', 'children'),
[Input('graph', 'clickData')])
def display_click_data(clickData):
print("clickData: ", clickData)
return [
dbc.ModalHeader("Test"),
dbc.ModalBody(
html.Div([
html.Div([
html.H6('Sales', style={'textAlign': 'center', 'padding': 10}),
html.P("Bitch", id="sales_stocks", style={'textAlign': 'center', 'padding': 10})
], className='pretty_container four columns'),
html.Div([
html.H5('Current ratio', style={'textAlign': 'center', 'padding': 10})
], className='pretty_container seven columns')
])),
dbc.ModalFooter(dbc.Button("Close", id="close"))
]
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
app.run_server(debug=True)
I encountered a similar question, but conceptually the same: click on something in a plotly/dash-object and then display a modal. Researching the issue, I also found this post on the plotly forum, which encounters very similar problems. The proposed solution there gave me the idea on how to solve.
There are 2 issues at hand if I copy your code.
its missing the link to the bootstrap "external stylesheet" which can be easily added in your sample above, replacing app = dash.Dash() with app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])
the call back now only alters the modal's children. However, to be displayed, it's attribute, open should be set to True. When the button, with id=close is pressed, the open be altered to False.
I worked your code snipped out into something working. Hope this helps you out as well!
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd
# added State to be used in callbacks
from dash.dependencies import Input, Output, State
# using #type: ignore to suppress warnings in my editor (vs code).
df = pd.read_excel("https://github.com/chris1610/pbpython/blob/master/data/salesfunnel.xlsx?raw=True")
pv = pd.pivot_table(df, index=['Name'], columns=["Status"], values=['Quantity'], aggfunc=sum, fill_value=0)#type: ignore
trace1 = go.Bar(x=pv.index, y=pv[('Quantity', 'declined')], name='Declined') #type: ignore
trace2 = go.Bar(x=pv.index, y=pv[('Quantity', 'pending')], name='Pending')#type: ignore
trace3 = go.Bar(x=pv.index, y=pv[('Quantity', 'presented')], name='Presented')#type: ignore
trace4 = go.Bar(x=pv.index, y=pv[('Quantity', 'won')], name='Won')#type: ignore
app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = html.Div(children=[
html.H1(children='Sales Funnel Report'),
html.Div(children='''National Sales Funnel Report.'''),
dcc.Graph(
id='graph',
figure={
'data': [trace1, trace2, trace3, trace4],
'layout':
go.Layout(title='Order Status by Customer', barmode='stack')#type: ignore
}),
dbc.Button("toggle", id="open"),
dbc.Modal(
[
dbc.ModalHeader("Header",id = 'modalheader'),
dbc.ModalBody("This is the content of the modal"),
dbc.ModalFooter(
dbc.Button("Close", id="close", className="ml-auto")
),
],
size="xl",
id="modal",
)
])
#app.callback([Output("modal", "children"),
Output("modal", "is_open")],
[Input("graph", "clickData"),
Input("close", "n_clicks")],
[State("modal", "is_open"),
State("modal", "children")])
def set_content(value,clicked,is_open,children):
ctx = dash.callback_context
if ctx.triggered[0]['prop_id'] == 'close.n_clicks':
# you pressed the closed button, keeping the modal children as is, and
# close the model itself.
return children, False
elif ctx.triggered[0]['prop_id'] == 'graph.clickData':
# you clicked in the graph, returning the modal children and opening it
return [dbc.ModalHeader("Test"),
dbc.ModalBody(
html.Div([
html.Div([
html.H6('Sales', style={'textAlign': 'center', 'padding': 10}),
html.P("Bitch", id="sales_stocks", style={'textAlign': 'center', 'padding': 10})
], className='pretty_container four columns'),
html.Div([
html.H5('Current ratio', style={'textAlign': 'center', 'padding': 10}),
html.P(str(value),style = {'fontFamily':'monospace'})
], className='pretty_container seven columns')
])),
dbc.ModalFooter(dbc.Button("Close", id="close"))
], True
else:
raise dash.exceptions.PreventUpdate
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
app.run_server(debug=True)

Dash application is not running on gunicorn nginx wsgi sever

I've developed one dash application for my data in Flask framework. The code is running on Local Server. But when I run this on production by using Gunicorn wsgi by configuring Nginx server, I'm not getting any results.
The project directory looks like follows:
flask_application
| static
|-
| templates
|- home.html
| app.py
| wsgi.py
I'm using Centos7 ssh connected by Putty. Here is the code which I'm trying to execute on wsgi server and the command used for running the application.
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objs as go
from flask import Flask, render_template
import pandas as pd
server = Flask(__name__)
app = dash.Dash(__name__, server=server)
#app.route("/")
def home_conf():
return render_template("home.html")
df= pd.read_csv('my_dataframe.csv')
df= df[1:]
features = df.columns
df_types= features[1:] #don't want the Customer column
app.layout = html.Div([
html.Div([
#Here is the interactive component
html.Div([
dcc.Dropdown(
id='yaxis',
options=[{'label':i,'value':i} for i in
df_types],
value='df-type'
)
], style={'width': '60%'})
]),
html.Div([dcc.Graph(
id='df-graphic',
figure={
'data': [go.Scatter(
x=df['Lender'],
y=[0,0],
mode='markers'
)],
'layout': go.Layout(
title = 'Use the dropdown to display the chart ...',
xaxis={'tickformat': 'd'}
)
}
)
], style={'width':'70%', 'display':'inline-block'}),
html.Div([dcc.Graph(
id='df-stacked',
figure={
'data': [go.Bar(
x=df['Lender'],
y=df['Login'],
name='Login'
),
go.Bar(
x=df['Lender'],
y=df['Approved'],
name='Approved'
),
go.Bar(
x=df['Lender'],
y=df['Reject'],
name='Reject'
),
go.Bar(
x=df['Lender'],
y=df['Agreement'],
name='Agreement'
),
go.Bar(
x=df['Lender'],
y=df['Disbursed'],
name='Disbursed'
),
go.Bar(
x=df['Lender'],
y=df['Cancelled'],
name='Cancelled'
),
],
'layout': go.Layout(
title ='Customer Count in the finance from August, 2019',
barmode='stack'
)
}
)
], style={'width':'70%', 'display':'inline-block'}),
html.Div([dcc.Graph(
id='df-boxplot',
figure={
'data': [go.Box(
y=df['Login'],
name='Login'
),
go.Box(
y=df['Approved'],
name='Approved'
),
go.Box(
y=df['Reject'],
name='Reject'
),
go.Box(
y=df['Agreement'],
name='Agreement'
),
go.Box(
y=df['Disbursed'],
name='Disbursed'
),
go.Box(
y=df['Cancelled'],
name='Cancelled'
),
],
'layout': go.Layout(
title='Customer Count in the Finance, August 2019'
)
}
)
], style={'width':'70%', 'display':'inline-block'}),
html.Div([
dcc.Markdown(children=markdown_text)
])
], style={'padding':10})
#Here is the callback
#app.callback(
Output('df-graphic', 'figure'),
[Input ('yaxis', 'value')])
def update_graphic(yaxis_lbit):
return {
'data': [go.Scatter(
x=df['Lender'],
y=df[yaxis_lbit],
mode='lines+markers',
marker={
'size': 15,
'opacity': 0.5,
'line': {'width':0.5, 'color':'white'}
}
)],
'layout': go.Layout(
title='{} in the Finance by Customer Count,
August 2019'.format(yaxis_lbit),
xaxis={'title': 'Lender'},
yaxis={'title': yaxis_lbit},
hovermode='closest'
)
}
if __name__ == '__main__':
app.run_server(host='0.0.0.0', debug=True)
The following is the command which I'm using for running the application in WSGi after connecting to centos ssh.
gunicorn app:app
Can anyone explain why I'm not getting the results after executing in wsgi server and what changes will be needed in the code. Any help would be greatly appreciated. Thank you.
You are running dash app inside flask server.
Try gunicorn app:server
Similarly, you should change your "if mean" statement

Why is dashboard created using Dash not working?

I'm trying to create a Dashboard using Dash, a python package. It is either taking too much of time to execute or throws an error saying "error in loading dependencies".
I'm running it on Jupyter notebook on IE browser.
Could anyone explain me, where I'm going wrong?
Thanks all in advance.
I've tried running a sample code from "https://www.datacamp.com/community/tutorials/learn-build-dash-python"
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd
df= pd.read_excel("https://github.com/chris1610/pbpython/blob/master/data/salesfnnel.xlsx?raw=True")
mgr_options = df["Manager"].unique()
app = dash.Dash()
app.layout = html.Div([
html.H2("Sales Funnel Report"),
html.Div(
[
dcc.Dropdown(
id="Manager",
options=[{
'label': i,
'value': i
} for i in mgr_options],
value='All Managers'),
],
style={'width': '25%',
'display': 'inline-block'}),
dcc.Graph(id='funnel-graph'),
])
#app.callback(
dash.dependencies.Output('funnel-graph', 'figure'),
[dash.dependencies.Input('Manager', 'value')])
def update_graph(Manager):
if Manager == "All Managers":
df_plot = df.copy()
else:
df_plot = df[df['Manager'] == Manager]
pv = pd.pivot_table(
df_plot,
index=['Name'],
columns=["Status"],
values=['Quantity'],
aggfunc=sum,
fill_value=0)
trace1 = go.Bar(x=pv.index, y=pv[('Quantity', 'declined')], name='Declined')
trace2 = go.Bar(x=pv.index, y=pv[('Quantity', 'pending')], name='Pending')
trace3 = go.Bar(x=pv.index, y=pv[('Quantity', 'presented')], name='Presented')
trace4 = go.Bar(x=pv.index, y=pv[('Quantity', 'won')], name='Won')
return {
'data': [trace1, trace2, trace3, trace4],
'layout':
go.Layout(
title='Customer Order Status for {}'.format(Manager),
barmode='stack')
}
if __name__ == '__main__':
app.run_server(debug=True, use_reloader = False)
Error in loading dependencies.

Resources