CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-plotly-js

The open source JavaScript graphing library that powers Plotly with comprehensive data visualization capabilities including statistical charts, 3D graphs, scientific visualizations, and interactive plotting features.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

core-plotting.mddocs/

Core Plotting Methods

Essential methods for creating, updating, and managing plots. These form the foundation of all plotly.js operations.

Capabilities

Create New Plot

Creates a new interactive plot from scratch.

/**
 * Creates a new plot in the specified DOM element
 * @param gd - DOM element or element ID where plot will be rendered
 * @param data - Array of trace objects defining the data and chart types
 * @param layout - Layout object defining plot appearance and behavior
 * @param config - Configuration object for plot-level settings
 * @returns Promise that resolves when plot is created
 */
function newPlot(gd, data, layout, config);

Usage Examples:

// Basic scatter plot
Plotly.newPlot('myDiv', [{
    x: [1, 2, 3, 4],
    y: [10, 11, 12, 13],
    type: 'scatter'
}]);

// Multiple traces with layout
Plotly.newPlot('myDiv', [
    {
        x: [1, 2, 3, 4],
        y: [10, 11, 12, 13],
        type: 'scatter',
        name: 'Series 1'
    },
    {
        x: [1, 2, 3, 4],
        y: [16, 18, 17, 19],
        type: 'bar',
        name: 'Series 2'
    }
], {
    title: 'Combined Chart',
    xaxis: { title: 'X Axis' },
    yaxis: { title: 'Y Axis' }
}, {
    responsive: true,
    displayModeBar: true
});

React (Efficient Update)

Efficiently updates a plot by comparing new data with existing data and only updating what has changed.

/**
 * Updates plot efficiently by comparing new vs existing data
 * @param gd - DOM element containing the plot
 * @param data - New array of trace objects
 * @param layout - New layout object
 * @param config - New configuration object
 * @returns Promise that resolves when update is complete
 */
function react(gd, data, layout, config);

Usage Examples:

// Initial plot
await Plotly.newPlot('myDiv', [{
    x: [1, 2, 3],
    y: [1, 4, 9],
    type: 'scatter'
}]);

// Efficient update - only changes what's different
await Plotly.react('myDiv', [{
    x: [1, 2, 3, 4],  // Added new point
    y: [1, 4, 9, 16], // Added new point
    type: 'scatter'
}]);

Restyle Traces

Updates trace properties like data, colors, and styling without affecting layout.

/**
 * Updates trace properties
 * @param gd - DOM element containing the plot
 * @param astr - Property path as string or object with property updates
 * @param val - New value(s) for the property
 * @param traces - Trace indices to update (optional, defaults to all traces)
 * @returns Promise that resolves when restyle is complete
 */
function restyle(gd, astr, val, traces);

Usage Examples:

// Update y-data for all traces
Plotly.restyle('myDiv', 'y', [[5, 10, 15, 20]]);

// Update multiple properties
Plotly.restyle('myDiv', {
    'marker.color': 'red',
    'marker.size': 10
});

// Update specific traces only
Plotly.restyle('myDiv', 'marker.color', 'blue', [0, 2]); // Only traces 0 and 2

// Update different values for different traces
Plotly.restyle('myDiv', 'marker.color', ['red', 'blue', 'green']);

Relayout

Updates layout properties like axes, title, and plot dimensions.

/**
 * Updates layout properties
 * @param gd - DOM element containing the plot
 * @param astr - Property path as string or object with property updates
 * @param val - New value for the property (not needed if astr is object)
 * @returns Promise that resolves when relayout is complete
 */
function relayout(gd, astr, val);

Usage Examples:

// Update title
Plotly.relayout('myDiv', 'title', 'New Plot Title');

// Update axis ranges
Plotly.relayout('myDiv', {
    'xaxis.range': [0, 10],
    'yaxis.range': [0, 20]
});

// Update plot dimensions
Plotly.relayout('myDiv', {
    width: 800,
    height: 600
});

Update (Combined Restyle and Relayout)

Updates both trace and layout properties in a single operation.

/**
 * Updates both trace and layout properties
 * @param gd - DOM element containing the plot
 * @param traceUpdate - Object with trace property updates
 * @param layoutUpdate - Object with layout property updates
 * @param traces - Trace indices to update (optional)
 * @returns Promise that resolves when update is complete
 */
