Skip to main content
Version: 26.6.0

Canvas

Canvases are the components of Muze which house visualizations. They act as a way to compose layers of visual marks (e.g. bar, line etc), where each mark represents data through different encoding methods - such as color, size, or position. These encoded elements combine to create comprehensive visualizations that can be further subdivided into smaller components based on additional discrete data dimensions.

The Canvas manages the lifecycle of many other internal logical components and exposes one consistent interface to create visualizations.

A Canvas instance is created by using the muze.canvas API.

const canvas = muze.canvas();

The wrapper automatically applies the following enhancements to each canvas:

Default Layers

Sets a default bar chart layer with ThoughtSpot color encoding

Context Menu Integration

Enables right-click context menus on chart elements, axes, and facets

ThoughtSpot Color Palettes

Applies ThoughtSpot brand colors to legends and chart elements

Automatic Canvas Resizing

When globalOptions.autoResizeCanvas is enabled (default: true), canvases automatically resize to match their mount element dimensions

Automatically disables animations during PNG/PDF exports for instant rendering

##Render Completion Tracking When globalOptions.autoEmitRenderCompletedEvent is enabled (default: true), automatically emits render completion events

XLSX Download Handler

The first canvas instance automatically handles XLSX download requests when globalOptions.autoHandledXLSXDownload is enabled (default: true):

rows(fieldsConfig?)

PropertiesTypeRequiredDefaultDescription
fieldsConfigArray<string | fieldInfo> | [Array<string | fieldInfo>, Array<string | fieldInfo>?]undefinedSpecifies the fields for creating vertical axes and facets. Can be a single array for one axis or a tuple of arrays for dual axes.

If fieldsConfig is not specified, acts as a getter and returns the fieldsConfig that has been set.

If fieldsConfig is specified, determines how the specified fields are used to control the vertical axes' and facets' layout and returns the Canvas instance.

info

Regardless of the order in which fields are provided, the fields are implicitly grouped into discrete and continuous fields (maintaining provided relative order within each kind of field).

  1. Discrete fields (dimensions) are processed as follows:

    • The discrete fields create facets.
    • If no continuous fields exist, then the last discrete field forms the axis and does not participate in faceting.
  2. Continuous fields (measures) are processed as follows:

    • Each creates a separate axis, arranged vertically.
    • When faceted, all the continuous axes stay together and are faceted as a combined unit.

For dual-axis configurations ([Array<string | fieldInfo>, Array<string | fieldInfo>?]):

  • Discrete fields from both arrays are combined and processed as above. Dual-axes cannot be created from discrete fields.
  • The continuous fields from the first array in the tuple creates the left axes while the ones from the second array create the right axes.
  • Continuous fields create matching pairs of axes where possible.
  • Unpaired continuous fields create single axes on the corresponding side with no axes on the opposite side.

Examples

Single Axis Configuration

// Single, continuous Y-axis
canvas.rows(["sales"]);

// Single, continuous Y-axis on the right side
canvas.rows([[], ["sales"]]);

// Multiple, continuous Y-axes with row faceting
canvas.rows(["category", "sales", "region", "profit"]);
// Results in:
// - Row facets: category, region
// - Y-Axes: profit, sales

Dual Axis Configuration

// Two rows each with a pair of Y-axes - one on each side
canvas.rows([
  ["sales", "profit"],
  ["quantity", "margin"],
]);
// Creates:
// - First row: sales on the left Y-axis, quantity on the right Y-axis
// - Second row: profit on the left Y-axis, margin on the right Y-axis

// Uneven number of fields
canvas.rows([["sales", "profit"], ["quantity"]]);
// Creates:
// - First row: sales on the left Y-axis, quantity on the right Y-axis
// - Second row: profit on the left Y-axis, no right Y-axis

columns(fieldsConfig?)

PropertiesTypeRequiredDefaultDescription
fieldsConfigArray<string | fieldInfo> | [Array<string | fieldInfo>, Array<string | fieldInfo>?]undefinedSpecifies the fields for creating horizontal axes and facets. Can be a single array for one axis or a tuple of arrays for dual axes.

