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

export-utilities.mddocs/

Export and Utilities

Export capabilities for generating images, validating data, and working with plot schemas and templates.

Capabilities

Image Export

Convert plots to various image formats for saving, sharing, and embedding.

/**
 * Export plot to image data
 * @param gd - Graph div element
 * @param opts - Export options and format settings
 * @returns Promise resolving to image data
 */
function toImage(gd: any, opts?: ImageExportOptions): Promise<string>;

/**
 * Download plot as image file
 * @param gd - Graph div element
 * @param opts - Download options including filename and format
 * @returns Promise resolving when download starts
 */
function downloadImage(gd: any, opts?: DownloadImageOptions): Promise<void>;

interface ImageExportOptions {
  format?: 'png' | 'jpeg' | 'webp' | 'svg' | 'html' | 'json';
  width?: number;
  height?: number;
  scale?: number;
  setBackground?: boolean | 'opaque' | 'transparent';
  imageDataOnly?: boolean;
}

interface DownloadImageOptions extends ImageExportOptions {
  filename?: string;
}

Usage Examples:

// Export as PNG (default)
Plotly.toImage(myDiv, {
    format: 'png',
    width: 800,
    height: 600,
    scale: 2
}).then(function(dataURL) {
    // dataURL contains the image as base64 data URL
    console.log('Image exported');
    
    // Use in img element
    document.getElementById('exported-image').src = dataURL;
});

// Export as SVG with transparent background
Plotly.toImage(myDiv, {
    format: 'svg',
    setBackground: 'transparent'
}).then(function(svgData) {
    // SVG data as string
    console.log('SVG exported');
});

// Download as JPEG
Plotly.downloadImage(myDiv, {
    format: 'jpeg',
    filename: 'my-chart',
    width: 1200,
    height: 800,
    scale: 1
});

// Export high-resolution PNG
Plotly.downloadImage(myDiv, {
    format: 'png',
    filename: 'high-res-chart',
    scale: 3,  // 3x resolution
    setBackground: 'opaque'
});

// Export raw image data only
Plotly.toImage(myDiv, {
    format: 'png',
    imageDataOnly: true
}).then(function(imageData) {
    // Raw image data without data URL prefix
    console.log('Raw image data exported');
});

Data Validation

Validate plot data and layout objects against Plotly.js schema.

/**
 * Validate plot data and layout
 * @param data - Array of trace objects to validate
 * @param layout - Layout object to validate
 * @returns Validation result with errors and warnings
 */
function validate(data: any[], layout?: any): ValidationResult;

interface ValidationResult {
  isValid: boolean;
  errors: ValidationError[];
  warnings: ValidationWarning[];
}

interface ValidationError {
  code: string;
  message: string;
  path: string[];
  trace?: number;
}

interface ValidationWarning {
  code: string;
  message: string;
  path: string[];
  trace?: number;
}

Usage Examples:

// Validate trace data
const data = [{
    x: [1, 2, 3],
    y: [1, 4, 9],
    type: 'scatter',
    invalidProperty: 'should cause warning'
}];

const layout = {
    title: 'My Chart',
    xaxis: { title: 'X Axis' },
    yaxis: { title: 'Y Axis' }
};

const validation = Plotly.validate(data, layout);

if (!validation.isValid) {
    console.log('Validation errors:');
    validation.errors.forEach(error => {
        console.log(`- ${error.message} at ${error.path.join('.')}`);
    });
}

if (validation.warnings.length > 0) {
    console.log('Validation warnings:');
    validation.warnings.forEach(warning => {
        console.log(`- ${warning.message} at ${warning.path.join('.')}`);
    });
}

// Validate before creating plot
function safePlot(gd, data, layout) {
    const validation = Plotly.validate(data, layout);
    
    if (validation.isValid) {
        return Plotly.newPlot(gd, data, layout);
    } else {
        console.error('Invalid plot data:', validation.errors);
        throw new Error('Plot validation failed');
    }
}

Template System

Create and manage plot templates for consistent styling across multiple plots.

