CanvasXpress Integrations Guide

Seamlessly connect CanvasXpress to your favorite data science and web frameworks.

CanvasXpress is designed to fit effortlessly into your existing development workflows, whether you're working in a web environment, a data science notebook, or with a backend framework. Below is a guide on how to integrate CanvasXpress with popular technologies.

General Installation

The CanvasXpress library consists of two files: a CSS file (canvasXpress.css) and a JavaScript file (canvasXpress.min.js). You can include these files in the <head> section of your web page.

CanvasXpress Website:

<link rel="stylesheet" href="https://www.canvasxpress.org/dist/canvasXpress.css" type="text/css"/>
<script type="text/javascript" src="https://www.canvasxpress.org/dist/canvasXpress.min.js"></script>

Local Files:

<link rel="stylesheet" href="path-to-canvasXpress.css" type="text/css"/>
<script type="text/javascript" src="path-to-canvasXpress.min.js"></script>

You can also install the library via a package manager for a more modern workflow:

NPM Installation:

npm install canvasxpress

Yarn Installation:

yarn add canvasxpress

HTML (Standalone)

Using CanvasXpress in a standalone HTML file is the simplest way to get started. You only need to include the CSS and JavaScript files, create a canvas element, and then write a script to initialize the object with your data and configuration.

<!-- In your HTML <head> -->
<link rel="stylesheet" href="https://www.canvasxpress.org/dist/canvasXpress.css" type="text/css"/>
<script type="text/javascript" src="https://www.canvasxpress.org/dist/canvasXpress.min.js"></script>

<!-- In your HTML <body> -->
<canvas id="canvasId" width="540" height="540"></canvas>

<!-- Script to initialize the object -->
<script>
  var data = {
    "y": {
      "vars": ["Gene1"],
      "smps": ["Smp1", "Smp2", "Smp3"],
      "data": [[10, 35, 88]]
    }
  };
  var conf = {
    "graphType": "Bar"
  };
  var cX = new CanvasXpress("canvasId", data, conf);
</script>

Python

For detailed information on installing the CanvasXpress Python library, please refer to the PyPI project. CanvasXpress can be used with popular frameworks like Flask and Django (below), and there are dedicated packages for Jupyter notebooks, Streamlit and Dash.

Example with Flask:

# bar.py
import json
from flask import Flask, render_template

app = Flask(__name__)

\@app.route('/')
def get_canvasxpress_js_chart():
  data = {
    "y": {
      "vars": ["Gene1"],
      "smps": ["Smp1", "Smp2", "Smp3"],
      "data": [[10, 35, 88]]
    }
  }

  cx_object_def = {
    "renderTo": "canvasId",
    "data": data,
    "config": {
      "graphType": "Bar"
    }
  }

  return render_template(
    'bar.html',
    bar_graph=json.dumps(cx_object_def)
  )

if __name__ == '__main__':
  app.run(debug=True)
<!-- templates/bar.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Flask CanvasXpress Example</title>
    <link rel='stylesheet' href='https://www.canvasxpress.org/dist/canvasXpress.css' type='text/css'/>
    <script type='text/javascript' src='https://www.canvasxpress.org/dist/canvasXpress.min.js'></script>
  </head>
  <body>
    <canvas id='canvasId' width='540' height='540'></canvas>
    <script type="text/javascript">
      var cxConfig = {{ bar_graph | safe }};
      new CanvasXpress(cxConfig);
    </script>
  </body>
</html>

Notebooks: Jupyter, JupyterLab, Colab, marimo & VS Code

Three small packages render CanvasXpress charts inside notebook cells. All of them take the same {"data", "config"} spec as new CanvasXpress({...}), so any example from the gallery or the R / Python packages works unchanged, and the library is loaded from the CanvasXpress CDN — there is no JavaScript build step.

Notebook widgetcanvasxpress-anywidget, built on anywidget, works in Jupyter, JupyterLab, Google Colab, VS Code and marimo. Assigning to a widget attribute re-renders the chart in place.

pip install canvasxpress-anywidget
from canvasxpress_anywidget import CanvasXpress

CanvasXpress(
    data={"y": {"vars": ["Revenue"],
                "smps": ["Q1", "Q2", "Q3", "Q4"],
                "data": [[10, 14, 9, 17]]}},
    config={"graphType": "Bar", "title": "Quarterly Revenue"},
)