If fieldsConfig is not specified, acts as a getter and returns the fieldsConfig that has been set.

If fieldsConfig is specified, determines how the specified fields are used to control the horizontal axes' and facets' layout and returns the Canvas instance.

info

Regardless of the order in which fields are provided, the fields are implicitly grouped into discrete and continuous fields (maintaining provided relative order within each kind of field).

  1. Discrete fields (dimensions) are processed as follows:

    • The discrete fields create facets.
    • If no continuous fields exist, then the last discrete field forms the axis and does not participate in faceting.
  2. Continuous fields (measures) are processed as follows:

    • Each creates a separate axis, arranged horizontally.
    • When faceted, all the continuous axes stay together and are faceted as a combined unit.

For dual-axis configurations, i.e., when a tuple ([Array<string | fieldInfo>, Array<string | fieldInfo>?]) is provided :

  • Discrete fields from both arrays are combined and processed as above. Dual-axes cannot be created from discrete fields.
  • The continuous fields from the first array in the tuple creates the top axes while the ones from the second array create the bottom axes.
  • Continuous fields create matching pairs of axes where possible.
  • Unpaired continuous fields create single axes on the corresponding side with no axes on the opposite side.

Examples

Single Axis Configuration

// Single, continuous X-axis
canvas.columns(["sales"]);

// Single, continuous X-axis on the top side
canvas.columns([["sales"]]);

// Multiple, continuous X-axes with column faceting
canvas.columns(["category", "sales", "region", "profit"]);
// Results in:
// - column facets: category, region
// - X-Axes: profit, sales

Dual Axis Configuration

// Two columns each with a pair of X-axes - one on each side
canvas.columns([
  ["sales", "profit"],
  ["quantity", "margin"],
]);
// Creates:
// - First column: sales on the top X-axis, quantity on the bottom X-axis
// - Second column: profit on the top X-axis, margin on the bottom X-axis

// Uneven number of fields
canvas.columns([["sales", "profit"], ["quantity"]]);
// Creates:
// - First column: sales on the top X-axis, quantity on the bottom X-axis
// - Second column: profit on the top X-axis, no bottom X-axis

color(colorFieldInfo?)

PropertiesTypeRequiredDefaultDescription
colorFieldInfostring | objectundefinedName of the field used to derive the color of the data plots
colorFieldInfo.fieldstring-Name of the color field
colorFieldInfo.as'discrete' | 'continuous'undefinedDetermines the scale type
colorFieldInfo.rangeArray<string> | stringundefinedArray of color strings or name of the color scheme present in Muze. For binned fields, if range is provided, stops will be ignored
colorFieldInfo.stepbooleanfalseCreates a step legend
colorFieldInfo.stopsnumber | Array<number>5Number of stops or actual stops in an array. Only valid when step is true
colorFieldInfo.domainArray<number>undefinedIf specified, overrides the default color domain which is calculated from the original values in the datamodel. Supported in gradient legend
colorFieldInfo.invalidValueColorstringundefinedIf specified, all null/invalid values will use provided color instead of fetching color from color-axis

If no parameter is specified, acts as a getter and returns the current color configuration.

If colorFieldInfo is specified, sets the color encoding for the visualization and returns the Canvas instance. Setting color automatically creates a legend in the chart.

Examples

Basic Usage

// Set color using field name
canvas.color("Origin");

// Get current color configuration
const color = canvas.color();

Advanced Configuration

// Set color with step configuration
canvas.color({
  field: "Acceleration",
  step: true,
});

// Set color with custom range and domain
canvas.color({
  field: "Speed",
  as: "continuous",
  range: ["#ff0000", "#00ff00", "#0000ff"],
  domain: [0, 100],
  invalidValueColor: "#cccccc",
});

// Set color with custom stops
canvas.color({
  field: "Rating",
  step: true,
  stops: [0, 25, 50, 75, 100],
});

size(sizeFieldInfo?)