/**
 * Generate a template from existing plot
 * @param gd - Graph div element to extract template from
 * @returns Template object with layout and trace defaults
 */
function makeTemplate(gd: any): PlotTemplate;

/**
 * Validate a plot template
 * @param template - Template object to validate
 * @returns Validation result for the template
 */
function validateTemplate(template: PlotTemplate): ValidationResult;

interface PlotTemplate {
  layout?: Partial<Layout>;
  data?: {
    [traceType: string]: Partial<any>;
  };
}

Usage Examples:

// Create template from existing plot
const template = Plotly.makeTemplate(myDiv);

console.log('Generated template:', template);

// Use template for new plots
Plotly.newPlot(newDiv, newData, {
    template: template,
    title: 'Chart with Custom Template'
});

// Validate template
const validationResult = Plotly.validateTemplate(template);
if (validationResult.isValid) {
    console.log('Template is valid');
} else {
    console.log('Template validation errors:', validationResult.errors);
}

// Custom template creation
const customTemplate = {
    layout: {
        font: { family: 'Arial, sans-serif', size: 14, color: '#333' },
        paper_bgcolor: '#f8f9fa',
        plot_bgcolor: 'white',
        colorway: ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728'],
        xaxis: {
            showgrid: true,
            gridcolor: '#e6e6e6',
            showline: true,
            linecolor: '#333'
        },
        yaxis: {
            showgrid: true,
            gridcolor: '#e6e6e6',
            showline: true,
            linecolor: '#333'
        }
    },
    data: {
        scatter: {
            marker: { size: 8 },
            line: { width: 2 }
        },
        bar: {
            marker: {
                line: { width: 1, color: '#333' }
            }
        }
    }
};

// Apply custom template
Plotly.newPlot(myDiv, data, {
    template: customTemplate,
    title: 'Chart with Custom Template'
});

Plot Schema Access

Access the complete Plotly.js schema for dynamic plot generation and validation.

/**
 * Plot schema containing all trace types and attributes
 */
interface PlotSchemaAccess {
  /**
   * Get complete plot schema
   * @returns Complete schema object with all traces and layout options
   */
  get(): PlotSchema;

  /**
   * Traverse attribute tree with callback function
   * @param attrs - Attribute object to traverse
   * @param callback - Function called for each attribute
   * @param level - Current traversal depth
   * @param attrString - Full attribute path as string
   */
  crawl(attrs: any, callback: Function, level?: number, attrString?: string): void;

  /**
   * Check if object is a validation object
   * @param obj - Object to check
   * @returns True if object is a validation object
   */
  isValObject(obj: any): boolean;

  /**
   * Find array attributes in trace definition
   * @param trace - Trace object to analyze
   * @returns Array of attribute names that can contain arrays
   */
  findArrayAttributes(trace: any): string[];

  /**
   * Get validation object for trace attribute
   * @param trace - Trace object
   * @param parts - Attribute path parts array
   * @returns Validation object for the attribute
   */
  getTraceValObject(trace: any, parts: string[]): any;

  /**
   * Get validation object for layout attribute
   * @param fullLayout - Full layout object
   * @param parts - Attribute path parts array
   * @returns Validation object for the attribute
   */
  getLayoutValObject(fullLayout: any, parts: string[]): any;
}

interface PlotSchema {
  traces: {
    [traceType: string]: TraceSchema;
  };
  layout: LayoutSchema;
  frames: FrameSchema;
  animation: AnimationSchema;
  config: ConfigSchema;
}

interface TraceSchema {
  attributes: {
    [attributeName: string]: AttributeSchema;
  };
  meta: {
    description: string;
    categories: string[];
  };
}

interface AttributeSchema {
  valType: string;
  description: string;
  dflt?: any;
  min?: number;
  max?: number;
  values?: any[];
  arrayOk?: boolean;
  role?: string;
}

Usage Examples:

// Get complete schema
const schema = Plotly.PlotSchema.get();

console.log('Available trace types:', Object.keys(schema.traces));

