tslab icon indicating copy to clipboard operation
tslab copied to clipboard

Two solutions to draw charts & plots!

Open dbuezas opened this issue 4 years ago • 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

dbuezas avatar Mar 01 '21 20:03 dbuezas

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

dbuezas avatar Mar 07 '21 22:03 dbuezas

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

yunabe avatar Mar 10 '21 11:03 yunabe

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

dbuezas avatar Aug 02 '21 15:08 dbuezas

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>
`);

KhalfaniW avatar Nov 28 '22 02:11 KhalfaniW

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

unexpected error: Error: Unexpected pending rebuildTimer

ChuckJonas avatar Aug 11 '23 05:08 ChuckJonas