PropertiesTypeRequiredDefaultDescription
sizeFieldInfostring | objectundefinedName of the field used to derive the size of the plots
sizeFieldInfo.fieldstring-Name of the size field
sizeFieldInfo.as'discrete' | 'continuous'undefinedDetermines the scale type
sizeFieldInfo.rangeArray<number>undefinedAn array of size values
sizeFieldInfo.domainArray<number>undefinedIf specified, overrides the default size domain which is calculated from the original values in the datamodel

If no parameter is specified, acts as a getter and returns the current size configuration.

If sizeFieldInfo is specified, sets the size encoding for the visualization and returns the Canvas instance. Setting size automatically creates a size legend in the chart.

info

Size field is not supported for the area layer.

Examples

Basic Usage

// Set size using field name
canvas.size("Origin");

// Get current size configuration
const size = canvas.size();

Advanced Configuration

// Set size with basic configuration
canvas.size({ field: "Cylinders" });

// Set size with custom range and domain
canvas.size({
  field: "Weight",
  as: "continuous",
  range: [10, 50],
  domain: [1000, 5000],
});

shape(shapeField?)

PropertiesTypeRequiredDefaultDescription
shapeFieldstringundefinedName of the field used to derive the shapes of the plots

If no parameter is specified, acts as a getter and returns the current shape configuration.

If shapeField is specified, sets the shape encoding for the visualization and returns the Canvas instance. Shape field should be of dimension type. Setting shape automatically creates a shape legend in the chart.

Examples

// Set shape using field name
canvas.shape("Origin");

// Get current shape configuration
const shape = canvas.shape();

detail(fieldArr?)

PropertiesTypeRequiredDefaultDescription
fieldArrArray<string>undefinedArray of field names that increase the level of detail in the chart

If no parameter is specified, acts as a getter and returns the current detail fields.

If fieldArr is specified, sets the detail fields for the visualization and returns the Canvas instance. Adding dimensions in the detail fields will increase the granularity of the data displayed in the chart, while adding measures will show them in the tooltip.

Examples

// Set detail fields
canvas.detail(["Acceleration"]);

// Get current detail fields
const detail = canvas.detail();

layers(layerDefinitions?)

PropertiesTypeRequiredDefaultDescription
layerDefinitionsArray<LayerDefinition>undefinedAn array of layer definitions
layerDefinitions[].markstring-Mark type of layer
layerDefinitions[].encodingobjectundefinedEncoding configuration of layer
layerDefinitions[].classNamestringundefinedCustom class name applied to the DOM element of layer
layerDefinitions[].outlineboolean | objectundefinedOutline configuration for point, arc, and bar marks
layerDefinitions[].outline.enableboolean-Activates the outline feature
layerDefinitions[].outline.fillbooleanfalseIf true, mark will be filled with color
layerDefinitions[].outline.strokeColorstringundefinedCustom border color; defaults to chart's color if unspecified
layerDefinitions[].outline.widthnumber1Border width in pixels
layerDefinitions[].transformobject{ type: 'identity' }Transform configuration of layer
layerDefinitions[].transform.typestring'identity'Type of transform (e.g., 'stack100percent' for 100% stacked charts)

If no parameter is specified, acts as a getter and returns the current layer definitions.

If layerDefinitions is specified as an empty array, disposes previous layers and renders a default layer based on rows and columns fields. Otherwise, sets the layer definitions for the visualization and returns the Canvas instance.

Examples

// Set multiple layers with different marks
canvas.layers([
  {
    mark: "bar",
    encoding: {
      y: "Acceleration",
    },
  },
  {
    mark: "line",
    encoding: {
      y: "Horsepower",
    },
  },
]);

// Create an outlined bar chart
canvas.layers([
  {
    mark: "bar",
    outline: {
      enable: true,
      fill: false,
      strokeColor: "#ff0000",
      width: 2,
    },
  },
]);

// Get current layer definitions
const layers = canvas.layers();

title(titleString?, options?)

PropertiesTypeRequiredDefaultDescription
titleStringstringundefinedTitle of the chart
optionsobjectSee belowConfiguration of title
options.positionstring'top'Position of the title
options.alignstring'left'Alignment of the title
options.paddingnumber4Padding around the title
options.classNamestring'muze-title-container'Custom class name for the title container