function update(gd, traceUpdate, layoutUpdate, traces);

Usage Examples:

// Update traces and layout together
Plotly.update('myDiv', 
    { 'marker.color': 'red' },      // Trace updates
    { 'title': 'Updated Chart' }    // Layout updates
);

// Update specific traces with layout changes
Plotly.update('myDiv',
    { 'y': [[1, 2, 3, 4]] },
    { 'yaxis.title': 'New Y Label' },
    [0]  // Only update trace 0
);

Redraw

Forces a complete redraw of the plot. Useful when manual DOM changes have been made.

/**
 * Forces a complete redraw of the plot
 * @param gd - DOM element containing the plot
 * @returns Promise that resolves when redraw is complete
 */
function redraw(gd);

Usage Examples:

// Force complete redraw
await Plotly.redraw('myDiv');

// Often used after manual DOM manipulation
document.getElementById('myDiv').style.width = '800px';
await Plotly.redraw('myDiv');

Purge

Completely removes the plot and cleans up all associated data, event listeners, and DOM elements.

/**
 * Removes plot and cleans up all associated data
 * @param gd - DOM element containing the plot
 * @returns The gd element that was purged
 */
function purge(gd);

Usage Examples:

// Clean up plot before removing from DOM
Plotly.purge('myDiv');
document.getElementById('myDiv').remove();

// Clean up before creating new plot
Plotly.purge('myDiv');
Plotly.newPlot('myDiv', newData, newLayout);

Trace Management

Methods for dynamically adding, removing, and reordering traces.

/**
 * Adds new traces to existing plot
 * @param gd - DOM element containing the plot
 * @param traces - Single trace object or array of trace objects to add
 * @param newIndices - Positions where traces should be inserted
 * @returns Promise that resolves when traces are added
 */
function addTraces(gd, traces, newIndices);

/**
 * Removes traces from plot
 * @param gd - DOM element containing the plot
 * @param indices - Index or array of indices of traces to remove
 * @returns Promise that resolves when traces are removed
 */
function deleteTraces(gd, indices);

/**
 * Reorders traces in the plot
 * @param gd - DOM element containing the plot
 * @param currentIndices - Current indices of traces to move
 * @param newIndices - New positions for the traces
 * @returns Promise that resolves when traces are moved
 */
function moveTraces(gd, currentIndices, newIndices);

Usage Examples:

// Add a new trace
await Plotly.addTraces('myDiv', {
    x: [1, 2, 3],
    y: [2, 4, 6],
    type: 'scatter',
    name: 'New Series'
});

// Add multiple traces at specific positions
await Plotly.addTraces('myDiv', [
    { x: [1, 2], y: [1, 4], type: 'scatter' },
    { x: [1, 2], y: [2, 8], type: 'bar' }
], [1, 3]); // Insert at positions 1 and 3

// Remove traces
await Plotly.deleteTraces('myDiv', [0, 2]); // Remove traces 0 and 2

// Reorder traces
await Plotly.moveTraces('myDiv', [0, 1], [1, 0]); // Swap first two traces

Shape Management

Methods for managing interactive shapes on plots.

/**
 * Delete currently active shape
 * @param gd - DOM element containing the plot
 * @returns Updated plot element
 */
function deleteActiveShape(gd: any): any;

Usage Examples:

// Delete active shape when user presses delete key
document.addEventListener('keydown', function(event) {
    if (event.key === 'Delete' || event.key === 'Backspace') {
        Plotly.deleteActiveShape('myDiv');
    }
});

// Delete active shape with custom button
function deleteCurrentShape() {
    Plotly.deleteActiveShape('myDiv');
}

// Use in editable mode with shape drawing
Plotly.newPlot('myDiv', data, layout, {
    editable: true,
    modeBarButtonsToAdd: [{
        name: 'Delete Shape',
        icon: Plotly.Icons.eraseshape,
        click: function(gd) {
            Plotly.deleteActiveShape(gd);
        }
    }]
});

Global Configuration

Set global configuration options that affect all plots.

