### Install visualization_toolkit via pip
Source: https://visualization-toolkit-docs.yipit.systems/index
This snippet shows the command to install the visualization_toolkit using pip. Ensure Jfrog is configured in your environment for access. This is the standard method for installing the library in a general Python project.
```bash
pip install visualization_toolkit
```
--------------------------------
### Install visualization_toolkit via pip
Source: https://visualization-toolkit-docs.yipit.systems/_sources/index.rst
Installs the visualization_toolkit package using pip. This command is typically run in a bash or terminal environment. Ensure Jfrog is configured in your environment for access.
```bash
pip install visualization-toolkit
```
--------------------------------
### Download Full Example Code
Source: https://visualization-toolkit-docs.yipit.systems/recipes/axes/plot_numerical_axis_tick_format
Provides a link to download the complete example code for numerical axis tick format customization.
```HTML
Go to the end
```
--------------------------------
### Python Visualization Example
Source: https://visualization-toolkit-docs.yipit.systems/_sources/recipes/styling/plot_atlas_chart_theme.rst
This section is intended for Python code examples related to visualization. The provided text indicates the start of a Python code block, but no actual code was found.
```Python
# Python code snippet placeholder
# No code was provided in the input text.
```
--------------------------------
### Setup Datadog APM Tracing
Source: https://visualization-toolkit-docs.yipit.systems/dash
Initializes Datadog APM tracing for the Dash application. This function enables performance monitoring through Datadog.
```APIDOC
visualization_toolkit.helpers.dash.setup_datadog()
- Initialize datadog APM tracing of the dash app.
- Returns: None
```
--------------------------------
### Setup Celery App for Dash Background Callbacks
Source: https://visualization-toolkit-docs.yipit.systems/dash
Initializes a Celery application, essential for enabling background callbacks in Dash applications. This setup is generally preferred for production Dash deployments. It returns the configured Celery app instance and a Celery manager, both utilized in background callback functionalities.
```APIDOC
visualization_toolkit.helpers.dash.setup_celery_app(_name_ , _broker_uri_ , _results_backend_uri =None_, _celery_app_kwargs =None_, _celery_manager_kwargs =None_)
Initializes a Celery application for Dash background callbacks.
Parameters:
- name (_str_): Celery application name.
- broker_uri (_str_): Redis URI to use as the Celery broker.
- results_backend_uri (_str_, optional): URI to use as the Celery results backend. Defaults to `broker_uri`. Supports Redis or PostgreSQL.
- celery_app_kwargs (_dict_, optional): Additional keyword arguments to pass to the Celery app constructor.
- celery_manager_kwargs (_dict_, optional): Additional keyword arguments to pass to the Celery manager.
Returns:
tuple: A tuple containing the Celery app instance (celery.Celery) and the Celery callback manager (dash.CeleryManager).
Example:
import uuid
from visualization_toolkit.helpers.dash import setup_celery_app
from visualization_toolkit.constants import APP_ENVIRONMENT
launch_uid = str(uuid.uuid4())
celery_app, celery_app_manager = setup_celery_app(
name=__name__,
broker_uri=APP_ENVIRONMENT.get("REDIS_URI"),
celery_manager_kwargs={
"cache_by": [lambda: launch_uid],
},
)
```
```python
import uuid
from visualization_toolkit.helpers.dash import setup_celery_app
from visualization_toolkit.constants import APP_ENVIRONMENT
# Use a different cache_by logic based on the needs of the dash application
launch_uid = str(uuid.uuid4())
celery_app, celery_app_manager = setup_celery_app(
name=__name__,
broker_uri=APP_ENVIRONMENT.get("REDIS_URI"),
celery_manager_kwargs={
"cache_by": [lambda: launch_uid],
},
)
```
--------------------------------
### Celery Application Setup
Source: https://visualization-toolkit-docs.yipit.systems/dash
Configures and initializes a Celery application, which is a distributed task queue system. This function is essential for setting up background task processing.
```APIDOC
setup_celery_app()
- Initializes and configures the Celery application.
- Returns: A configured Celery application instance.
```
--------------------------------
### Basic Area Chart Example
Source: https://visualization-toolkit-docs.yipit.systems/_sources/recipes/area_chart/index.rst
Demonstrates the creation of a basic area chart. Area charts are useful for showing trends over time and can be stacked to represent parts of a whole.
```python
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.arange(10)
y1 = np.sin(x)
y2 = np.cos(x)
# Create figure and axes
fig, ax = plt.subplots()
# Plot the first area
ax.fill_between(x, 0, y1, alpha=0.5, label='Sine Wave')
# Plot the second area, stacked on top of the first
ax.fill_between(x, y1, y1 + y2, alpha=0.5, label='Cosine Wave (Stacked)')
# Add labels and title
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_title('Basic Area Chart Example')
ax.legend()
# Show the plot
plt.show()
```
--------------------------------
### Setup Sentry Tracking for Dash Apps
Source: https://visualization-toolkit-docs.yipit.systems/dash
Initializes Sentry tracking for exceptions in a Dash app. Connects via the `SENTRY_DSN` environment variable. Handles optional environment client.
```APIDOC
visualization_toolkit.helpers.dash.setup_sentry(_env =None_, _env_var ='SENTRY_DSN')
- Initializes sentry tracking of exceptions. Will connect to sentry via the `SENTRY_DSN` variable set in the app environment.
- Parameters:
- env (_envelop.Environment_): Enveleop Environment client to use. Defaults to the libraries `APP_ENVIRONMENT`. Generally not needed to be set.
- env_var (_str_): Environment variable name that stores the sentry dsn. Defaults to `SENTRY_DSN`.
- Returns: None
```
--------------------------------
### Shade Positive and Negative Regions
Source: https://visualization-toolkit-docs.yipit.systems/_sources/recipes/chart_context/index.rst
Call out positive or negative areas within a chart, especially for growth rate visualizations. This is achieved using the shade_y instance and specifying the appropriate start, end, and color.
```python
This example demonstrates shading positive and negative regions in a chart. It utilizes the `shade_y` instance to define shaded areas based on value ranges and specified colors. This is particularly useful for visualizing growth rates or performance trends.
```
--------------------------------
### System Monitoring Setup Functions
Source: https://visualization-toolkit-docs.yipit.systems/_sources/dash.rst
Helper functions to set up production monitoring for Dash applications, essential for cloud deployments. These include integrations with Sentry, Datadog, and health check services.
```APIDOC
setup_sentry
Configures Sentry for error tracking and monitoring.
setup_datadog
Configures Datadog for application performance monitoring.
setup_healthcheck
Sets up a health check endpoint for the Dash application.
```
--------------------------------
### Set Date Axis Intervals
Source: https://visualization-toolkit-docs.yipit.systems/_sources/recipes/axes/index.rst
Charts tick intervals are automatically sized by the relevant axis' start and end values and calculating a reasonable number of ticks. However, many visualizations might be presented better with specific tick intervals given the use case. In these situations, a tick_interval can be specified as an axis argument.
```Python
# Example code for setting date axis intervals.
# This snippet is a placeholder as the actual code was not provided in the input.
# For example:
# fig, ax = plt.subplots()
# ax.plot(dates, values)
# ax.xaxis.set_major_locator(mdates.DayLocator(interval=5))
# plt.show()
```
--------------------------------
### Get Databricks Spark Session
Source: https://visualization-toolkit-docs.yipit.systems/_modules/visualization_toolkit/helpers/dash/databricks
Creates and manages a PySpark SparkSession for Databricks, supporting both Databricks Connect and Databricks app presets. It includes logic for session restarting based on a time-based cache marker to ensure session health. Environment variables like YDBC_DEPLOYMENT_NAME and OAuth credentials are used for local/CI setups.
```python
import logging
import pandas as pd
from datetime import datetime
from pyspark.sql import SparkSession
from databricks.connect import DatabricksSession
# Assume APP_ENVIRONMENT, cache, get_setting_from_environment, ydbc_get_spark_session are defined elsewhere
logger = logging.getLogger(__name__)
def get_spark_session() -> SparkSession:
"""
Create a ``pyspark.SparkSession`` to execute queries on databricks via spark-connect.
This should be used when pyspark is necessary for a data app and comes with trade-offs:
- pyspark is more powerful in generating transformations dynamically
- spark-connect however has less caching and concurrency capabilities than databricks SQL.
- spark-connect can also be more costly than databricks SQL.
To use a pyspark session locally, set ``YDBC_DEPLOYMENT_NAME``, ``YDBC_OAUTH_CLIENT_ID``, and ``YDBC_OAUTH_SECRET`` as environment variables.
These are typically set via infisical by the Platform Engineering team.
:return:
"""
def _get_spark_session():
if APP_ENVIRONMENT.get_bool("ATLAS_IS_DATABRICKS_APP", False):
# Use databricks app preset credentials to create a session
return DatabricksSession.builder.serverless(True).getOrCreate()
else:
# Fetch the SparkSession via Databricks Connect
# Following environment variables are required in CircleCI:
# - YDBC_DEPLOYMENT_NAME
# - YDBC_CLUSTER_ID (classic only)
# - YDBC_OAUTH_CLIENT_ID
# - YDBC_OAUTH_SECRET
return ydbc_get_spark_session(
serverless=hasattr(DatabricksSession.builder, "serverless"),
deployment_name=get_setting_from_environment("YDBC_DEPLOYMENT_NAME"),
)
# Use databricks app preset credentials to create a session
spark = _get_spark_session()
# Restart spark session every 600 seconds by checking
# if the cache has a timestamp marker for the last time the session was restarted
spark_timestamp = cache.get("SPARK_SESSION_TIMESTAMP")
now = datetime.utcnow()
if not spark_timestamp:
print("Restarting spark session after 600 seconds ..")
spark.stop()
spark = _get_spark_session()
cache.set(
"SPARK_SESSION_TIMESTAMP",
now.isoformat(),
timeout=600,
)
return spark
```
--------------------------------
### Generate Basic Waterfall Chart
Source: https://visualization-toolkit-docs.yipit.systems/_sources/recipes/waterfall_chart/plot_waterfall_chart.rst
This snippet shows how to generate a waterfall chart. It requires specifying data points as totals, additions, or subtractions using the 'series' parameter. Customization of the y-axis is possible via 'y1_axis'. The 'data' parameter expects a single row with columns for each adjustment type, and 'total' defines the starting and ending values.
```python
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "recipes/waterfall_chart/plot_waterfall_chart.py"
.. LINE NUMBERS ARE GIVEN BELOW.
.. only:: html
.. note::
:class: sphx-glr-download-link-note
:ref:`Go to the end `
to download the full example code.
.. rst-class:: sphx-glr-example-title
.. _sphx_glr_recipes_waterfall_chart_plot_waterfall_chart.py:
Basic Waterfall Chart
---------------------------
Generate a waterfall chart using the ``waterfall_chart`` function. Waterfall charts can show the net result of a starting value after a series of positive/negative adjustments.
- ``series`` must be used to specify data points that are the starting ending ``totals``, incremental ``additions``, and incremental ``subtractions``
- The ``y1_axis`` can be used to customize y-axis behavior
- ``data`` must be a single row with each column representing a total, addition, or subtraction
- ``total`` must be two series each representing the starting value and ending value respectively
.. GENERATED FROM PYTHON SOURCE LINES 14-51
```
```javascript
window.PLOTLYENV=window.PLOTLYENV || {}; if (document.getElementById("2986fc60-c864-4cb5-bd22-a0b65a155c8d")) {
Plotly.newPlot(
"2986fc60-c864-4cb5-bd22-a0b65a155c8d",
[{"connector":{"line":{"color":"rgb(158, 158, 158)","width":1}},"decreasing":{"marker":{"color":"#f48d5c"}},"increasing":{"marker":{"color":"#abd0d9"}},"measure":["absolute","relative","relative","relative","absolute"],"orientation":"v","text":["$186,994","$36,691","$-36,489","$-40,530","$146,656"],"textposition":"auto","totals":{"marker":{"color":"#0d4753"}},"x":["Prior Period","Expansion","Contraction","Churn","Ending Period"],"y":[186994,36691,-36489,-40530,146656],"type":"waterfall"}],
{"template":{"data":{"histogram2dcontour":[{...}],"choropleth":[{...}],"histogram2d":[{...}],"heatmap":[{...}],"contourcarpet":[{...}],"contour":[{...}],"surface":[{...}],"mesh3d":[{...}],"scatter":[{...}],"parcoords":[{...}]}}}
);
}
```
--------------------------------
### Plot Positive and Negative Regions with Visualization Toolkit
Source: https://visualization-toolkit-docs.yipit.systems/recipes/chart_context/plot_positive_negative_regions
Demonstrates shading positive (green) and negative (red) regions on a chart using the visualization toolkit's `shade_y` function. This Python example requires pandas and the toolkit's charting utilities to visualize Y/Y Growth Rate data, setting specific start and end points for the shaded areas.
```python
import pandas as pd
from visualization_toolkit.helpers.plotly import chart, axis, series, shade_y
fig = chart(
pdf,
x_axis=axis(column_name="fiscal_qy", label="Fiscal Quarter"),
chart_series=[
series(
column_name="yy",
label="Y/Y Growth Rate",
color="black",
location="y1",
shape="dash",
),
],
y1_axis=axis(label="Growth Rate", axis_type="percent", axis_min=-0.2, axis_max=0.2),
shaded_regions=[
shade_y(
start=-0.2,
end=0,
color="red",
),
shade_y(
start=0,
end=0.2,
color="green",
),
],
)
fig
```
--------------------------------
### Initialize Pendo Callback
Source: https://visualization-toolkit-docs.yipit.systems/_modules/visualization_toolkit/helpers/dash/analytics
Registers a client-side callback to initialize the Pendo session with user data. It reads a JavaScript template, renders it with debug parameters, and attaches it to a Dash app.
```python
import os
import json
from dash import Dash, Output, Input, State
# Assuming LIBRARY_PATH, JINJA_ENVIRONMENT, ATLAS_DEBUG are defined elsewhere
# from your_module import LIBRARY_PATH, JINJA_ENVIRONMENT, ATLAS_DEBUG
def initializePendoCallback(app: Dash, user_store_id: str, debug: bool = False):
"""
Client Side callback to initialize the Pendo session.
:param app: Dash app to register the client side callback
:param user_store_id: HTML ID of the user store that contains user/account information to initialize Pendo client. Must be associated with a ``dcc.Store`` component.
:param debug: When ``True``, the client side callback will log additional information to the browser console. By default, this is ``False`` and should not be used outside of development.
:return:
"""
with open(
os.path.join(LIBRARY_PATH, "templates/pendo/initializePendoCallback.js")
) as f:
clientside_script = (
JINJA_ENVIRONMENT.from_string(f.read())
.render(parameters={"debug": debug})
.strip()
)
app.clientside_callback(
clientside_script,
Output(user_store_id, "modified_timestamp"),
Input(user_store_id, "data"),
)
```
--------------------------------
### Setup Datadog APM Tracing
Source: https://visualization-toolkit-docs.yipit.systems/_modules/visualization_toolkit/helpers/dash/monitoring
Initializes Datadog APM (Application Performance Monitoring) tracing for the Dash application. It configures the Datadog tracer with the application's IP address and patches all relevant libraries for automatic instrumentation.
```python
import logging
import os
from urllib3 import Retry
import requests
logger = logging.getLogger(__name__)
def setup_datadog():
"""
Initialize datadog APM tracing of the dash app.
:return:
"""
if ATLAS_ENABLE_DATADOG:
from ddtrace import tracer
from ddtrace import patch_all
DD_PRIVATE_IP = get_aws_ip()
tracer.configure(hostname=DD_PRIVATE_IP)
patch_all()
```
--------------------------------
### Pendo Initialization Callback
Source: https://visualization-toolkit-docs.yipit.systems/_modules/visualization_toolkit/helpers/dash/analytics
Provides a client-side callback function to initialize a Pendo session within a Dash application. Once initialized, other client-side callbacks can be triggered to send Pendo events, leveraging the data from the user_store component.
```python
fromdashimport dcc, Dash, Input, Output, State
fromvisualization_toolkit.constantsimport (
ATLAS_USER_STORE_ID,
ATLAS_DEBUG,
)
defpendo_initialize_callback(
app: Dash, user_store_id: str = ATLAS_USER_STORE_ID, debug: bool = ATLAS_DEBUG
):
"""
Client Side callback to initialize a Pendo session. Once the session is initialized other client-side callbacks
to send Pendo events can be executed. This should be used in conjunction with the ``user_store`` component. The data from
"""
# The actual implementation of the callback logic is missing in the provided snippet.
```
--------------------------------
### Plotly Plot Configuration Examples
Source: https://visualization-toolkit-docs.yipit.systems/_sources/recipes/line_chart/plot_line_chart_with_shaded_bounds.rst
This section provides examples of common plot configurations used in visualization libraries, demonstrating how to define plot types, color scales, and layout properties.
```json
{
"data": [
{
"type": "choropleth",
"colorscale": [
[0.0, "#0d0887"],
[0.1111111111111111, "#46039f"],
[0.2222222222222222, "#7201a8"],
[0.3333333333333333, "#9c179e"],
[0.4444444444444444, "#bd3786"],
[0.5555555555555556, "#d8576b"],
[0.6666666666666666, "#ed7953"],
[0.7777777777777778, "#fb9f3a"],
[0.8888888888888888, "#fdca26"],
[1.0, "#f0f921"]
],
"colorbar": {
"outlinewidth": 0,
"ticks": ""
}
},
{
"type": "histogram2d",
"colorscale": [
[0.0, "#0d0887"],
[0.1111111111111111, "#46039f"],
[0.2222222222222222, "#7201a8"],
[0.3333333333333333, "#9c179e"],
[0.4444444444444444, "#bd3786"],
[0.5555555555555556, "#d8576b"],
[0.6666666666666666, "#ed7953"],
[0.7777777777777778, "#fb9f3a"],
[0.8888888888888888, "#fdca26"],
[1.0, "#f0f921"]
],
"colorbar": {
"outlinewidth": 0,
"ticks": ""
}
},
{
"type": "heatmap",
"colorscale": [
[0.0, "#0d0887"],
[0.1111111111111111, "#46039f"],
[0.2222222222222222, "#7201a8"],
[0.3333333333333333, "#9c179e"],
[0.4444444444444444, "#bd3786"],
[0.5555555555555556, "#d8576b"],
[0.6666666666666666, "#ed7953"],
[0.7777777777777778, "#fb9f3a"],
[0.8888888888888888, "#fdca26"],
[1.0, "#f0f921"]
],
"colorbar": {
"outlinewidth": 0,
"ticks": ""
}
},
{
"type": "scatter",
"fillpattern": {
"fillmode": "overlay",
"size": 10,
"solidity": 0.2
}
},
{
"type": "bar",
"error_x": {
"color": "#2a3f5f"
},
"error_y": {
"color": "#2a3f5f"
},
"marker": {
"line": {
"color": "#E5ECF6",
"width": 0.5
},
"pattern": {
"fillmode": "overlay",
"size": 10,
"solidity": 0.2
}
}
},
{
"type": "histogram",
"marker": {
"pattern": {
"fillmode": "overlay",
"size": 10,
"solidity": 0.2
}
}
},
{
"type": "pie",
"automargin": true
}
],
"layout": {
"annotations": [
{
"align": "left",
"arrowcolor": "#444444",
"arrowhead": 0,
"arrowsize": 0.5,
"arrowwidth": 1,
"bgcolor": "rgba(255,255,255,0)",
"bordercolor": "rgba(255,255,255,0)",
"borderwidth": 0,
"font": {
"color": "#444444",
"family": "Roboto,system-ui,sans-serif",
"size": 16
},
"showarrow": false,
"valign": "middle"
}
],
"colorway": [
"#0d4753",
"#abd0d9",
"#f48d5c",
"#288b6f",
"#f4bb01",
"#e9514e",
"#19889F",
"#f8bca0",
"#61d1b1",
"#fedd71",
"#ef8280",
"#daeff2",
"#000000",
"#999999"
],
"font": {
"color": "#444444",
"family": "Roboto,system-ui,sans-serif",
"size": 16
},
"height": 610,
"hoverlabel": {
"align": "left",
"bgcolor": "rgba(255,255,255,1)",
"bordercolor": "#F5F5F5",
"font": {
"color": "#444444",
"family": "Roboto,system-ui,sans-serif",
"size": 16
}
},
"legend": {
"bordercolor": "rgba(255,255,255,0)",
"font": {
"color": "#444444",
"family": "Roboto,system-ui,sans-serif",
"size": 16
},
"grouptitlefont": {
"color": "#444444",
"family": "Roboto,system-ui,sans-serif",
"size": 16
},
"orientation": "h",
"title": {
"font": {
"color": "#444444",
"family": "Roboto,system-ui,sans-serif",
"size": 16
}
}
}
}
}
```
--------------------------------
### System Monitoring Setup Functions
Source: https://visualization-toolkit-docs.yipit.systems/dash
Provides functions to integrate various system monitoring and health check services into the application. This includes setting up Sentry for error tracking, Datadog for performance monitoring, and a basic health check endpoint.
```APIDOC
setup_sentry()
- Configures the application to send error reports to Sentry.
setup_datadog()
- Configures the application for Datadog integration, enabling metrics and tracing.
setup_healthcheck()
- Sets up a health check endpoint for monitoring application status.
```
--------------------------------
### Create Waterfall Chart
Source: https://visualization-toolkit-docs.yipit.systems/_modules/visualization_toolkit/helpers/plotly/charts/waterfall
Generates a Waterfall chart to summarize the effects of multiple positive or negative adjustments to a starting and ending balance. The chart automatically styles additions and subtractions, ensuring the starting value from totals equals the ending value. Data can be provided as a DataFrame, Pandas DataFrame, or a list of dictionaries. Requires exactly two 'totals' series for the starting and ending balances.
```Python
fromtypingimport Any, Optional
fromplotlyimport graph_objs as go
frompyspark.sqlimport DataFrame
importpandasaspd
fromvisualization_toolkit.exceptionsimport InvalidInputException
fromvisualization_toolkit.helpers.plotly.charts.core.figureimport generate_base_figure
fromvisualization_toolkit.helpers.plotly.charts.core.chartimport (
_normalize_input_data_to_pandas,
)
fromvisualization_toolkit.helpers.plotly.charts.core.seriesimport Series
fromvisualization_toolkit.helpers.plotly.charts.core.axisimport Axis
fromvisualization_toolkit.helpers.plotly.colorsimport resolve_color
fromvisualization_toolkit.helpers.plotly.themeimport (
YD_CLASSIC_THEME,
ATLAS_TICK_COLOR,
)
[docs][](https://visualization-toolkit-docs.yipit.systems/plotly.html#visualization_toolkit.helpers.plotly.waterfall_chart)
defwaterfall_chart(
df: DataFrame | pd.DataFrame | list[dict[str, Any]],
y1_axis: Axis,
totals: list[Series] = None,
additions: list[Series] = None,
subtractions: list[Series] = None,
theme: dict = YD_CLASSIC_THEME,
) -> go.Figure:
"""
Create a Waterfall chart that can summarize the effects of multiple positive or negative adjustments to a starting and ending balance.
The chart will automatically style ``additions`` and ``subtractions`` series so that the starting value from ``totals`` equals the ending value of ``totals``.
Data must be provided as a single row where the columns indicate the starting and ending totals along with any adjustments that are to be plotted.
:param df: Input data to visualize. The columns from this data will be used for the ``totals``, ``additions``, and ``subtractions`` series and the ``y1_axis``.
:param y1_axis: The ``axis`` that the balances are plotted on
:param totals: Two ``series`` containing the starting and ending balance for the data. The order matters so pass in the totals in the correct order.
:param additions: Any number of ``series`` indicating positive adjustments to the starting balance.
:param subtractions: Any number of ``series`` indicating negative adjustments to the starting balance.
:param theme: Optionally changes the theme used to format the chart. Defaults to the ``YD_CLASSIC_THEME`` if not set.
:return:
Examples
^^^^^^^^^^^^^^
.. code-block:: python
:caption: Example of creating a waterfall chart. Notice the shape of data that is used. It is acceptable to pass data as a dataframe, pandas dataframe, or a single-item list of dictionaries.
from visualization_toolkit.helpers.plotly import waterfall_chart, axis, series
data = [
{
"prior_period": 186994,
"expansion": 36691,
"contraction": -36489,
"churn": -40530,
"ending_period": 146656,
}
]
fig = waterfall_chart(
data,
y1_axis=axis(label="Spend", axis_type="currency"),
totals=[
series(
column_name="prior_period",
label="Prior Period",
),
series(
column_name="ending_period",
label="Ending Period",
),
],
additions=[
series(
column_name="expansion",
label="Expansion",
),
],
subtractions=[
series(
column_name="contraction",
label="Contraction",
),
series(
column_name="churn",
label="Churn",
),
],
)
display(fig)
"""
totals = totals or []
additions = additions or []
subtractions = subtractions or []
if len(totals) != 2:
raise InvalidInputException("2 total series must be provided")
pdf = _normalize_input_data_to_pandas(df)
data = pdf.to_dict("records")[0]
x = []
measure = []
y = []
x.append(totals[0].resolved_label)
y.append(data[totals[0].column_name])
measure.append("absolute")
for series_item in additions:
x.append(series_item.resolved_label)
y.append(data[series_item.column_name])
measure.append("relative")
for series_item in subtractions:
x.append(series_item.resolved_label)
y.append(data[series_item.column_name])
measure.append("relative")
x.append(totals[1].resolved_label)
y.append(data[totals[1].column_name])
measure.append("absolute")
axis_min, axis_max = _get_axis_range(
data,
totals=totals,
additions=additions,
subtractions=subtractions,
)
fig = generate_base_figure(theme=theme)
y1_axis.axis_min = axis_min
y1_axis.axis_max = axis_max
```
```Python
from visualization_toolkit.helpers.plotly import waterfall_chart, axis, series
data = [
{
"prior_period": 186994,
"expansion": 36691,
"contraction": -36489,
"churn": -40530,
"ending_period": 146656,
}
]
fig = waterfall_chart(
data,
y1_axis=axis(label="Spend", axis_type="currency"),
totals=[
series(
column_name="prior_period",
label="Prior Period",
),
series(
column_name="ending_period",
label="Ending Period",
),
],
additions=[
series(
column_name="expansion",
label="Expansion",
),
],
subtractions=[
series(
column_name="contraction",
label="Contraction",
),
series(
column_name="churn",
label="Churn",
),
],
)
display(fig)
```
--------------------------------
### Setup Datadog RUM Tracking
Source: https://visualization-toolkit-docs.yipit.systems/_modules/visualization_toolkit/helpers/dash/monitoring
Initializes Datadog Real User Monitoring (RUM) for the Dash application's browser-side interactions. It injects JavaScript snippets to enable RUM tracking and user identification, requiring specific IDs for user stores and locations.
```python
import logging
import os
from dash import Dash, Input, Output
from envelop import Environment
logger = logging.getLogger(__name__)
def setup_datadog_rum(
app: Dash,
user_store_id: str = ATLAS_USER_STORE_ID,
location_id: str = ATLAS_LOCATION_ID,
debug: bool = ATLAS_DEBUG,
):
"""
Initialize datadog RUM tracking of the dash app on the browser. Requires adding ``user_store`` and ``location_store`` to the dash app.
:param app: Dash app to enable RUm on
:param user_store_id: ID of user store that user information will exist in. Defaults to ``ATLAS_USER_STORE_ID``.
:param location_id: Environment variable name that stores the sentry dsn. Defaults to ``USE_DATADOG``.
:param debug: If True, additional logging will be included in the client side callbacks to debug in the browser.
:return:
"""
if ATLAS_ENABLE_DATADOG:
# initialize DD rum client via the browser
with open(
os.path.join(LIBRARY_PATH, "templates/datadog/initializeDDRum.js")
) as f:
init_script = JINJA_ENVIRONMENT.from_string(f.read()).render(
parameters={
"debug": debug,
"dd_client_token": DATADOG_CLIENT_TOKEN,
"dd_application_id": DATADOG_APPLICATION_ID,
"dd_service_name": DATADOG_SERVICE_NAME,
"dd_environment": DATADOG_ENVIRONMENT,
}
)
app.clientside_callback(
init_script,
Input(location_id, "href"),
)
# Then register a callback to register the user once DD rum is initialized and user is authenticated
with open(os.path.join(LIBRARY_PATH, "templates/datadog/ddRumSetUser.js")) as f:
user_script = JINJA_ENVIRONMENT.from_string(f.read()).render(
parameters={
"debug": debug,
}
)
app.clientside_callback(
user_script,
Input(user_store_id, "data"),
)
```
--------------------------------
### Date Axis for Bar Charts
Source: https://visualization-toolkit-docs.yipit.systems/_sources/recipes/axes/index.rst
Axes in general work the same way independent of what type of mode a series is. For example, a bar chart can be used with a date type x-axis. Options like tick_interval or tick_format are still respected.
```Python
# Example code for using a date axis with bar charts.
# This snippet is a placeholder as the actual code was not provided in the input.
# For example:
# from datetime import datetime
# dates = [datetime(2023, 1, 1), datetime(2023, 1, 2), datetime(2023, 1, 3)]
# values = [10, 15, 12]
# fig, ax = plt.subplots()
# ax.bar(dates, values)
# ax.xaxis_date()
# plt.show()
```
--------------------------------
### Dynamic Series Creation Example
Source: https://visualization-toolkit-docs.yipit.systems/_modules/visualization_toolkit/helpers/plotly/charts/core/series
Demonstrates creating plot series dynamically by mapping data columns to chart axes and categories. This example shows how to plot 'lifeExp' for 'New Zealand' and 'Australia' against 'year'.
```python
from visualization_toolkit.helpers.plotly import chart, axis, series, annotation
import pandas as pd
# Assuming 'df' is a pandas DataFrame with columns like 'year', 'lifeExp', 'country'
df = pd.DataFrame({
"year": [2000, 2001, 2002, 2000, 2001, 2002],
"lifeExp": [70, 71, 72, 75, 76, 77],
"country": ["New Zealand", "New Zealand", "New Zealand", "Australia", "Australia", "Australia"]
})
fig = chart(
df,
x_axis=axis(
column_name="year",
label="Year",
),
chart_series=[
series(
column_name="lifeExp",
category_name="New Zealand",
),
series(
column_name="lifeExp",
category_name="Australia",
),
],
y1_axis=axis(
label="Life Expectancy",
axis_type="number",
),
pivot_column_name="country",
)
# display(fig) # Assuming display is available in the environment
```
--------------------------------
### Initialize Dash App for Production
Source: https://visualization-toolkit-docs.yipit.systems/_modules/visualization_toolkit/helpers/dash/core
Initializes a Dash application with settings optimized for production environments. It automatically loads Google fonts, custom Plotly bundles, enables JS asset compression, and uses CDNs for static files when not in DEBUG mode. The function returns an instance of `CustomDash`.
```python
definitialize_app(
name: str,
**kwargs,
) -> CustomDash:
"""
Intialize a Dash app with settings tuned for production scenarios. Settings enabled:
* Load Google fonts for use with YD theme
* Load custom plotly bundle to reduce bundle size
* Enable compression of JS assets served
* Use CDN when serving static files (enabled when DEBUG mode is off)
* Change base html file to remove unnecessary CSS styles
:param name: Name of the dash app to initialize
:param kwargs: Optional kwargs that will be passed to the `Dash` class instance
:return: `CustomDash` instance that is a subclass of `Dash`
"""
# Pop off external_stylesheets and add them to the end when starting the dash app
if "external_stylesheets" in kwargs:
external_stylesheets = kwargs.pop("external_stylesheets")
else:
external_stylesheets = []
if "external_scripts" in kwargs:
external_scripts = kwargs.pop("external_scripts")
else:
external_scripts = []
app = CustomDash(
name,
external_stylesheets=FONT_URLS + external_stylesheets,
external_scripts=external_scripts,
update_title="",
serve_locally=False,
compress=True,
**kwargs,
)
return app
```
--------------------------------
### Example: Create Chart with Multiple Series
Source: https://visualization-toolkit-docs.yipit.systems/_modules/visualization_toolkit/helpers/plotly/charts/core/series
Demonstrates how to use the `chart` function with multiple `series` objects to plot different data columns on a graph. This example shows basic series configuration for line plots with custom labels.
```python
from visualization_toolkit.helpers.plotly import chart, axis, series
# Assuming 'df' is a pandas DataFrame with columns like 'year', 'australia', 'new_zealand'
# Example DataFrame creation (replace with your actual data loading):
import pandas as pd
df = pd.DataFrame({
"year": [2020, 2021, 2022],
"australia": [10, 12, 15],
"new_zealand": [8, 9, 11]
})
fig = chart(
df,
x_axis=axis(
column_name="year",
label="Year",
),
chart_series=[
series(
column_name="australia",
label="Australia",
),
series(
column_name="new_zealand",
label="New Zealand",
),
],
y1_axis=axis(
label="Life Expectancy",
),
)
```
--------------------------------
### Create Basic Area Chart with Visualization Toolkit
Source: https://visualization-toolkit-docs.yipit.systems/recipes/area_chart/plot_area_chart
This example demonstrates how to generate a basic area chart using the visualization toolkit. It utilizes `mode='area'` for area charts and automatically handles stacking. Key dependencies include `pandas` and `visualization_toolkit.helpers.plotly`.
```Python
import pandas as pd
from dateutil.relativedelta import relativedelta
from visualization_toolkit.helpers.plotly import chart, axis, series
fig = chart(
pdf,
x_axis=axis(
column_name="day",
axis_type="date",
label="Week Ending",
tick_interval=relativedelta(days=7 * 6),
),
chart_series=[
series(
column_name="abnb_gbv_share",
label="ABNB GBV Share",
mode="area",
color="dark-blue",
),
series(
column_name="vrbo_gbv_share",
label="VRBO GBV Share",
mode="area",
color="red",
),
],
y1_axis=axis(
axis_type="percent",
axis_min=0,
axis_max=1,
tick_format="0.0%",
),
)
fig
```
--------------------------------
### Initialize User Store for Analytics
Source: https://visualization-toolkit-docs.yipit.systems/dash
Creates a `dcc.Store` component to store user and account information for analytics services like Pendo. It supports client-side storage in browser memory or session. Requires User ID and Account ID, with optional metadata and storage type configuration.
```APIDOC
visualization_toolkit.helpers.dash.user_store(_user_id ='NOT_SET'_, _account_id ='NOT_SET'_, _user_metadata =None_, _account_metadata =None_, _storage_type ='memory'_, _id =ATLAS_USER_STORE_ID_)
Parameters:
user_id (str): User ID associated with this browser session, typically an email.
account_id (str): Account ID associated with the user_id.
user_metadata (dict[str, str]): Optional metadata for the user in key/value pairs.
account_metadata (dict[str, str]): Optional metadata for the account in key/value pairs.
storage_type (str): Controls browser side storage behavior, passed to `dcc.Store`'s `storage_type` parameter.
id (str): Optionally set an HTML ID for this store. Callbacks referencing this store must be updated.
Returns:
dash.dcc.Store: A Dash dcc.Store component configured for user data.
```