IPython cell magiccanvasxpress-magic adds a %%cxplot magic: the cell body is the JSON spec, no Python code required.

pip install canvasxpress-magic
%load_ext canvasxpress_magic

%%cxplot --width 800 --height 500
{"data": {"y": {"vars": ["Revenue"],
                "smps": ["Q1", "Q2", "Q3", "Q4"],
                "data": [[10, 14, 9, 17]]}},
 "config": {"graphType": "Bar", "title": "Quarterly Revenue"}}

VS Code notebook renderer — the CanvasXpress Notebook Renderer extension draws any cell output with the mime type application/canvasxpress+json as an interactive chart, from any kernel (Python, R, Julia…). Install it from the Extensions view (search “CanvasXpress”), then emit the mime type:

# Python kernel
from IPython.display import display
spec = {"data": {...}, "config": {"graphType": "Bar"}}
display({"application/canvasxpress+json": spec}, raw=True)

# R kernel
IRdisplay::publish_mimebundle(list("application/canvasxpress+json" = spec_list))

Streamlit

canvasxpress-streamlit renders a chart as a Streamlit component. Arguments: data, config, width (600), height (400) and an optional widget key.

pip install canvasxpress-streamlit
import streamlit as st
from canvasxpress_streamlit import canvasxpress

st.title("CanvasXpress in Streamlit")
canvasxpress(
    data={"y": {"vars": ["Revenue"],
                "smps": ["Q1", "Q2", "Q3", "Q4"],
                "data": [[10, 14, 9, 17]]}},
    config={"graphType": "Bar", "title": "Quarterly Revenue"},
    height=420,
)

Dash

canvasxpress-dash provides a CanvasXpress(...) component that drops into any Dash layout; it returns a self-contained html.Iframe that renders one chart.

pip install canvasxpress-dash
from dash import Dash, html
from canvasxpress_dash import CanvasXpress

app = Dash(__name__)
app.layout = html.Div([
    html.H2("CanvasXpress in Dash"),
    CanvasXpress(
        data={"y": {"vars": ["Revenue"],
                    "smps": ["Q1", "Q2", "Q3", "Q4"],
                    "data": [[10, 14, 9, 17]]}},
        config={"graphType": "Bar", "title": "Quarterly Revenue"},
        height=420,
    ),
])

if __name__ == "__main__":
    app.run(debug=True)

R

The CanvasXpress R library allows you to generate conventional plots directly from the R console, RStudio, or seamlessly embedded in Shiny web applications. For more information, visit our GitHub repository.

y <- read.table("https://www.canvasxpress.org/data/cX-irist-dat.txt",
  header = TRUE,
  sep = "	",
  quote = "",
  row.names = 1,
  fill = TRUE,
  check.names = FALSE,
  stringsAsFactors = FALSE)

z <- read.table("https://www.canvasxpress.org/data/cX-irist-var.txt",
  header = TRUE,
  sep = "	",
  quote = "",
  row.names = 1,
  fill = TRUE,
  check.names = FALSE,
  stringsAsFactors = FALSE)

canvasXpress(
  data = y,
  varAnnot = z,
  graphType = "Scatter3D",
  colorBy = "Species",
  ellipseBy = "Species",
  xAxis = list("Sepal.Length"),
  yAxis = list("Petal.Width"),
  zAxis = list("Petal.Length"),
  theme = "CanvasXpress",
  title = "Iris Data Set",
  axisTickScaleFontFactor = 0.5,
  axisTitleScaleFontFactor = 0.5)

Bioconductor

CanvasXpressBio bridges CanvasXpress to the core Bioconductor classes: cxplot() renders a SummarizedExperiment — and anything that extends it, such as SingleCellExperiment or DESeqDataSet — as an interactive heatmap carrying its rowData and colData annotations, and cxvolcano() draws a volcano plot from a differential-expression result table. The package has been submitted to Bioconductor and is under review; until it ships in a Bioconductor release, install it from GitHub:

remotes::install_github("neuhausi/CanvasXpressBio")

library(CanvasXpressBio)
cxplot(se, n = 25, title = "Top 25 most variable genes")   # se: a SummarizedExperiment
cxvolcano(res, title = "Differential expression")           # res: DESeq2::results() or a data frame

React

