CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-plotly-js-dist

JavaScript data visualization library for creating interactive charts, graphs, and scientific visualizations

81

1.02x
Overview
Eval results
Files

data-updates.mddocs/

Data Updates

Functions for updating trace data and layout properties of existing plots without recreating them. These functions provide efficient ways to modify plots while preserving performance and user interactions.

Capabilities

restyle

Updates trace properties of existing traces. Can modify styling, data, or any trace-level attributes.

/**
 * Updates trace attributes of existing traces
 * @param graphDiv - DOM element ID (string) or element reference
 * @param update - Object with attribute paths as keys and new values, or attribute string with value
 * @param traces - Array of trace indices to update, or single index (optional, defaults to all traces)
 * @returns Promise that resolves to the graph div element
 */
function restyle(
  graphDiv: string | HTMLElement,
  update: {[attributePath: string]: any} | string,
  traces?: number | number[]
): Promise<HTMLElement>;

// Alternative signature for single attribute
function restyle(
  graphDiv: string | HTMLElement,
  attributePath: string,
  value: any,
  traces?: number | number[]
): Promise<HTMLElement>;

Usage Examples:

import Plotly from 'plotly.js-dist';

// Update y data for first trace
await Plotly.restyle('chart', {'y': [[5, 6, 7, 8]]}, [0]);

// Update marker color for all traces
await Plotly.restyle('chart', {'marker.color': 'red'});

// Update multiple attributes at once
await Plotly.restyle('chart', {
  'marker.color': 'blue',
  'marker.size': 10,
  'line.width': 3
}, [0]);

// Update specific trace by index
await Plotly.restyle('chart', {'name': 'Updated Series'}, [1]);

// Single attribute syntax
await Plotly.restyle('chart', 'marker.color', 'green', [0]);

// Update data arrays with different values per trace
await Plotly.restyle('chart', {
  'y': [[1, 2, 3], [4, 5, 6]]  // First array for trace 0, second for trace 1
}, [0, 1]);

relayout

Updates layout properties of the plot. Can modify axes, titles, styling, and any layout-level configuration.

/**
 * Updates layout attributes of an existing plot
 * @param graphDiv - DOM element ID (string) or element reference  
 * @param update - Object with layout attribute paths as keys and new values
 * @returns Promise that resolves to the graph div element
 */
function relayout(
  graphDiv: string | HTMLElement,
  update: {[attributePath: string]: any}
): Promise<HTMLElement>;

Usage Examples:

// Update plot title
await Plotly.relayout('chart', {'title': 'New Chart Title'});

// Update axis properties
await Plotly.relayout('chart', {
  'xaxis.title': 'Time (seconds)',
  'yaxis.title': 'Value',
  'xaxis.range': [0, 10],
  'yaxis.range': [0, 100]
});

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

// Update multiple layout properties
await Plotly.relayout('chart', {
  'title': 'Updated Chart',
  'plot_bgcolor': 'lightgray',
  'paper_bgcolor': 'white',
  'font.size': 14,
  'showlegend': false
});

// Update axis range (useful for zooming programmatically)
await Plotly.relayout('chart', {
  'xaxis.range': [new Date('2023-01-01'), new Date('2023-12-31')]
});

update

Combines restyle and relayout operations in a single function call for efficiency. Ideal when updating both trace and layout properties simultaneously.

/**
 * Combined restyle and relayout in a single call
 * @param graphDiv - DOM element ID (string) or element reference
 * @param traceUpdate - Object with trace attribute updates (same format as restyle)
 * @param layoutUpdate - Object with layout attribute updates (same format as relayout)
 * @param traces - Array of trace indices for trace updates (optional, defaults to all)
 * @returns Promise that resolves to the graph div element
 */
function update(
  graphDiv: string | HTMLElement,
  traceUpdate: {[attributePath: string]: any},
  layoutUpdate: {[attributePath: string]: any},
  traces?: number | number[]
): Promise<HTMLElement>;

Usage Examples:

// Update both trace data and layout title
await Plotly.update('chart', 
  {'y': [[10, 20, 30]]},  // Trace update
  {'title': 'Updated Data and Title'}  // Layout update
);