// Explore scatter trace attributes
const scatterSchema = schema.traces.scatter;
console.log('Scatter trace attributes:', Object.keys(scatterSchema.attributes));

// Get attribute details
const markerColorAttr = scatterSchema.attributes['marker.color'];
console.log('Marker color attribute:', {
    type: markerColorAttr.valType,
    description: markerColorAttr.description,
    default: markerColorAttr.dflt
});

// Dynamic plot generation using schema
function generateRandomPlot(traceType) {
    const traceSchema = schema.traces[traceType];
    if (!traceSchema) {
        throw new Error(`Unknown trace type: ${traceType}`);
    }
    
    // Generate trace based on schema
    const trace = { type: traceType };
    
    // Add required attributes
    if (traceSchema.attributes.x) {
        trace.x = [1, 2, 3, 4, 5];
    }
    if (traceSchema.attributes.y) {
        trace.y = [1, 4, 2, 8, 5];
    }
    
    return trace;
}

// Traverse schema attributes with callback
Plotly.PlotSchema.crawl(schema.traces.scatter.attributes, function(attr, attrName, attrs, level, fullAttrString) {
    if (Plotly.PlotSchema.isValObject(attr)) {
        console.log(`Found attribute: ${fullAttrString} (level ${level})`);
        console.log(`Type: ${attr.valType}, Default: ${attr.dflt}`);
    }
});

// Find array attributes in a trace
const arrayAttrs = Plotly.PlotSchema.findArrayAttributes({
    type: 'scatter',
    x: [1, 2, 3],
    y: [1, 4, 9],
    marker: { color: ['red', 'blue', 'green'] }
});
console.log('Array attributes found:', arrayAttrs);

// Get validation object for specific attribute
const markerColorValidation = Plotly.PlotSchema.getTraceValObject(
    { type: 'scatter' }, 
    ['marker', 'color']
);
console.log('Marker color validation:', markerColorValidation);

// Get layout validation object
const titleValidation = Plotly.PlotSchema.getLayoutValObject(
    { title: 'My Chart' },
    ['title']
);
console.log('Title validation:', titleValidation);

Plot Serialization

Methods for serializing and deserializing complete plots.

/**
 * Serialize plot to JSON
 * @param gd - Graph div element
 * @param dataOnly - Include only data, not layout
 * @param layout - Layout object to include
 * @param data - Data array to include
 * @param frames - Animation frames to include
 * @returns JSON representation of the plot
 */
function graphJson(
  gd: any, 
  dataOnly?: boolean, 
  layout?: any, 
  data?: any[], 
  frames?: any[]
): string;

Usage Examples:

// Serialize complete plot
const plotJson = Plotly.Plots.graphJson(myDiv);
console.log('Serialized plot:', plotJson);

// Parse and recreate plot
const plotData = JSON.parse(plotJson);
Plotly.newPlot(newDiv, plotData.data, plotData.layout);

// Serialize only data
const dataJson = Plotly.Plots.graphJson(myDiv, true);
console.log('Data only:', dataJson);

// Save plot state for later restoration
function savePlotState(gd, stateName) {
    const state = Plotly.Plots.graphJson(gd);
    localStorage.setItem(`plot-state-${stateName}`, state);
}

function restorePlotState(gd, stateName) {
    const state = localStorage.getItem(`plot-state-${stateName}`);
    if (state) {
        const plotData = JSON.parse(state);
        return Plotly.react(gd, plotData.data, plotData.layout);
    }
}

Utility Functions

Various utility functions for plot manipulation and analysis.

/**
 * Resize plot to fit container
 * @param gd - Graph div element
 * @returns Promise resolving when resize is complete
 */
function resize(gd: any): Promise<void>;

/**
 * Send plot data to Plotly cloud
 * @param gd - Graph div element  
 * @param options - Cloud upload options
 * @returns Promise resolving with cloud URL
 */
function sendDataToCloud(gd: any, options?: CloudOptions): Promise<string>;

