Hi All,
I am integrating Dash in Django using django-plotly-dash library. The code I am using to fetch graphs using Dash is as follows:
# import libraries
from dash import dcc, html
import dash
from django_plotly_dash import DjangoDash
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd
# create dash app
app = DjangoDash("TestSample", external_scripts=['https://cdn.plot.ly/plotly-basic-2.18.2.min.js'],
external_stylesheets=[dbc.themes.BOOTSTRAP],)
# read data from database
testData = pd.read_sql(read from source database)
# create app layout
app.layout = dbc.Container([
dbc.Row(
dbc.Col(html.H1('Test'), class_name='text-center text-primary-mb-4', width=12)
),
dbc.Row([
dbc.Col([
dbc.Label('Select category'),
], xs=12, sm=12, md=6, lg=3, xl=3),
dbc.Col([
dcc.Dropdown(
options=[{'label': x, 'value': x} for x in testData['category'].unique()] + [
{'label': 'Select all', 'value': 'all'}],
value='all',
multi=False,
clearable=False,
id="category-select",
)
], xs=12, sm=12, md=6, lg=3, xl=3),
]),
dbc.Row([
dbc.Col([
dcc.Graph(
id="category-by-date",
figure={},
)
], xs=12, sm=12, md=12, lg=6, xl=6),
]),
])
# create callbacks to display charts
@app.callback(
Output('category-by-date', 'figure'),
Input('category-select', 'value'),
)
# function to update chart as per selection value
def update_chart(selectedCategory):
if selectedCategory == 'all':
data = testData
else:
data = testData.loc[testData['category'] == selectedCategory]
categoryCountData = data.groupby(['category'], sort=False).size()
categoryCountData = categoryCountData.reset_index(name="count")
print(categoryCountData)
fig = px.bar(categoryCountData, 'category', 'count', title='Category count', template='simple_white')
fig.show()
return fig
The above code displays graph correctly when I use fig.show() but when returned through the function to html page, the values on y-axis are index values instead of values in ‘Category’ column.
Can you someone please help me understand where am I going wrong.
Note: The Dash graphs created works well without Django integration.