// Update styling and layout together
await Plotly.update('chart',
  {
    'marker.color': 'red',
    'marker.size': 12
  },
  {
    'plot_bgcolor': 'lightblue',
    'xaxis.gridcolor': 'white'
  },
  [0, 1]  // Apply trace updates to first two traces
);

// Complex update with multiple changes
await Plotly.update('chart',
  {
    'x': [[1, 2, 3, 4, 5]],
    'y': [[5, 10, 15, 20, 25]],
    'mode': 'lines+markers',
    'name': 'Updated Series'
  },
  {
    'title': 'Real-time Data',
    'xaxis.title': 'Time',
    'yaxis.title': 'Measurement',
    'width': 900
  }
);

Attribute Path Syntax

All update functions use dot notation to specify nested attributes:

// Examples of attribute paths
'marker.color'              // Marker color
'marker.line.width'         // Marker outline width  
'line.color'               // Line color
'xaxis.range'              // X-axis range
'xaxis.title.text'         // X-axis title text
'legend.bgcolor'           // Legend background color
'annotations[0].text'      // First annotation text
'shapes[1].fillcolor'      // Second shape fill color

Array Updates

When updating arrays, wrap values in arrays to specify per-trace values:

// Update y data for multiple traces
await Plotly.restyle('chart', {
  'y': [
    [1, 2, 3, 4],      // Data for first trace
    [5, 6, 7, 8],      // Data for second trace  
    [9, 10, 11, 12]    // Data for third trace
  ]
}, [0, 1, 2]);

// Update single attribute for multiple traces
await Plotly.restyle('chart', {
  'marker.color': ['red', 'blue', 'green']  // Colors for three traces
}, [0, 1, 2]);

Event Handling

Update functions emit specific events:

interface UpdateEvents {
  'plotly_restyle': (eventData: RestyleEvent) => void;
  'plotly_relayout': (eventData: RelayoutEvent) => void;
  'plotly_update': (eventData: UpdateEvent) => void;
}

interface RestyleEvent {
  [attributePath: string]: any[];
}

interface RelayoutEvent {
  [attributePath: string]: any;
}

interface UpdateEvent {
  data: RestyleEvent;
  layout: RelayoutEvent;
}

Usage Examples:

const chartDiv = document.getElementById('my-chart');

chartDiv.on('plotly_restyle', (eventData) => {
  console.log('Trace attributes changed:', eventData);
});

chartDiv.on('plotly_relayout', (eventData) => {
  console.log('Layout changed:', eventData);
  
  // Detect axis range changes (user zoom/pan)
  if (eventData['xaxis.range[0]'] !== undefined) {
    console.log('X-axis range changed');
  }
});

Performance Tips

  • Use update() instead of separate restyle() and relayout() calls when changing both
  • Batch multiple attribute changes in a single call rather than multiple separate calls
  • Use trace indices to limit updates to specific traces when possible
  • Consider using react() for large-scale changes instead of multiple update calls

Common Update Patterns

// Toggle trace visibility
await Plotly.restyle('chart', {'visible': 'legendonly'}, [0]);
await Plotly.restyle('chart', {'visible': true}, [0]);

// Animate-like updates with smooth transitions
for (let i = 0; i < 100; i++) {
  const newY = data.map(d => d + Math.sin(i * 0.1));
  await Plotly.restyle('chart', {'y': [newY]}, [0]);
  await new Promise(resolve => setTimeout(resolve, 50));
}

// Conditional styling based on data
const colors = yData.map(y => y > threshold ? 'red' : 'blue');
await Plotly.restyle('chart', {'marker.color': [colors]}, [0]);

// Update axis range based on data
const maxY = Math.max(...yData);
await Plotly.relayout('chart', {'yaxis.range': [0, maxY * 1.1]});

Install with Tessl CLI

npx tessl i tessl/npm-plotly-js-dist

docs

animation.md

chart-types.md

core-plotting.md

data-streaming.md

data-updates.md

export-utilities.md

index.md

interactive-components.md

layout-system.md

trace-management.md

tile.json