yunabe/tslab

Two solutions to draw charts & plots!

Opened this issue · 5 comments

Is there any recommended way to output charts & plots?

I managed this using gnuplot but it feels quite hacky.

import * as tslab from "tslab";
import gnuplot from 'gnuplot';
async function plot(code:string) {
    const plot = gnuplot().println(code, {end:true});
    function streamToString (stream) {
        const chunks = [];
        return new Promise((resolve, reject) => {
            stream.on('data', (chunk) => chunks.push(chunk));
            stream.on('error', (err) => reject(err));
            stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
        })
    };
    const str = await streamToString(plot)
    tslab.display.html('<div style="width:100%">'+str as string+"</div>");
}

Usage:

image

I needed some more advanced plots so I made a Plotly.js integration, which is interactive and much fancier.

Instructions

add this (uncompressed) file to the folder where you are working:
plot.ts.zip
(npm i @types/plotly.js to get types or remove the typings from the file. The runtime is fetched from a cdn)

Then use like this

import { newPlot } from "./plot";
newPlot([{
    x: [1, 2, 3, 4, 5],
    y: [1, 2, 4, 8, 16]
}], {
    margin: { t: 0 } 
});

Shift+Enter will give you this:

image

All controls work

plotly

These examples are really cool!

David, are you interested in adding your code into the examples?
Example notebooks are maintained in https://github.com/yunabe/tslab-examples

This is now an npm package with better type support and easy install (npm i tslab-plotly)

https://github.com/dbuezas/tslab-plotly
https://www.npmjs.com/package/tslab-plotly

Here is a simple example of how to make a Datatable

tslab.display.html(`
<div id="table-container"></div>
  <script type="module">
 import tableify from "https://cdn.skypack.dev/tableify";
import {DataTable} from "https://cdn.skypack.dev/simple-datatables"


const testData = [
  {
    mountain: "Everest",
    height: 8848,
    chain: "Himalaya"
  },
  {
    mountain: "Fuji",
    height: 3776,
    country: "Japan",
    type: "volcano"
  },
  {
    mountain: "Kilimanjaro",
    height: 5895,
    country: "Tanzania",
    type: "volcano"
  }
];

document.getElementById("table-container").innerHTML = tableify(testData);
const dataTable = new DataTable("#table-container>table");

  </script>
`);

types are broken on tslab-plotly and @dbuezas embedded solution returns the following error:

unexpected error: Error: Unexpected pending rebuildTimer