interface CloudOptions {
  filename?: string;
  fileopt?: 'overwrite' | 'new';
  world_readable?: boolean;
  sharing?: 'public' | 'private' | 'secret';
}

Usage Examples:

// Resize plot (useful after container size changes)
window.addEventListener('resize', function() {
    Plotly.Plots.resize(myDiv);
});

// Manual resize
function resizePlot() {
    return Plotly.Plots.resize(myDiv).then(function() {
        console.log('Plot resized');
    });
}

// Cloud upload (requires Plotly account)
Plotly.Plots.sendDataToCloud(myDiv, {
    filename: 'my-chart',
    fileopt: 'overwrite',
    sharing: 'public'
}).then(function(url) {
    console.log('Plot uploaded to:', url);
}).catch(function(error) {
    console.error('Upload failed:', error);
});

Snapshot System

Advanced export and cloning capabilities.

/**
 * Snapshot system for advanced export operations
 */
interface SnapshotSystem {
  /**
   * Clone plot for export without affecting original
   * @param gd - Graph div element
   * @param options - Clone options
   * @returns Cloned plot element
   */
  clone(gd: any, options?: CloneOptions): HTMLElement;

  /**
   * Convert plot to SVG
   * @param gd - Graph div element
   * @param format - Output format
   * @param scale - Resolution scale
   * @returns Promise resolving to SVG data
   */
  toSVG(gd: any, format?: string, scale?: number): Promise<string>;

  /**
   * Convert SVG to raster image
   * @param svg - SVG data
   * @param format - Target format
   * @param scale - Resolution scale
   * @returns Promise resolving to image data
   */
  svgToImg(svg: string, format: string, scale?: number): Promise<string>;
}

interface CloneOptions {
  format?: string;
  height?: number;
  width?: number;
  scale?: number;
}

Usage Examples:

// Clone plot for export
const clonedPlot = Plotly.Snapshot.clone(myDiv, {
    width: 1200,
    height: 800,
    scale: 2
});

// Convert to SVG
Plotly.Snapshot.toSVG(myDiv, 'svg', 2).then(function(svgData) {
    console.log('SVG generated');
    
    // Convert SVG to PNG
    return Plotly.Snapshot.svgToImg(svgData, 'png', 2);
}).then(function(pngData) {
    console.log('PNG generated from SVG');
});

// Advanced export workflow
async function advancedExport(gd, options) {
    try {
        // Clone plot with specific dimensions
        const clone = Plotly.Snapshot.clone(gd, {
            width: options.width,
            height: options.height,
            scale: options.scale
        });
        
        // Generate SVG
        const svg = await Plotly.Snapshot.toSVG(clone, 'svg', options.scale);
        
        // Convert to desired format
        const imageData = await Plotly.Snapshot.svgToImg(
            svg, 
            options.format, 
            options.scale
        );
        
        return imageData;
    } catch (error) {
        console.error('Export failed:', error);
        throw error;
    }
}

Configuration for Export

Global Export Settings

/**
 * Global configuration options affecting export behavior
 */
interface ExportConfig {
  plotlyServerURL?: string;
  showSendToCloud?: boolean;
  showEditInChartStudio?: boolean;
  toImageButtonOptions?: {
    format?: 'png' | 'svg' | 'jpeg' | 'webp';
    filename?: string;
    height?: number;
    width?: number;
    scale?: number;
  };
}

Usage Examples:

// Configure default export options
Plotly.setPlotConfig({
    toImageButtonOptions: {
        format: 'png',
        filename: 'custom-chart',
        height: 800,
        width: 1200,
        scale: 2
    }
});

// Custom export button in mode bar
const config = {
    modeBarButtonsToAdd: [{
        name: 'Export PNG',
        icon: Plotly.Icons.camera,
        click: function(gd) {
            Plotly.downloadImage(gd, {
                format: 'png',
                filename: 'my-chart',
                width: 1920,
                height: 1080,
                scale: 2
            });
        }
    }]
};

Plotly.newPlot(myDiv, data, layout, config);

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