If no parameters are specified, acts as a getter and returns the current title configuration.

If parameters are specified, sets the title for the visualization and returns the Canvas instance.

Examples

// Set simple title
canvas.title("Chart title");

// Set title with HTML content
canvas.title(html`<span style="color:blue;">Chart</span>Title<span></span>`);

// Set title with custom options
canvas.title("Chart Title", {
  position: "top",
  align: "center",
  padding: 8,
});

// Get current title
const title = canvas.title();

subtitle(subtitleString?, options?)

PropertiesTypeRequiredDefaultDescription
subtitleStringstringundefinedSubtitle of the chart
optionsobjectSee belowConfiguration of subtitle
options.positionstring'top'Position of the subtitle
options.alignstring'left'Alignment of the subtitle
options.paddingnumber16Padding around the subtitle
options.maxLinesnumber2Maximum number of lines for subtitle
options.classNamestring'muze-subtitle-container'Custom class name for the subtitle container

If no parameters are specified, acts as a getter and returns the current subtitle configuration.

If parameters are specified, sets the subtitle for the visualization and returns the Canvas instance.

Examples

// Set simple subtitle
canvas.subtitle("Chart subtitle");

// Set subtitle with HTML content
canvas.subtitle(
  html`<span style="color:blue;">Chart</span>SubTitle<span></span>`
);

// Set subtitle with custom options
canvas.subtitle("Chart Subtitle", {
  position: "top",
  align: "center",
  padding: 20,
  maxLines: 3,
});

// Get current subtitle
const subtitle = canvas.subtitle();

mount(domElement?)

PropertiesTypeRequiredDefaultDescription
domElementHTMLElement | stringundefinedRaw DOM node or CSS selector (e.g., '#chart-container' or '.chart-container')

If no parameter is specified, acts as a getter and returns the current mount point.

If domElement is specified, sets the mount point where the canvas will be rendered and returns the Canvas instance.

Examples

// Mount using CSS selector
canvas.mount("#chart");

// Mount using DOM node
canvas.mount(domNode);

// Get current mount point
const node = canvas.mount();

config(config?)

PropertiesTypeRequiredDefaultDescription
configobjectundefinedConfiguration object for the canvas
config.useUTCbooleanfalseGenerate continuous temporal-axis ticks and format supported temporal values in UTC

If no parameter is specified, acts as a getter and returns the current configuration.

If config is specified, sets the configuration for the canvas and returns the Canvas instance.

info

For a detailed list of configuration attributes, see Configuration

Examples

// Set configuration
canvas.config({
  scrollBar: {
    vertical: {
      initialScrollPercent: 50,
    },
    horizontal: {
      initialScrollPercent: 50,
    },
  },
});

// Get current configuration
const config = canvas.config();

useUTC

Set useUTC to true to generate continuous temporal-axis ticks and format supported temporal values in text layers, tooltips, and legends in UTC rather than the browser's local time zone.

Set this option before mounting the canvas:

canvas
  // ...
  .config({
    // ...
    useUTC: true,
    // ...
  })
  // ...
  .mount("#chart");

useUTC changes how Muze generates continuous temporal-axis ticks and formats temporal values; it does not change the underlying timestamps in the input data or parse timezone-less input as UTC.

transform(transformObj)

PropertiesTypeRequiredDefaultDescription
transformObjobject-Object containing named transform functions

Sets data transformation methods for layers. Each key in the object is a unique name that can be referenced in layer definitions' source property. The corresponding value is a function that takes a datamodel, applies operations, and returns a transformed datamodel.

Examples

canvas
  .transform({
    // Create a named data source for layers
    weightChangeModel: (ds) => ds.groupBy([]),
  })
  .layers([
    {
      mark: "bar",
    },
    {
      mark: "text",
      source: "weightChangeModel", // Reference the transform
    },
  ]);

firebolt()

Returns the firebolt instance of canvas.

info

For more details on firebolt, see Firebolt

Examples

// Get firebolt instance
const firebolt = canvas.firebolt();

dispose()

Disposes the canvas instance and cleans up resources.

Examples

// Dispose the canvas instance
canvas.dispose();