- Print
- DarkLight
Chart
- Print
- DarkLight
Chart
BUILD leverages the Plotly library to generate charts. We suggest using Plotly Express with Panda DataFrame to quickly create common charts.
Here's a reference to the types of charts available.
Overview
Here's a quick summary of how a Plotly chart is created and rendered:
Import plotly and set up the custom theme with our utility function.
import plotly
import plotly.express as px
import plotly.io as pio
import plotly.graph_objects as go
from sm_udf.app_builder.util import setup_plotly_theme
setup_plotly_theme()
In Page Logic, we query SQL and create a Pandas DataFrame:
df.We use Python plotly.express to create the plotly figure i.e.
fig = px.bar(df, ....)We use
plotly.utils.PlotlyJSONEncoderto convertfiginto JSON.We return the JSON to the Frontend JavaScript plotly to render.
Example
# === Bar Chart UI Panel ===
# Create the Bar Chart UI Panel from the SQL/DataFrame output
# ==========================
# check if no data returns
if df.empty:
fig_json = None
else:
# create the bar chart, passing in df.
# df in this example contains "Day", "Output" and "Shift" columns
fig = px.bar(
df,
x='Day',
y='Output',
color="Shift"
)
# use update_layout to specify layout details.
fig.update_layout(
xaxis=dict(
tickformat='%Y-%m-%d',
tickvals=df['Day'],
tickmode='array'
)
)
# convert fig to json
fig_json = json.loads(json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder))
# create the panel and pass fig_json to viz_props
chart_panel = {
"id": "plotly-chart",
"viz_type": "plotly",
"viz_props": fig_json,
"title": {
"value": "Bar Chart",
"font-size": 16,
"align": "left",
"margin": "13px 13px 13px 13px",
},
}
The above example generates this bar chart:
.png)
Page Linking
To add page linking to a chart (selecting a point to go to another page), we add link_mapping to the fig_json:
# === Create Page Link Mapping ===
link_mapping = {
'page_id': 'sample_app_table',
'mapping': {
'asset': 'asset',
'dateRange': 'dateRange',
'filter': 'filter',
}
}
fig_json['link_mapping'] = link_mappingThis will enable linking when a point on the chart is selected:
.png)
More details here: Page Linking
fig.show('iframe')
In Page Logic (Jupyter notebook), by running fig.show('iframe') the notebook will generate the chart inline. Use this for quicker development when testing specific chart configurations. Make sure to remove it once configured to keep the notebook clean.
.png)