/**
 * Set global plot configuration
 * @param config - Global configuration object
 */
function setPlotConfig(config: GlobalConfig): void;

interface GlobalConfig {
  plotlyServerURL?: string;
  showSendToCloud?: boolean;
  showEditInChartStudio?: boolean;
  linkText?: string;
  showTips?: boolean;
  locale?: string;
  locales?: { [locale: string]: any };
  toImageButtonOptions?: {
    format?: 'png' | 'svg' | 'jpeg' | 'webp';
    filename?: string;
    height?: number;
    width?: number;
    scale?: number;
  };
}

Usage Examples:

// Set global defaults
Plotly.setPlotConfig({
    showSendToCloud: false,
    showEditInChartStudio: false,
    locale: 'en-US',
    toImageButtonOptions: {
        format: 'png',
        filename: 'plot',
        scale: 2
    }
});

// Configure for offline use
Plotly.setPlotConfig({
    showSendToCloud: false,
    showEditInChartStudio: false,
    plotlyServerURL: false
});

// Set default export options
Plotly.setPlotConfig({
    toImageButtonOptions: {
        format: 'svg',
        width: 1200,
        height: 800,
        scale: 1
    }
});

Extend and Prepend Data

Methods for efficiently adding data points to existing traces.

/**
 * Appends new data points to existing traces
 * @param gd - DOM element containing the plot
 * @param update - Object with arrays of new data points
 * @param indices - Trace indices to update
 * @param maxPoints - Maximum number of points to keep per trace
 * @returns Promise that resolves when data is extended
 */
function extendTraces(gd, update, indices, maxPoints);

/**
 * Prepends new data points to existing traces
 * @param gd - DOM element containing the plot  
 * @param update - Object with arrays of new data points
 * @param indices - Trace indices to update
 * @param maxPoints - Maximum number of points to keep per trace
 * @returns Promise that resolves when data is prepended
 */
function prependTraces(gd, update, indices, maxPoints);

Usage Examples:

// Add new points to the end of traces
await Plotly.extendTraces('myDiv', {
    x: [[5, 6]], // New x values for trace 0
    y: [[25, 36]] // New y values for trace 0
}, [0]);

// Add points with maximum limit (useful for streaming data)
await Plotly.extendTraces('myDiv', {
    x: [[new Date()]],
    y: [[Math.random()]]
}, [0], 100); // Keep only last 100 points

// Add points to beginning
await Plotly.prependTraces('myDiv', {
    x: [[-1, 0]],
    y: [[1, 0]]
}, [0]);

Parameter Types

Graph Division (gd)

// Can be a DOM element or string ID
type GraphDiv = HTMLElement | string;

Trace Object

interface Trace {
  type: string;
  x?: any[];
  y?: any[];
  z?: any[];
  mode?: string;
  name?: string;
  visible?: boolean | 'legendonly';
  showlegend?: boolean;
  marker?: Partial<Marker>;
  line?: Partial<Line>;
  fill?: string;
  fillcolor?: string;
  text?: string | string[];
  hovertext?: string | string[];
  hovertemplate?: string;
  hoverinfo?: string;
}

Layout Object

interface Layout {
  title?: string | Partial<Title>;
  width?: number;
  height?: number;
  autosize?: boolean;
  margin?: Partial<Margin>;
  paper_bgcolor?: string;
  plot_bgcolor?: string;
  font?: Partial<Font>;
  xaxis?: Partial<Axis>;
  yaxis?: Partial<Axis>;
  legend?: Partial<Legend>;
  annotations?: Partial<Annotation>[];
  shapes?: Partial<Shape>[];
  images?: Partial<Image>[];
}

Config Object

interface Config {
  staticPlot?: boolean;
  editable?: boolean;
  displayModeBar?: boolean | 'hover';
  modeBarButtonsToRemove?: string[];
  responsive?: boolean;
  locale?: string;
  scrollZoom?: boolean;
  doubleClick?: 'reset' | 'autosize' | 'reset+autosize' | false;
}

Install with Tessl CLI

npx tessl i tessl/npm-plotly-js

docs

3d-charts.md

basic-charts.md

core-plotting.md

events.md

export-utilities.md

index.md

layout.md

statistical-charts.md

tile.json