### Install Node.js Dependencies and Develop Source: https://github.com/canva-public/flourishcharts/blob/main/python_package/README.md Installs Node.js dependencies and starts the development build process with live reloading for TypeScript code. ```bash npm install npm run dev ``` -------------------------------- ### Voila and Streamlit Integration Example Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/widget-implementation.md Demonstrates how to use the Flourish widget with Voila and Streamlit. Ensure you have the necessary libraries installed. ```python # Works with Voila from flourishcharts import Flourish chart = Flourish(chart_type="scatter") # Works with Streamlit via streamlit-option-menu or similar import streamlit as st st.write(chart) # Displays widget ``` -------------------------------- ### Python: Configure Chart Styling (General Pattern and Examples) Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/quick-reference.md Shows the general method for configuring chart-specific details and layout in Python, with examples for scatter, bar chart race, and sankey charts. ```python # All set methods follow this pattern chart.set__details( _title="Title", _title_color="#333333", chart_layout_background_color="#ffffff" ) # Examples: chart.set_scatter_details(scatter_title="Title", scatter_point_size=6) chart.set_bar_chart_race_details(bar_race_title="Race", bar_race_animation_speed=0.5) chart.set_sankey_details(sankey_node_font_size=12) ``` -------------------------------- ### Install Flourishcharts from GitHub Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/r-package-api.md Install the flourishcharts R package directly from its GitHub repository. Ensure 'remotes' package is installed first. ```r # Install remotes if needed install.packages("remotes") # Install from GitHub remotes::install_github("canva-public/flourishcharts", subdir="R_package") ``` -------------------------------- ### Example Metadata with Formats Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/types.md Demonstrates metadata for a datetime column with specific input and output formats, and a number column with custom separators. ```python { "data": { "date_column": { "type": "datetime", "type_id": "datetime$%Y-%m-%d", "output_format_id": "datetime$%d/%m/%Y" }, "sales": { "type": "number", "type_id": "number$comma_point", "output_format_id": "number$space_point" }, "category": { "type": "string", "type_id": "string$arbitrary", "output_format_id": "string$arbitrary" } } } ``` -------------------------------- ### R: Configure Chart Styling (General Pattern and Examples) Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/quick-reference.md Illustrates the common pattern for setting chart-specific details and layout options in R, with examples for scatter, bar chart race, and sankey charts. ```r # All set methods follow this pattern chart <- chart |> set__details( _title = "Title", _title_color = "#333333", chart_layout_background_color = "#ffffff" ) # Examples: chart <- chart |> set_scatter_details(scatter_title = "Title", scatter_point_size = 6) chart <- chart |> set_bar_chart_race_details(bar_race_title = "Race", bar_race_animation_speed = 0.5) chart <- chart |> set_sankey_details(sankey_node_font_size = 12) ``` -------------------------------- ### Development Installation with Pipenv Source: https://github.com/canva-public/flourishcharts/blob/main/python_package/README.md Installs the flourishcharts package in development mode from a Git repository using pipenv, linking it to a local subdirectory. ```bash pipenv install --dev -e "git+ssh://git@github.com/Canva-public/flourishcharts@main#egg=flourishcharts&subdirectory=python_package" ``` -------------------------------- ### Python: Bind Data to Chart (General Pattern and Examples) Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/quick-reference.md Illustrates the general pattern for binding data to different chart types in Python and provides specific examples for scatter, bar chart race, and sankey charts. ```python # All bind methods follow this pattern chart.bind__data( data=pd.DataFrame, column1="df_column1", column2="df_column2" ) # Examples: chart.bind_scatter_data(data=df, x="x_col", y="y_col") chart.bind_bar_chart_race_data(data=df, label="col", values=["2020", "2021"]) chart.bind_sankey_data(data=df, source="from", target="to", value="amount") ``` -------------------------------- ### Create DataFrame (Python) Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/quick-reference.md Example of creating a pandas DataFrame with sample data for use with Flourish charts. ```python import pandas as pd df = pd.DataFrame({ 'country': ['China', 'USA', 'India'], 'gdp': [1000, 950, 800], 'population': [1.3e9, 3.3e8, 1.2e9] }) ``` -------------------------------- ### anywidget Framework Setup Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/widget-implementation.md Defines the Flourish class inheriting from anywidget.AnyWidget, specifying ESM and CSS modules, and synchronizing model data. ```python class Flourish(anywidget.AnyWidget): _esm = pathlib.Path(__file__).parent / "static" / "widget.js" _css = pathlib.Path(__file__).parent / "static" / "widget.css" _model_data = traitlets.Dict().tag(sync=True) ``` -------------------------------- ### Python Quick Start: Create, Bind, Configure, Export Scatter Chart Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/quick-reference.md This snippet demonstrates the basic workflow for creating a scatter chart in Python: initializing the chart, binding data, configuring appearance, and optionally exporting a snapshot. ```python from flourishcharts import Flourish import pandas as pd import os # 1. Create chart chart = Flourish( chart_type="scatter", api_key=os.environ["FLOURISH_API_KEY"] ) # 2. Bind data chart.bind_scatter_data( data=your_data_df, x="column_x", y="column_y", color="column_color" ) # 3. Configure appearance chart.set_scatter_details( scatter_title="My Chart", scatter_title_color="#333333" ) # 4. Export (optional) chart.save_snapshot(filename="chart", format="png") ``` -------------------------------- ### Example: Details Error - Correct Method Call Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/utility-functions.md Shows a correct usage of set_details method matching the chart type. ```python # This works: chart = Flourish(chart_type="scatter") chart.set_scatter_details(scatter_title="Title") ``` -------------------------------- ### Example Bindings for Sankey Diagram Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/types.md Shows column mappings for a Sankey diagram, connecting 'from_country', 'to_country', and 'trade_volume'. ```python { "data": { "source": "from_country", "target": "to_country", "value": "trade_volume" } } ``` -------------------------------- ### Example State Configuration for Scatter Plot Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/types.md An example of a state dictionary tailored for a scatter plot, including title, size, and opacity settings. ```python { "chart_type": "scatter", "scatter_title": "Life Expectancy Analysis", "scatter_title_color": "#333333", "scatter_title_size": 24, "scatter_point_size": 8, "scatter_point_opacity": 0.7 } ``` -------------------------------- ### Method Chaining for Chart Configuration Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/details-methods.md Demonstrates how to chain multiple configuration methods, starting from chart initialization, binding data, and setting details for a scatter plot. This allows for a fluent and readable configuration process. ```python chart = (Flourish(chart_type="scatter", api_key="API_KEY") .bind_scatter_data(data=data, x="x_col", y="y_col", color="color_col") .set_scatter_details( scatter_title="My Chart", scatter_title_color="#333333", scatter_point_size=6 ) .set_audio_details(...) # Only if applicable for chart type ) ``` -------------------------------- ### R: Bind Data to Chart (General Pattern and Examples) Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/quick-reference.md Demonstrates the common pattern for binding data to various chart types in R, with specific examples for scatter, bar chart race, and sankey charts. ```r # All bind methods follow this pattern chart <- chart |> bind__data( data = data.frame, column1 = "df_column1", column2 = "df_column2" ) # Examples: chart <- chart |> bind_scatter_data(data = df, x = "x_col", y = "y_col") chart <- chart |> bind_bar_chart_race_data(data = df, label = "col", values = c("2020", "2021")) chart <- chart |> bind_sankey_data(data = df, source = "from", target = "to", value = "amount") ``` -------------------------------- ### Install flourishcharts in R from GitHub Source: https://github.com/canva-public/flourishcharts/blob/main/README.md Install the flourishcharts package directly from its GitHub repository, specifying the subdirectory for the R package. ```r remotes::install_github("canva-public/flourishcharts", subdir="R_package") ``` -------------------------------- ### Install flourishcharts in Python globally using pip Source: https://github.com/canva-public/flourishcharts/blob/main/README.md Install or upgrade the flourishcharts package to your global Python installation using pip. ```bash python3 -m pip install --upgrade flourishcharts ``` -------------------------------- ### R Quick Start: Create, Bind, Configure, Display Scatter Chart Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/quick-reference.md This snippet shows the basic workflow for creating a scatter chart in R: initializing the chart, binding data, configuring appearance, and displaying it in an RMarkdown environment. ```r library(flourishcharts) # 1. Create chart chart <- flourish(chart_type = "scatter") # 2. Bind data chart <- chart |> bind_scatter_data( data = your_data_df, x = "column_x", y = "column_y", color = "column_color" ) # 3. Configure appearance chart <- chart |> set_scatter_details( scatter_title = "My Chart", scatter_title_color = "#333333" ) # 4. Display in RMarkdown chart ``` -------------------------------- ### Install flourishcharts in Python using pipenv Source: https://github.com/canva-public/flourishcharts/blob/main/README.md Use this command to install the flourishcharts package within a specific virtual environment managed by pipenv. ```bash pipenv install flourishcharts ``` -------------------------------- ### Example Bindings for Scatter Plot Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/types.md Illustrates how columns like 'gdpPercap' and 'lifeExp' are mapped to the 'x' and 'y' axes for a scatter plot. ```python { "data": { "x": "gdpPercap", "y": "lifeExp", "size": "population", "color": "continent", "label": "country" } } ``` -------------------------------- ### Create DataFrame (R) Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/quick-reference.md Example of creating an R data frame with sample data for use with Flourish charts. ```r df <- data.frame( country = c("China", "USA", "India"), gdp = c(1000, 950, 800), population = c(1.3e9, 3.3e8, 1.2e9) ) ``` -------------------------------- ### Install and Load flourishcharts Package Source: https://github.com/canva-public/flourishcharts/blob/main/R_package/README.md Install the flourishcharts package from CRAN and load it into your R session to begin creating visualizations. ```r install.packages("flourishcharts") library(flourishcharts) ``` -------------------------------- ### Example: Bindings Error - Correct Method Call Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/utility-functions.md Shows a correct usage of a bind_data method that matches the chart type. ```python # This works: chart = Flourish(chart_type="bar_chart_race") chart.bind_bar_chart_race_data(data=data, label="label", values=["2020", "2021"]) ``` -------------------------------- ### Creating Chart from Base Visualization Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/r-package-api.md Example of creating a new visualization by referencing an existing published Flourish visualization using `base_visualisation_id` and binding new data. ```r # Reference existing published visualization chart <- flourish( base_visualisation_id = 12345678, api_key = Sys.getenv("FLOURISH_API_KEY") ) |> bind_bar_chart_race_data( data = new_data, label = "country", values = c("2023", "2024") ) ``` -------------------------------- ### Automatic API Key Loading Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/configuration.md If no API key is provided as a parameter or found in the environment, the library will attempt to load it automatically. This simplifies setup when the environment variable is correctly configured. ```python # Automatic environment loading chart = Flourish(chart_type="scatter") ``` -------------------------------- ### Example: Details Error - Incorrect Method Call Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/utility-functions.md Illustrates how calling the wrong set_details method for a chart type raises an exception. ```python # This raises an Exception: chart = Flourish(chart_type="scatter") chart.set_bar_chart_race_details(bar_race_title="Title") # Raises: The function [set_bar_chart_race_details] does not work with this # chart type [scatter]. Instead the ideal detail-setting function for this # chart type is [set_scatter_details]. ``` -------------------------------- ### Metadata Type System Example Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/widget-implementation.md Shows the structure of metadata used by the Flourish API to parse input values, apply format transformations, and display values correctly. ```typescript metadata = { "data": { "column_name": { "type": "string|number|datetime", "type_id": "string$format|number$format|datetime$format", "output_format_id": "..." } } } // Flourish API uses this to: // 1. Parse input values // 2. Apply format transformations // 3. Display values correctly ``` -------------------------------- ### Bar Chart Race Creation Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/r-package-api.md Example demonstrating how to create a bar chart race visualization. It uses `flourish()` with `bind_bar_chart_race_data()` and `set_bar_chart_race_details()` for customization. ```r race_data <- data.frame( country = c("China", "USA", "India", "Japan"), `2020` = c(1000, 950, 800, 700), `2021` = c(1100, 1000, 850, 750), `2022` = c(1200, 1050, 900, 800), check.names = FALSE ) chart <- flourish(chart_type = "bar_chart_race") |> bind_bar_chart_race_data( data = race_data, label = "country", values = c("2020", "2021", "2022") ) |> set_bar_chart_race_details( bar_race_title = "Global GDP Race", bar_race_title_color = "#1f77b4", bar_race_title_size = 28 ) ``` -------------------------------- ### Basic Scatter Plot Creation Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/r-package-api.md Example of creating a basic scatter plot using the `flourish()` function and `bind_scatter_data()`. Requires the `flourishcharts` library to be loaded. ```r library(flourishcharts) data <- data.frame( lifeExp = c(76.9, 78.8, 65.5, 83.1), gdpPercap = c(9945, 42951, 1676, 32459), country = c("China", "USA", "India", "Japan") ) chart <- flourish(chart_type = "scatter") |> bind_scatter_data( data = data, x = "gdpPercap", y = "lifeExp" ) ``` -------------------------------- ### Datetime Format Strings Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/types.md Provides examples of Python strftime format codes for representing dates in various string formats. ```python "%Y-%m-%d" # 2024-06-03 ``` ```python "%d/%m/%Y" # 03/06/2024 ``` ```python "%B %d, %Y" # June 03, 2024 ``` ```python "%Y%m%d" # 20240603 ``` ```python "%d %b %Y" # 03 Jun 2024 ``` -------------------------------- ### Method Chaining (Python) Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/quick-reference.md Chain multiple method calls together for a concise way to configure and save a chart. This example chains data binding, detail setting, and snapshot saving. ```python chart = (Flourish(chart_type="scatter") .bind_scatter_data(data=df, x="x", y="y") .set_scatter_details(scatter_title="Title") .save_snapshot(filename="chart") ) ``` -------------------------------- ### Example: Bindings Error - Incorrect Method Call Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/utility-functions.md Demonstrates an exception raised when an incorrect data binding method is used for a chart type. ```python # This raises an Exception: chart = Flourish(chart_type="bar_chart_race") chart.bind_scatter_data(data=data, x="x", y="y") # Raises: The data bindings function [bind_scatter_data] does not work with this # chart type [bar_chart_race]. Instead the ideal data bindings function is # [bind_bar_chart_race_data]. ``` -------------------------------- ### Invalid Constructor: Missing API Key Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/configuration.md This example demonstrates an invalid constructor call that will raise an exception if the FLOURISH_API_KEY environment variable is not set, as the API key is required. ```python # Missing API key Flourish(chart_type="scatter") # Raises if FLOURISH_API_KEY not set ``` -------------------------------- ### Install flourishcharts in R from CRAN Source: https://github.com/canva-public/flourishcharts/blob/main/README.md Install the flourishcharts package from the Comprehensive R Archive Network (CRAN). ```r install.packages("flourishcharts") ``` -------------------------------- ### Build Process Commands Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/widget-implementation.md Provides bash commands for running the development server, creating a production build, and performing type checking. ```bash # Development: watch and rebuild npm run dev # Production: minified build npm run build # Type checking npm run typecheck ``` -------------------------------- ### Initialize Flourish with Chart Type and Bind Data Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/flourish-class.md Demonstrates initializing a Flourish chart by specifying its type and then binding data using the appropriate method. Also shows how to set visual details and save a snapshot. Requires the FLOURISH_API_KEY environment variable. ```python import os from flourishcharts import Flourish import pandas as pd # Initialize with chart type (preferred method) chart = Flourish( chart_type="scatter", chart_description="Correlation between life expectancy and GDP per capita by country", api_key=os.environ["FLOURISH_API_KEY"] ) # Bind data using the appropriate method chart.bind_scatter_data( data=your_data_df, x="gdpPercap", y="lifeExp", size="population", color="continent" ) # Configure visual details chart.set_scatter_details( scatter_title="Life Expectancy vs GDP", scatter_title_color="#333333", scatter_point_size=6 ) # Save as static image chart.save_snapshot(filename="scatter_plot", format="png") ``` -------------------------------- ### Bar Chart Race Data Binding Usage Example Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/data-bindings.md Demonstrates how to use the bind_bar_chart_race_data method with a pandas DataFrame and Flourish object. This example sets up the necessary imports and initializes the Flourish object. ```python import pandas as pd from flourishcharts import Flourish ``` -------------------------------- ### Initialize Flourish from Existing Visualization Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/flourish-class.md Shows how to initialize a Flourish chart by referencing an existing, published Flourish visualization using its ID. Requires the FLOURISH_API_KEY environment variable. ```python # Initialize from existing published visualization chart = Flourish( base_visualisation_id="12345678", api_key=os.environ["FLOURISH_API_KEY"] ) ``` -------------------------------- ### Python: Initialize Chart Methods Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/quick-reference.md Demonstrates different ways to initialize a Flourish chart object in Python, including by chart type, template ID, or an existing visualization ID. ```python # Method 1: By chart type (preferred) chart = Flourish(chart_type="scatter") # Method 2: By template ID + version chart = Flourish( template_id="@flourish/scatter", template_version_number="3" ) # Method 3: From existing visualization chart = Flourish(base_visualisation_id="12345") ``` -------------------------------- ### Load API Key in Python Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/configuration.md Demonstrates how to retrieve the Flourish API key from environment variables and use it when initializing the Flourish constructor. It also shows initialization without explicitly passing the API key, relying on automatic detection. ```python import os api_key = os.environ.get("FLOURISH_API_KEY") # In Flourish constructor from flourishcharts import Flourish chart = Flourish(chart_type="scatter", api_key=api_key) # Or rely on automatic environment variable detection chart = Flourish(chart_type="scatter") ``` -------------------------------- ### Python: Retry Fetching Base Visualization Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/errors.md Illustrates how to handle base visualization fetch failures by retrying the operation after a short delay. This is useful for transient network issues or API downtime. ```python # Retry with valid visualization ID import time try: chart = Flourish(base_visualisation_id="12345", api_key=key) except Exception as e: time.sleep(5) chart = Flourish(base_visualisation_id="12345", api_key=key) # Or check visualization ID format (should be numeric) chart = Flourish(base_visualisation_id="12345678", api_key=key) ``` -------------------------------- ### Column Validation Example Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/data-bindings.md Asserts that a specified column name exists within the DataFrame. This is a common validation step before data binding. ```python if url is not None: assert url in data_columns, f"[url] is not a column in the data." ``` -------------------------------- ### Python Configuration Structure Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/widget-implementation.md Illustrates the structure of the _model_data dictionary created in Python for widget configuration. ```python # Python creates this structure _model_data = { "state": {...}, "data": {...}, "bindings": {...}, "metadata": {...}, "template": "@flourish/scatter", "version": "3", "api_key": "abc123...", "chart_description": "...", "width": None, "height": None, "base_visualisation_id": None, "snapshot": {...} } ``` -------------------------------- ### Loading Environment Variable Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/types.md Demonstrates how to retrieve the FLOURISH_API_KEY from the environment using os.environ.get(). ```python import os api_key = os.environ.get("FLOURISH_API_KEY") ``` -------------------------------- ### Initialize Flourish with chart_description Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/configuration.md Initializes a Flourish chart and provides an accessibility description for screen readers. This text is not visually displayed but aids users with assistive technologies. ```python chart = Flourish( chart_type="scatter", chart_description="Scatter plot showing the relationship between life expectancy and GDP per capita, with each point representing a country", api_key=api_key ) ``` -------------------------------- ### R: Initialize Chart Methods Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/quick-reference.md Shows various methods for initializing a Flourish chart object in R, such as specifying the chart type, template ID with version, or an existing visualization ID. ```r # Method 1: By chart type (preferred) chart <- flourish(chart_type = "scatter") # Method 2: By template ID + version chart <- flourish( template_id = "@flourish/scatter", template_version_number = "3" ) # Method 3: From existing visualization chart <- flourish(base_visualisation_id = 12345) ``` -------------------------------- ### RMarkdown Inline Flourish Chart Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/r-package-api.md Embed a Flourish chart directly within an RMarkdown document using a code chunk. This example creates a scatter plot. ```rmarkdown ```{r} flourish(chart_type = "scatter") |> bind_scatter_data(data = mtcars, x = "mpg", y = "hp") ``` ``` -------------------------------- ### Python Initialization Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/widget-implementation.md Initializes a Flourish instance in Python, which serves as the base for the anywidget. ```python chart = Flourish(chart_type="scatter", api_key=key) # Creates Flourish instance with anywidget.AnyWidget base class # Initializes _model_data with widget configuration ``` -------------------------------- ### Color Specifications (Hex Format) Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/quick-reference.md Examples of common color specifications using the 6-digit hex code format, including red, green, blue, grays, and black/white. ```python "#FF0000" # Red "#00FF00" # Green "#0000FF" # Blue "#333333" # Dark gray "#CCCCCC" # Light gray "#FFFFFF" # White "#000000" # Black ``` -------------------------------- ### R: Export Chart Snapshot (Formats and Options) Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/quick-reference.md Demonstrates exporting chart snapshots in R using `save_charts`, including default PNG, custom filenames, resolution scaling, and support for JPEG and SVG formats. ```r # PNG (default) save_charts(chart) # With custom name and resolution save_charts( chart, filename = "my_chart", format = "png", scale = 2 # Double resolution ) # As JPEG save_charts(chart, filename = "my_chart", format = "jpeg") # As SVG (vector) save_charts(chart, filename = "my_chart", format = "svg") ``` -------------------------------- ### Run Unit Tests Source: https://github.com/canva-public/flourishcharts/blob/main/python_package/README.md Discovers and runs unit tests for the project using the Python unittest module. ```bash python -m unittest discover -s tests ``` -------------------------------- ### Copy Environment Variables Demo File Source: https://github.com/canva-public/flourishcharts/blob/main/python_package/README.md Copies the .envrc-demo file to .envrc, which is used for setting environment variables like API keys. ```bash cp .envrc-demo .envrc ``` -------------------------------- ### Shiny App with Dynamic Flourish Chart Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/r-package-api.md Integrate Flourish charts into a Shiny application, allowing users to select chart types dynamically. This example uses a selectInput for chart type. ```r library(shiny) library(flourishcharts) ui <- fluidPage( titlePanel("Flourish Chart"), sidebarLayout( sidebarPanel( selectInput("chart_type", "Chart Type:", choices = c("scatter", "bar_chart_race")) ), mainPanel( uiOutput("chart") ) ) ) server <- function(input, output, session) { output$chart <- renderUI({ flourish(chart_type = input$chart_type) |> bind_scatter_data( data = data, x = "x_col", y = "y_col" ) }) } shinyApp(ui, server) ``` -------------------------------- ### Method Chaining (R) Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/quick-reference.md Chain multiple function calls using the pipe operator for a concise way to configure and save a chart. This example chains data binding, detail setting, and chart saving. ```r chart <- flourish(chart_type = "scatter") |> bind_scatter_data(data = df, x = "x", y = "y") |> set_scatter_details(scatter_title = "Title") |> save_charts(filename = "chart") ``` -------------------------------- ### Python: Export Chart Snapshot (Formats and Options) Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/quick-reference.md Shows how to export a chart snapshot in Python using `save_snapshot`, covering default PNG export, custom filenames, resolution scaling, and alternative formats like JPEG and SVG. ```python # PNG (default) chart.save_snapshot() # With custom name and resolution chart.save_snapshot( filename="my_chart", format="png", scale=2 # Double resolution ) # As JPEG chart.save_snapshot(filename="my_chart", format="jpeg") # As SVG (vector) chart.save_snapshot(filename="my_chart", format="svg") ``` -------------------------------- ### Common Layout Parameters Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/quick-reference.md Demonstrates the common parameters for controlling the overall chart layout, such as background color and margins. ```python chart_layout_background_color="#ffffff" chart_layout_margin_top=20 chart_layout_margin_right=20 chart_layout_margin_bottom=20 chart_layout_margin_left=20 ``` -------------------------------- ### Type Validation Error Example Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/details-methods.md Illustrates an error scenario where an incorrect details method (`set_scatter_details`) is called for a chart type (`bar_chart_race`). The library is designed to raise an exception indicating the mismatch and suggesting the correct method. ```python # Will raise Exception: # "The function [set_scatter_details] does not work with this chart type # [bar_chart_race]. Instead the ideal detail-setting function for this # chart type is [set_bar_chart_race_details]." chart = Flourish(chart_type="bar_chart_race", api_key=api_key) chart.set_scatter_details(scatter_title="Title") ``` -------------------------------- ### Setting Sankey Diagram Details Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/details-methods.md Example of how to bind Sankey data and then set specific visual details for the chart, such as title, colors, and link opacity. Ensure chart type and API key are correctly initialized. ```python chart = Flourish(chart_type="sankey", api_key="YOUR_API_KEY") chart.bind_sankey_data( data=flow_data, source="from", target="to", value="amount" ) chart.set_sankey_details( sankey_title="Sales Flow Analysis", sankey_title_color="#2ca02c", sankey_title_size=22, sankey_node_font_size=12, sankey_link_opacity=0.5, sankey_show_values=True, chart_layout_background_color="#fafafa" ) ``` -------------------------------- ### Configure Flourish API Key Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/r-package-api.md Set the FLOURISH_API_KEY environment variable in the .Renviron file for authentication. Restart R after setting the variable. ```r FLOURISH_API_KEY = "your_api_key_here" ``` ```r Sys.getenv("FLOURISH_API_KEY") # Should print your API key ``` -------------------------------- ### Handle Unsupported Map Templates in Flourish Charts Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/errors.md The flourishcharts library does not support map or globe chart types directly. This example shows how initializing with such types raises an exception. The recommended alternative is to use the Flourish web interface or contact support. ```python chart = Flourish(chart_type="map_world") # Raises Exception ``` ```python chart = Flourish(chart_type="globe_3d") # Raises Exception ``` -------------------------------- ### JavaScript Configuration Reception Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/widget-implementation.md Shows how the JavaScript frontend receives and accesses the configuration options passed from the Python backend. ```typescript const opts = model.get("_model_data"); // opts contains all configuration // opts.container = rendered chart div // opts.state = configuration state // opts.data = chart data // opts.bindings = data bindings // opts.metadata = type metadata ``` -------------------------------- ### Python: Correct Details Method for Scatter Chart Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/errors.md Demonstrates the correct way to set details for a scatter plot. Ensure you are using the appropriate method for styling your chart. ```python # Use the correct details method for your chart type chart = Flourish(chart_type="scatter") chart.set_scatter_details(scatter_title="My Title") ``` -------------------------------- ### Python: Format Parameter Mismatch Hint Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/errors.md Shows the pattern for a validation hint regarding format parameters. This indicates that both `input_format` and `output_format` should ideally be defined together. ```python if url_input_format is None and url_output_format is not None: f"[url_input_format] and [url_output_format] must both be defined." ``` -------------------------------- ### Generate PNG Snapshots for Reports Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/snapshot.md Create PNG snapshots of charts for inclusion in static reports. Adjust the scale factor for desired resolution. ```python # Generate charts for static report chart1 = Flourish(chart_type="scatter", api_key=api_key) chart1.bind_scatter_data(data=df1, x="x", y="y") chart1.save_snapshot(filename="report_figure_1", format="png", scale=2) chart2 = Flourish(chart_type="bar_chart_race", api_key=api_key) chart2.bind_bar_chart_race_data(data=df2, label="label", values=values) chart2.save_snapshot(filename="report_figure_2", format="png", scale=2) ``` -------------------------------- ### Provide Both Format Parameters Together Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/errors.md When binding data, specify both input and output formats for date columns if they differ. This ensures correct parsing and display of date information. ```python chart.bind_scatter_data( data=data, x="date_col", x_input_format="%Y-%m-%d", x_output_format="%d/%m/%Y" ) ``` -------------------------------- ### save_snapshot() Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/snapshot.md Export the current visualization as a static image in PNG, JPEG, or SVG format. The method triggers the frontend widget to render the visualization and download it. It supports custom filenames, formats, and resolution scaling. ```APIDOC ## save_snapshot() ### Description Export the current visualization as a static image in PNG, JPEG, or SVG format. This method triggers the frontend widget to render the visualization and download it to the user's default downloads folder. It supports custom filenames, formats, and resolution scaling. ### Method ```python def save_snapshot( self, filename: str = "Flourish_Live_API_image", format: str = "png", scale: int = 1 ) -> Flourish ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | filename | str | No | "Flourish_Live_API_image" | File name for the saved image. Do not include file extension; it is added automatically based on format parameter. Spaces and special characters are allowed. | | format | str | No | "png" | Output format. Valid values: "png", "jpeg", "svg". PNG and JPEG are raster formats. SVG is a vector format preserving text and element interactivity information. | | scale | int | No | 1 | Scale factor for image resolution. Default scale of 1 produces standard resolution. Use 2 for double resolution, 3 for triple, etc. Higher scales produce larger file sizes. Useful for high-resolution displays or printing. | ### Return Type Returns `self` for method chaining. The snapshot operation is asynchronous; the file download is triggered but the method returns immediately. ### Examples #### Basic PNG Export ```python from flourishcharts import Flourish chart = Flourish(chart_type="scatter", api_key="YOUR_API_KEY") chart.bind_scatter_data( data=data, x="gdpPercap", y="lifeExp", color="continent" ) chart.save_snapshot() # Saves as "Flourish_Live_API_image.png" ``` #### High-Resolution PNG for Printing ```python chart.save_snapshot( filename="high_res_scatter", format="png", scale=3 # Triple resolution for printing ) # File saved as "high_res_scatter.png" at 3x resolution ``` #### JPEG with Custom Filename ```python chart.save_snapshot( filename="bar_chart_race_2024", format="jpeg" ) # File saved as "bar_chart_race_2024.jpg" ``` #### SVG Vector Format ```python chart.save_snapshot( filename="sankey_diagram", format="svg" ) # File saved as "sankey_diagram.svg" with vector elements ``` #### Method Chaining ```python chart = (Flourish(chart_type="scatter", api_key="YOUR_API_KEY") .bind_scatter_data(data=data, x="x_col", y="y_col") .set_scatter_details(scatter_title="My Chart") .save_snapshot(filename="final_chart", format="png", scale=2) ) ``` ``` -------------------------------- ### Build Configuration in package.json Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/widget-implementation.md Defines npm scripts for development (watch and rebuild), production builds (minified), and type checking using esbuild and TypeScript. ```json { "scripts": { "dev": "npm run build -- --sourcemap=inline --watch", "build": "esbuild js/widget.ts --minify --format=esm --bundle --outdir=flourishcharts/static", "typecheck": "tsc --noEmit" }, "devDependencies": { "@anywidget/types": "^0.1.4", "typescript": "^5.2.2", "esbuild": "^0.19.5" } } ``` -------------------------------- ### Load API Key in R Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/configuration.md Shows how to retrieve the Flourish API key using Sys.getenv() in R and pass it to the flourish() function. ```r # In R, use Sys.getenv() api_key <- Sys.getenv("FLOURISH_API_KEY") # In flourish() function chart <- flourish( chart_type = "scatter", api_key = Sys.getenv("FLOURISH_API_KEY") ) ``` -------------------------------- ### Python Snapshot Configuration Dictionary Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/snapshot.md Illustrates the internal Python dictionary structure created by `save_snapshot()` before it is merged into the main model data. ```python self.snapshot = { "snapshot_flag": True, "snapshot_metadata": { "filename": filename, "format": format, "scale": scale, "download": True } } ``` -------------------------------- ### Frontend Rendering Logic Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/widget-implementation.md Renders the chart container and initializes the Flourish Live API with configuration options obtained from the model. ```typescript function render({ model, el }: RenderContext) { let chart = document.createElement("div"); chart.id = "chart"; el.appendChild(chart); let opts = model.get("_model_data"); // Configuration setup opts.container = chart; var flourish_visualisation = new flourishliveApi.Live(opts); } ``` -------------------------------- ### Use Deep Merge for Configuration Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/utility-functions.md Demonstrates how deep_merge is used to combine chart data and bindings, ensuring null terms are cleaned first. ```python dict_to_merge = self.data_and_bindings clean_dict = clean_null_terms(dict_to_merge) # Assuming clean_null_terms is defined elsewhere self._model_data = deep_merge(self._model_data, clean_dict) ``` -------------------------------- ### Base Visualization Structure Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/types.md Defines components for loading data from an existing published visualization, including state, data, bindings, and metadata. ```python base_state: dict # Chart state configuration base_data: list | dict # Chart data (may be dict of arrays) base_bindings: dict # Column mappings base_metadata: dict # Type information ``` -------------------------------- ### Snapshot Export Configuration Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/types.md Configuration for exporting static images. Specifies snapshot flag, filename, format, scale, and download option. ```python snapshot: dict = { "snapshot_flag": bool, "snapshot_metadata": { "filename": str, "format": "png" | "jpeg" | "svg", "scale": int, "download": bool } } ``` ```python { "snapshot_flag": True, "snapshot_metadata": { "filename": "my_chart", "format": "png", "scale": 2, "download": True } } ``` -------------------------------- ### Initialize Flourish with base_visualisation_id Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/configuration.md Initializes a Flourish chart by referencing an existing published visualization ID. This loads the configuration, data, and state from the specified visualization. The data can be overridden using bind methods. ```python chart = Flourish( base_visualisation_id="12345678", api_key=api_key ) # Can now override data: chart.bind_scatter_data(data=new_data, x="x_col", y="y_col") ``` -------------------------------- ### Valid Constructor: By Template ID and Version Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/configuration.md Create a Flourish chart using a specific template by providing 'template_id' and 'template_version_number'. 'api_key' is required, and other parameters are optional. ```python Flourish(template_id="@flourish/scatter", template_version_number="3") ``` -------------------------------- ### Method Chaining for Snapshot Export Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/snapshot.md Demonstrates how to chain multiple Flourish methods, including `save_snapshot`, in a single statement. This allows for a fluent API usage pattern. ```python chart = (Flourish(chart_type="scatter", api_key="YOUR_API_KEY") .bind_scatter_data(data=data, x="x_col", y="y_col") .set_scatter_details(scatter_title="My Chart") .save_snapshot(filename="final_chart", format="png", scale=2) ) ``` -------------------------------- ### Set API Key (R) Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/quick-reference.md Set the Flourish API key by adding it to your .Renviron file. The library will then automatically pick it up. ```r # Add to ~/.Renviron: # FLOURISH_API_KEY = "your_key" # Then use: chart <- flourish(chart_type = "scatter") ``` -------------------------------- ### Common Title Parameters Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/quick-reference.md Illustrates the common parameters used for setting chart titles, including text, color, size, and weight. ```python _title="Title Text" _title_color="#333333" _title_size=24 _title_weight="bold" ``` -------------------------------- ### Basic PNG Export Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/snapshot.md Use this snippet to perform a basic export of the current visualization as a PNG file. The default filename 'Flourish_Live_API_image.png' will be used. ```python from flourishcharts import Flourish chart = Flourish(chart_type="scatter", api_key="YOUR_API_KEY") chart.bind_scatter_data( data=data, x="gdpPercap", y="lifeExp", color="continent" ) chart.save_snapshot() # Saves as "Flourish_Live_API_image.png" ``` -------------------------------- ### Flourish Live API Constructor Source: https://github.com/canva-public/flourishcharts/blob/main/_autodocs/widget-implementation.md Instantiates the Flourish Live API with the provided options object, which includes the container and configuration details. ```typescript var flourish_visualisation = new flourishliveApi.Live(opts); ```