Related
I'm trying to plot certain values using dash as a bar chart but use a separate column to map the colors. Using below, I'm plotting dates as a bar-chart that corresponds to a drop down bar.
Is it possible to keep the dates as the x-axis but use DOW (day of the week) as a discrete color map? I'll attach the current output below. The dates get plotted but there are a few issues.
The string formatting for each date in the dropdown isn't in date time
The color map isn't sequenced to the day of the week
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
import plotly.express as px
import plotly.graph_objs as go
import pandas as pd
from datetime import datetime as dt
df = pd.DataFrame({
'Type': ['A','B','B','B','C','C','D','E','E','E','E','F','F','F'],
})
N = 30
df = pd.concat([df] * N, ignore_index=True)
df['TIMESTAMP'] = pd.date_range(start='2022/01/01 07:30', end='2022/01/30 08:30', periods=len(df))
df['TIMESTAMP'] = pd.to_datetime(df['TIMESTAMP'], dayfirst = True).sort_values()
df['DATE'], df['TIME'] = zip(*[(d.date(), d.time()) for d in df['TIMESTAMP']])
df['DATE'] = pd.to_datetime(df['DATE'])
df = df.sort_values(by = 'DATE')
df['DOW'] = df['DATE'].dt.weekday
df = df.sort_values('DOW').reset_index(drop=True)
df['DOW'] = df['DATE'].dt.day_name()
external_stylesheets = [dbc.themes.SPACELAB, dbc.icons.BOOTSTRAP]
app = dash.Dash(__name__, external_stylesheets = external_stylesheets)
filter_box = html.Div(children=[
html.Div(children=[
html.Label('Day of the week:', style={'paddingTop': '2rem'}),
dcc.Dropdown(
id='DATE',
options=[
{'label': x, 'value': x} for x in df['DATE'].unique()
],
value=df['DATE'].unique(),
multi=True
),
], className="four columns",
style={'padding':'2rem', 'margin':'1rem'} )
])
app.layout = dbc.Container([
dbc.Row([
dbc.Col(html.Div(filter_box, className="bg-secondary h-100"), width=2),
dbc.Col([
dbc.Row([
dbc.Col(dcc.Graph(id = 'date-bar-chart'),
),
]),
], width=5),
])
], fluid=True)
#app.callback(
Output('date-bar-chart', 'figure'),
[Input("DATE", "value"),
])
def date_chart(date):
dff = df[df['DATE'].isin(date)]
count = dff['DATE'].value_counts()
data = px.bar(x = count.index,
y = count.values,
#color = dff['DOW'],
)
layout = go.Layout(title = 'Date')
fig = go.Figure(data = data, layout = layout)
return fig
if __name__ == '__main__':
app.run_server(debug=True, port = 8051)
Not sure why do you want to use DATE as Dropdown but I think you should change it to string and then pass it to dcc.Dropdown. Used the previous way to add color_discrete_map I think you can revise your code as below:
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
import plotly.express as px
import plotly.graph_objs as go
import pandas as pd
from datetime import datetime as dt
from dash.exceptions import PreventUpdate
df = pd.DataFrame({
'Type': ['A','B','B','B','C','C','D','E','E','E','E','F','F','F'],
})
N = 30
df = pd.concat([df] * N, ignore_index=True)
df['TIMESTAMP'] = pd.date_range(start='2022/01/01 07:30', end='2022/01/30 08:30', periods=len(df))
df['TIMESTAMP'] = pd.to_datetime(df['TIMESTAMP'], dayfirst = True).sort_values()
df['DATE'], df['TIME'] = zip(*[(d.date(), d.time()) for d in df['TIMESTAMP']])
df['DATE'] = pd.to_datetime(df['DATE'],format='%Y-%m-%d')
df = df.sort_values(by = 'DATE')
df['DOW'] = df['DATE'].dt.weekday
df = df.sort_values('DOW').reset_index(drop=True)
df['DOW'] = df['DATE'].dt.day_name()
df['DATE'] = df['DATE'].astype(str)
df['Color'] = df['DOW'].map(dict(zip(df['DOW'].unique(),
px.colors.qualitative.Plotly[:len(df['DOW'].unique())])))
Color = df['Color'].unique()
Category = df['DOW'].unique()
Color = df['Color'].unique()
Category = df['DOW'].unique()
cats = dict(zip(Category,Color))
external_stylesheets = [dbc.themes.SPACELAB, dbc.icons.BOOTSTRAP]
app = dash.Dash(__name__, external_stylesheets = external_stylesheets)
filter_box = html.Div(children=[
html.Div(children=[
html.Label('Day of the week:', style={'paddingTop': '2rem'}),
dcc.Dropdown(
id='DATE',
options=[
{'label': x, 'value': x} for x in df['DATE'].unique()
],
value=df['DATE'].unique(),
multi=True
),
], className="four columns",
style={'padding':'2rem', 'margin':'1rem'} )
])
app.layout = dbc.Container([
dbc.Row([
dbc.Col(html.Div(filter_box, className="bg-secondary h-100"), width=2),
dbc.Col([
dbc.Row([
dbc.Col(dcc.Graph(id = 'date-bar-chart'),
),
]),
], width=5),
])
], fluid=True)
#app.callback(
Output('date-bar-chart', 'figure'),
[Input("DATE", "value"),
])
def date_chart(date):
if date:
dff = df[df['DATE'].isin(date)]
count = dff.groupby(['DATE',"DOW"])['DATE'].count().reset_index(name='counts')
data = px.bar(x = count['DATE'],
y = count['counts'],
color = count['DOW'],
color_discrete_map = cats,
)
layout = go.Layout(title = 'Date')
fig = go.Figure(data = data, layout = layout)
return fig
else:
raise PreventUpdate
if __name__ == '__main__':
app.run_server(debug=False, port = 8051)
I used groupby in callback to return new dataframe and then use it to make graph. Hope this help.
I'm creating a fitness chart using Plotly Dash that allows a user to enter a weight, which saves the data to an excel file, and then the user can refresh the screen to update the graph. I've been able to do them seperately by only having one function under the app.callback section. How can I have both functions? I can make the graph OR I can collect the input and refresh, but not both. Here's a sample of the data I'm using.
And here's the MVP code I'm trying to use.
import openpyxl
import dash
from dash import html, dcc, Input, Output, State
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
app = dash.Dash(__name__)
app.layout = html.Div([
dcc.Input(id='weight', placeholder='Enter Your Weight', type='text'),
html.Button(id='submit-button', type='submit', children='Submit'),
html.A(html.Button('Refresh'), href='/'),
dcc.Graph(
id='chart')
])
#app.callback(Output('chart', 'figure'),
[Input('submit-button', 'n_clicks')],
[State('weight', 'value')],
)
def display_time_series(n_clicks, input_value):
xlsx = pd.read_excel('Weight Tracker.xlsx')
df = xlsx
fig = px.line(df, x="DATE", y="ACTUAL WEIGHT")
fig.add_trace(
go.Scatter(x=df['DATE'], y=df['HIGH ESTIMATE'], name="HIGH ESTIMATE", line=dict(color="green", dash="dash")),
secondary_y=False,
)
fig.add_trace(
go.Scatter(x=df['DATE'], y=df['LOW ESTIMATE'], name="LOW ESTIMATE", line=dict(color="red", dash="dash")),
secondary_y=False,
)
if n_clicks is not None:
wb = openpyxl.load_workbook('Weight Tracker.xlsx')
sheet = wb.active
# Finds the last open row in Column B or the 'Actual Weight' Column
last_empty_entry = max((b.row for b in sheet['B'] if b.value is not None)) + 1
c1 = sheet.cell(row=last_empty_entry, column=2)
c1.value = int(input_value)
wb.save("Weight Tracker.xlsx")
print("Excel has been saved.")
return fig
if __name__ == '__main__':
app.run_server(debug=True)
Here's the error I'm getting and the graph doesn't display and the input button doesn't do anything.
Cannot read properties of null (reading 'data')
at f.value (http://127.0.0.1:8050/_dash-component-suites/dash/dcc/async-graph.js:1:4493)
at f.value (http://127.0.0.1:8050/_dash-component-suites/dash/dcc/async-graph.js:1:9778)
at callComponentWillReceiveProps (http://127.0.0.1:8050/_dash-component-suites/dash/deps/react-dom#16.v2_3_1m1648990364.14.0.js:13111:16)
at updateClassInstance (http://127.0.0.1:8050/_dash-component-suites/dash/deps/react-dom#16.v2_3_1m1648990364.14.0.js:13313:9)
at updateClassComponent (http://127.0.0.1:8050/_dash-component-suites/dash/deps/react-dom#16.v2_3_1m1648990364.14.0.js:17242:22)
at beginWork (http://127.0.0.1:8050/_dash-component-suites/dash/deps/react-dom#16.v2_3_1m1648990364.14.0.js:18755:18)
at HTMLUnknownElement.callCallback (http://127.0.0.1:8050/_dash-component-suites/dash/deps/react-dom#16.v2_3_1m1648990364.14.0.js:182:16)
at Object.invokeGuardedCallbackDev (http://127.0.0.1:8050/_dash-component-suites/dash/deps/react-dom#16.v2_3_1m1648990364.14.0.js:231:18)
at invokeGuardedCallback (http://127.0.0.1:8050/_dash-component-suites/dash/deps/react-dom#16.v2_3_1m1648990364.14.0.js:286:33)
at beginWork$1 (http://127.0.0.1:8050/_dash-component-suites/dash/deps/react-dom#16.v2_3_1m1648990364.14.0.js:23338:9)
The main issue you're having is the callback is being called at initial start of program, so to fix this pass in prevent_initial_callbacks=True into dash app instance.
Then you need 2 separate inputs for each button and don't use an anchor for Refresh button it won't work.
import dash
from dash import html, dcc, Input, Output, State
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import datetime as dt
app = dash.Dash(__name__, prevent_initial_callbacks=True)
app.layout = html.Div([
dcc.Input(id='weight', placeholder='Enter Your Weight', type='text'),
html.Button(id='submit-button', type='submit', children='Submit'),
html.Button('Refresh', id='refresh'),
dcc.Graph(id='chart'),
html.P(children='dummy', id='dummy', hidden=True)
])
#app.callback(Output('chart', 'figure'),
[Input('refresh', 'n_clicks')],
prevent_initial_callback=True,
)
def display_time_series(n_clicks):
if n_clicks is not None:
xlsx = pd.read_excel('Weight Tracker.xlsx')
df = xlsx
fig = px.line(df, x="DATE", y="ACTUAL WEIGHT")
fig.add_trace(
go.Scatter(x=df['DATE'], y=df['HIGH ESTIMATE'], name="HIGH ESTIMATE", line=dict(color="green", dash="dash")),
secondary_y=False,
)
fig.add_trace(
go.Scatter(x=df['DATE'], y=df['LOW ESTIMATE'], name="LOW ESTIMATE", line=dict(color="red", dash="dash")),
secondary_y=False,
)
return fig
#app.callback(Output('dummy', 'children'),
[Input('submit-button', 'n_clicks')],
[State('weight', 'value')],
prevent_initial_callback=True
)
def save_new_entry(n_clicks, input_value):
if n_clicks is not None:
wb = openpyxl.load_workbook('Weight Tracker.xlsx')
sheet = wb.active
# Finds the last open row in Column B or the 'Actual Weight' Column
last_empty_entry = max((b.row for b in sheet['B'] if b.value is not None)) + 1
c0 = sheet.cell(row=last_empty_entry, column=1)
c0.value = dt.datetime.now()
c1 = sheet.cell(row=last_empty_entry, column=2)
c1.value = int(input_value)
wb.save("Weight Tracker.xlsx")
print("Excel has been saved.")
if __name__ == '__main__':
app.run_server(debug=True)
I want to create a graphical terminal like a tradingview. For this, I use plotly dash to make the display as comfortable as possible. But a situation arose that I have been unable to resolve for several days now.
Now my code looks like this:
import asyncio import datetime as DT from threading import Thread
import dash import numpy as np import plotly.graph_objs as go from dash import dcc, html from dash.dependencies import Input, Output
# ======================================================================================================================
# === Create DATA ======================================================================================================
# ======================================================================================================================
Start_Time = DT.datetime.timestamp(DT.datetime.now().replace(second=0, microsecond=0)) * 1000 X_time = np.array([]) Y_one = np.array([]) Y_two = np.array([]) Y_three = np.array([])
async def create_connection():
from random import randrange
import time
count = 0
global X_time
global Y_one
global Y_two
global Y_three
while count < 1000000:
X_time = np.append(X_time, count)
Y_one = np.append(Y_one, randrange(10000))
Y_two = np.append(Y_two, randrange(10000))
Y_three = np.append(Y_three, randrange(10000))
count += 1
time.sleep(1)
def async_main_wrapper():
"""Not async Wrapper around async_main to run it as target function of Thread"""
asyncio.run(create_connection())
# ======================================================================================================================
# === Create DASH ======================================================================================================
# ======================================================================================================================
X = np.array([0]) Y = np.array([0])
external_stylesheets = ['https://fonts.googleapis.com/css2?family=Montserrat+Alternates:wght#400;600&display=swap'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
colors = {
'background': '#FDFEFE',
'text': '#424242' }
app.layout = html.Div(style={'backgroundColor': colors['background']}, children=[
html.H1(
children='Main graph',
style={
'textAlign': 'left',
"fontFamily": "Montserrat Alternates",
"fontWeight": "600",
'color': colors['text']
}),
dcc.Graph(id='live_graph', style={'height': '700px', 'width': '100%'}, animate=True, config={'scrollZoom':True}),
dcc.Interval(
id='graph_update',
interval=1000 * 1
), ] )
def create_area(line_Y_one, line_Y_two, line_Y_three, X_time):
fig = {'data': [line_Y_one, line_Y_two, line_Y_three],
'layout': go.Layout(xaxis=dict(range=[min(X_time), max(X_time)], rangeslider=dict(visible=True)),
yaxis=dict(tickfont=dict(color='rgba(0, 188, 212, 0.0)')),
yaxis2=dict(overlaying="y", tickfont=dict(color='rgba(0, 188, 212, 0.0)')),
yaxis3=dict(overlaying="y"),
)}
return fig
#app.callback(Output('live_graph', 'figure'),
Input('graph_update', 'n_intervals')) def update_graph_scatter(graph_update):
global X_time
global Y_one
global Y_two
global Y_three
clr_green = 'rgba(139, 195, 74, '
clr_red = 'rgba(220, 20, 60, '
clr_brown = 'rgba(93, 64, 55, 1.0)'
line_Y_one = go.Scatter(
x=X_time,
y=Y_one,
name='Y_one',
line=dict(color=clr_green + '0.0)'),
fillcolor=clr_green + '0.3)',
fill='tozeroy',
yaxis='y1'
)
line_Y_two = go.Scatter(
x=X_time,
y=Y_two,
name='Y_two',
line=dict(color=clr_red + '0.0)'),
fillcolor=clr_red + '0.3)',
fill='tozeroy',
yaxis='y1'
)
line_Y_three = go.Scatter(
name='Y_three',
x=X_time,
y=Y_three,
line=dict(color=clr_brown),
yaxis='y3'
)
return create_area(line_Y_one, line_Y_two, line_Y_three, X_time)
# ======================================================================================================================
# === Start ===========================================================================================================
# ======================================================================================================================
if __name__ == '__main__':
th = Thread(target=async_main_wrapper)
th.start()
app.run_server(host='localhost', port=8080, debug=True, use_reloader=False)
th.join()
When starting the graph, everything goes well, it is updated once a second, as specified in the settings:
https://i.postimg.cc/L8yCj6Dw/normal.gif
But if I switch to another tab or window (i.e. I don't look at the chart), then when I return, the chart starts to update quickly, compressing and decompressing like a spring:
https://i.postimg.cc/BvXhp9w6/glitch.gif
How can I solve this situation?
And as an addition: could you recommend a good raftly dash guide that
will show solutions to similar problems?
I’m trying to make a live updates from mySql database but graphs did not update with new data but Stop and Re-run script. I tried to find solutions or simple code but I couldn’t find it.
Below is my code:
import pandas as pd
import numpy as np
import plotly.express as px
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
import dash_bootstrap_components as dbc
import plotly.graph_objects as go
from io import BytesIO
from wordcloud import WordCloud
import base64
import dash.dependencies as dd
import mysql.connector
db = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="indeed_data_dump"
)
cur = db.cursor()
cur.execute("SELECT * FROM jobs")
data = pd.DataFrame(cur.fetchall())
db.close()
data.rename(columns = {1:'Url',2:'Job Link',3:'Title',4:'Company',5:'Rating',6:'Location',
7:'Posted',8:'Job Description',9:'Min Salary',10:'Max Salary'}, inplace = True)
data.to_dict()
data = data[data['Max Salary'].notnull()]
jobs_2 = data[['Title','Company','Rating','Location','Max Salary']]
jobs_2['Max Salary'] = jobs_2['Max Salary'].str.replace(',','')
jobs_2['Type'] = jobs_2['Max Salary'].str[-5:]
jobs_2['Type'] = jobs_2['Type'].str.replace(' ','')
jobs_2['Max Salary'] = jobs_2['Max Salary'].str.extract('(\d+)')
jobs_2 = jobs_2.dropna(subset=['Max Salary'])
jobs_2['Max Salary'] = jobs_2['Max Salary'].astype(int)
jobs_2['Max Salary'] = np.where((jobs_2['Type'] == "year"),(jobs_2['Max Salary']/12).round(decimals=0),jobs_2['Max Salary'])
jobs_2['Max Salary'] = np.where((jobs_2['Type'] == "week"),(jobs_2['Max Salary']*4).round(decimals=0),jobs_2['Max Salary'])
app = dash.Dash(__name__,external_stylesheets=[dbc.themes.LUX])
app.layout = html.Div([
dbc.Row([
dbc.Col([
dbc.Card([
dbc.CardBody([html.H5('Average salary on each location',className='text-center'), #marks=mark_values
dcc.Graph(id='sal_location',figure={},style={'height':500,'width':'auto'}),
])
])
],width={'size':12,"offset":0,'order':1},style={'padding-left' : 25,'padding-right' : 25}),
]),
html.Hr(),
dbc.Row([
dbc.Col([
dbc.Card([
dbc.CardBody([html.H5('Top 10 Job',className='text-center'), #marks=mark_values
dcc.Graph(id='sal_top10',figure={},style={'height':600,'width':'auto'}),
])
])
],width={'size':6,"offset":0,'order':1},style={'padding-left' : 25}),
dbc.Col([
dbc.Card([
dbc.CardBody([html.H5('Average salary on star',className='text-center'), #marks=mark_values
dcc.Graph(id='sal_star',figure={},style={'height':600,'width':'auto'}),
])
])
],width={'size':6,"offset":0,'order':1},style={'padding-right' : 25}),
]),
html.Hr(),
dbc.Row([
dbc.Col([html.H5('Drop Down',className='text-center'),
dcc.Dropdown(id='location_cd_2',placeholder="Please select location",
options=[{'label':x,'value':x} for x in data.sort_values('Location')['Location'].unique()],
value='Select',
multi=False,
disabled=False,
clearable=True,
searchable=True),
],width={'size':6,"offset":0,'order':1},style={'padding-left' : 25}),
]),
html.Hr(),
dbc.Row([
dbc.Col([
dbc.Card([
dbc.CardBody([html.H5('Job on each location',className='text-center'), #marks=mark_values
dcc.Graph(id='job_location_2',figure={},style={'height':600,'width':'auto'}),
])
])
],width={'size':12,"offset":0,'order':1},style={'padding-left' : 25,'padding-right' : 25}),
]),
dbc.Row([
dbc.Col([
dbc.Card([
dbc.CardBody([html.H5('Word Cloud',className='text-center'),
html.Img(id="image_wc"),
])
])
],width={'size':12,"offset":0,'order':1},style={'padding-left' : 25,'padding-right' : 25},className='text-center'),
]),
dcc.Interval(id='update', n_intervals = 0, interval=1000*5)
])
#app.callback(
Output('sal_location', 'figure'),
[Input('update', 'n_intervals')])
def update_graph(jobs_location):
global jobs
jobs = jobs_2.copy()
jobs_location = pd.pivot_table(jobs,values=['Max Salary',],index=['Location'],aggfunc=np.mean)
jobs_location = jobs_location.reset_index()
# Fig 1
fig_1 = go.Figure(data=[
go.Bar(x=jobs_location['Location'],
y=jobs_location['Max Salary'].round(decimals=2),
width=0.45,
text = jobs_location['Max Salary'].round(decimals=2),
textposition='inside',
marker_color='indianred')])
fig_1.update_layout(barmode='stack')
fig_1.update_traces(texttemplate='%{text:,}')
fig_1.update_layout(plot_bgcolor='rgba(0,0,0,0)')
fig_1.update_yaxes(showline=False,showgrid=False,dtick=5000,exponentformat="none",separatethousands=True)
return fig_1
#app.callback(
Output('sal_top10', 'figure'),
[Input('update', 'n_intervals')])
def update_graph_2(top_10):
global job_cloud
jobs['Rating'].fillna(0,inplace=True)
jobs_title = pd.pivot_table(jobs,values=['Max Salary',],index=['Title'],aggfunc=np.mean)
jobs_title = jobs_title.reset_index()
top_10 = jobs_title.sort_values(['Max Salary'], ascending=[False]).head(10)
top_10 = top_10.sort_values(['Max Salary'], ascending=[True])
job_cloud = jobs.groupby(["Title"])["Title"].count().reset_index(name="count")
# Fig 3
fig_3 = px.bar(top_10, x="Max Salary", y="Title", orientation='h')
fig_3.update_traces(marker_color='#E8788C')
fig_3.update_layout(plot_bgcolor='white',xaxis_title='',yaxis_title='')
fig_3.update_yaxes(showline=False,showgrid=False,exponentformat="none",separatethousands=True)
fig_3.update_xaxes(showline=False,showgrid=False,exponentformat="none",separatethousands=True)
return fig_3
#app.callback(
Output('sal_star', 'figure'),
[Input('update', 'n_intervals')])
def update_graph_3(jobs_rating):
jobs_rating = pd.pivot_table(jobs,values=['Max Salary',],index=['Rating'],aggfunc=np.mean)
jobs_rating = jobs_rating.reset_index()
fig_2 = go.Figure(data=[
go.Bar(x=jobs_rating['Rating'],
y=jobs_rating['Max Salary'].round(decimals=2),
width=0.45,
text = jobs_rating['Max Salary'].round(decimals=2),
textposition='inside',
marker_color='lightsalmon')])
fig_2.update_layout(barmode='stack')
fig_2.update_traces(texttemplate='%{text:,}')
fig_2.update_layout(plot_bgcolor='rgba(0,0,0,0)')
fig_2.update_yaxes(showline=False,showgrid=False,dtick=5000,exponentformat="none",separatethousands=True)
fig_2.update_xaxes(type='category')
return fig_2
#app.callback(Output('job_location_2', 'figure'),
[Input('location_cd_2', 'value'),
Input('update', 'n_intervals')])
def build_graph(location_code,dff_2):
if not location_code or 'Select' in location_code:
dff_2 = pd.pivot_table(jobs,values=['Max Salary',],index=['Location','Title'],aggfunc=np.mean).reset_index()
dff_2 = dff_2[(dff_2['Location']=='Kuala Lumpur')]
else:
dff_2 = pd.pivot_table(jobs,values=['Max Salary',],index=['Location','Title'],aggfunc=np.mean).reset_index()
dff_2 = dff_2[(dff_2['Location'] == location_code)]
fig_4 = go.Figure(data=[
go.Bar(x=dff_2['Title'],
y=dff_2['Max Salary'].round(decimals=2),
width=0.45,
text = dff_2['Max Salary'].round(decimals=2),
textposition='inside',
marker_color='lightsalmon')])
fig_4.update_layout(barmode='stack')
fig_4.update_traces(texttemplate='%{text:,}')
fig_4.update_layout(plot_bgcolor='rgba(0,0,0,0)')
fig_4.update_yaxes(showline=False,showgrid=False,dtick=20000,exponentformat="none",separatethousands=True)
fig_4.update_xaxes(type='category')
return fig_4
def plot_wordcloud(data):
d = {a: x for a, x in data.values}
wc = WordCloud(background_color='white', width=1080, height=360)
wc.fit_words(d)
return wc.to_image()
#app.callback(dd.Output('image_wc', 'src'), [dd.Input('image_wc', 'id')])
def make_image(b):
img = BytesIO()
plot_wordcloud(data=job_cloud).save(img, format='PNG')
return 'data:image/png;base64,{}'.format(base64.b64encode(img.getvalue()).decode())
if __name__ == "__main__":
app.run_server(debug=False,port=1215)
This code worked good with csv files but didn't update data from mySql.
What should I change for my code or could you give me a sample code? Thank you.
I am trying to make a graph with Dash. When I copy the examples in Plotly it works fine, but when I change some variables with my values and run it then all the elements appear except for the graph.
This is the code:
app = dash.Dash(__name__)
app.layout = html.Div([
dcc.Graph(id='graph-with-slider'),
dcc.Slider(
id='year-slider',
min=subset_date['Year'].unique().min(),
max=subset_date['Year'].unique().max(),
value=subset_date['Year'].unique().min(),
step=None
)
])
#app.callback(
Output('graph-with-slider', 'figure'),
[Input('year-slider', 'value')])
def update_figure(selected_year):
return {
'data': go.Scatter(x=subset_date.index,
y=subset_date['Value'],
mode='lines'),
'layout': go.Layout(
title='My Title'
)
}
if __name__=='__main__':
app.run_server()
What am I doing wrong?
Here is a simple app layout:
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.graph_objs as go
# Step 1. Launch the application
app = dash.Dash()
# Step 2. Import the dataset
# Scimago Journal & Country Rank
# from www.scimagojr.com
st = {'Date': ['2008-01-01', '2009-01-01', '2010-01-01', '2011-01-01', '2012-01-01', '2013-01-01', '2014-01-01', '2015-01-01', '2016-01-01','2017-01-01', '2018-01-01'],
# 'Turkey': [26526, 30839, 33325, 34926, 36766, 40302, 41400, 44529, 47138, 44584,45582],
'Iran': [20006, 24509, 30013, 39682, 41513, 42252, 44923, 45013, 52538, 56029, 60268]
}
st = pd.DataFrame(st)
# range slider options
st['Date'] = pd.to_datetime(st.Date)
dates = ['2008-01-01', '2009-01-01', '2010-01-01', '2011-01-01', '2012-01-01', '2013-01-01', '2014-01-01', '2015-01-01', '2016-01-01','2017-01-01', '2018-01-01']
# Step 3. Create a plotly figure
trace_1 = go.Scatter(x = st.Date, y = st['Iran'],
name = 'Iran',
line = dict(width = 2,
color = 'rgb(229, 151, 50)'))
layout = go.Layout(title = 'Scimago Journal & Country Rank (Iran)',
hovermode = 'closest')
fig = go.Figure(data = [trace_1], layout = layout)
# Step 4. Create a Dash layout
app.layout = html.Div([
# adding a plot
dcc.Graph(id = 'plot', figure = fig),
# range slider
dcc.RangeSlider(id = 'slider',
marks = {i : dates[i] for i in range(0, 11)},
min = 0,
max = 10,
value = [1, 7])
])
# Step 5. Add callback functions
#app.callback(Output('plot', 'figure'),
[
Input('slider', 'value')])
def update_figure( input2):
# filtering the data
st2 = st[(st.Date > dates[input2[0]]) & (st.Date < dates[input2[1]])]
# updating the plot
trace_1 = go.Scatter(x = st2.Date, y = st2['Iran'],
name = 'Iran',
# mode = 'markers'
line = dict(width = 2,
color = 'rgb(229, 151, 50)'))
fig = go.Figure(data = [trace_1], layout = layout)
return fig
# Step 6. Add the server clause
if __name__ == '__main__':
app.run_server(debug = False)