CanvasXpress can be implemented with any React-powered frameworks. For more information and examples, visit our GitHub repository or check out this online example.

import React from 'react';
import ReactDOM from 'react-dom';
import CanvasXpressReact from 'canvasxpress-react';

class Bar extends React.Component {
  render() {
    var target = "canvas";
    var data = {
      "y": {
      "vars": ["Variable1"],
      "smps": ["Sample1", "Sample2", "Sample3"],
      "data": [[33, 48, 55]]
      }
    };
    var config = {
      "graphOrientation": "vertical",
      "graphType": "Bar",
      "theme": "CanvasXpress",
      "title": "Simple Bar graph"
    };
    return (
      <CanvasXpressReact target={target} data={data} config={config} width={500} height={500} />
    )
  }
}
var reactapp = document.createElement("div");
document.body.appendChild(reactapp);
ReactDOM.render(<Bar />, reactapp)

Vue.js

CanvasXpress also supports integration with Vue.js. For more information and examples, visit our GitHub repository.

<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel='stylesheet' href='https://www.canvasxpress.org/dist/canvasXpress.css' type='text/css' />
  </head>
  <body>
    <div id="app">
      <div style="width: 600px; height: 600px;">
        <canvas id="canvasId" style="position:absolute;" width="600" height="600"></canvas>
      </div>
    </div>
    <!-- CanvasXpress -->
    <script type="text/javascript" src="https://www.canvasxpress.org/dist/canvasXpress.min.js"></script>
    <!-- Vue -->
    <script src="https://unpkg.com/vue\@3/dist/vue.global.js"></script>
    <!-- Vue Script -->
    <script type="module">
      const { createApp } = Vue
      createApp({
        setup() {
          const charts = {}
          function foo() {
            var data = {
              "y": {
                "vars": [ "Gene1"],
                "smps": [ "Smp1", "Smp2", "Smp3" ],
                "data": [ [ 10, 35, 88 ] ]
              }
            };
            var conf = {
              "graphType": "Bar"
            };
            charts.cx = new CanvasXpress("canvasId", data, conf);
          }
          return {
            charts,
            foo
          }
        }
      }).mount('#app')
    </script>
  </body>
</html>

Quarto

The CanvasXpress Quarto extension adds a shortcode that embeds a live chart from a JSON spec file in any HTML-format Quarto document.

quarto add neuhausi/canvasxpress-quarto
{{< canvasxpress spec.json >}}
{{< canvasxpress spec="spec.json" width="800" height="300" >}}

Observable

A single ES module, canvasxpress.js, works in both Observable Framework and classic notebooks: canvasxpress(spec, {width, height}) returns a self-contained element. In Observable Framework, copy the file into your project (e.g. src/components/) and import it; in a classic notebook, import it straight from the CDN:

canvasxpress = (await import("https://cdn.jsdelivr.net/gh/neuhausi/canvasxpress-js@master/observable/canvasxpress.js")).canvasxpress

canvasxpress({
  data: {y: {vars: ["Revenue"], smps: ["Q1", "Q2", "Q3", "Q4"], data: [[10, 14, 9, 17]]}},
  config: {graphType: "Bar", title: "Quarterly Revenue"}
})

PHP & Ruby-on-Rails

CanvasXpress integrates with various backend web services. Here are examples for both PHP and Ruby-on-Rails.

Example with PHP:

<?php
\$cx = array(
  "y" => array(
  "vars" => array("Gene1"),
  "smps" => array("Smp1", "Smp2", "Smp3"),
  "data" => array(array(10, 35, 88))
  ),
  "graphType" => "Bar");?>

<html>
  <head>
    <meta charset="UTF-8">
    <title>PHP CanvasXpress Example</title>
    <link rel='stylesheet' href='https://www.canvasxpress.org/dist/canvasXpress.css' type='text/css'/>
    <script type='text/javascript' src='https://www.canvasxpress.org/dist/canvasXpress.min.js'></script>
  </head>
  <body>
    <canvas id='canvasId' width='540' height='540'></canvas>
    <script type="text/javascript">
      var data = <?php echo json_encode(\$cx, JSON_NUMERIC_CHECK); ?>;
      var cX = new CanvasXpress('canvasId', data);
    </script>
  </body>
</html>

Example with Ruby-on-Rails:

For more information on integrating with Ruby-on-Rails, visit our GitHub repository.