0
# Export and Utilities
1
2
Export capabilities for generating images, validating data, and working with plot schemas and templates.
3
4
## Capabilities
5
6
### Image Export
7
8
Convert plots to various image formats for saving, sharing, and embedding.
9
10
```javascript { .api }
11
/**
12
* Export plot to image data
13
* @param gd - Graph div element
14
* @param opts - Export options and format settings
15
* @returns Promise resolving to image data
16
*/
17
function toImage(gd: any, opts?: ImageExportOptions): Promise<string>;
18
19
/**
20
* Download plot as image file
21
* @param gd - Graph div element
22
* @param opts - Download options including filename and format
23
* @returns Promise resolving when download starts
24
*/
25
function downloadImage(gd: any, opts?: DownloadImageOptions): Promise<void>;
26
27
interface ImageExportOptions {
28
format?: 'png' | 'jpeg' | 'webp' | 'svg' | 'html' | 'json';
29
width?: number;
30
height?: number;
31
scale?: number;
32
setBackground?: boolean | 'opaque' | 'transparent';
33
imageDataOnly?: boolean;
34
}
35
36
interface DownloadImageOptions extends ImageExportOptions {
37
filename?: string;
38
}
39
```
40
41
**Usage Examples:**
42
43
```javascript
44
// Export as PNG (default)
45
Plotly.toImage(myDiv, {
46
format: 'png',
47
width: 800,
48
height: 600,
49
scale: 2
50
}).then(function(dataURL) {
51
// dataURL contains the image as base64 data URL
52
console.log('Image exported');
53
54
// Use in img element
55
document.getElementById('exported-image').src = dataURL;
56
});
57
58
// Export as SVG with transparent background
59
Plotly.toImage(myDiv, {
60
format: 'svg',
61
setBackground: 'transparent'
62
}).then(function(svgData) {
63
// SVG data as string
64
console.log('SVG exported');
65
});
66
67
// Download as JPEG
68
Plotly.downloadImage(myDiv, {
69
format: 'jpeg',
70
filename: 'my-chart',
71
width: 1200,
72
height: 800,
73
scale: 1
74
});
75
76
// Export high-resolution PNG
77
Plotly.downloadImage(myDiv, {
78
format: 'png',
79
filename: 'high-res-chart',
80
scale: 3, // 3x resolution
81
setBackground: 'opaque'
82
});
83
84
// Export raw image data only
85
Plotly.toImage(myDiv, {
86
format: 'png',
87
imageDataOnly: true
88
}).then(function(imageData) {
89
// Raw image data without data URL prefix
90
console.log('Raw image data exported');
91
});
92
```
93
94
### Data Validation
95
96
Validate plot data and layout objects against Plotly.js schema.
97
98
```javascript { .api }
99
/**
100
* Validate plot data and layout
101
* @param data - Array of trace objects to validate
102
* @param layout - Layout object to validate
103
* @returns Validation result with errors and warnings
104
*/
105
function validate(data: any[], layout?: any): ValidationResult;
106
107
interface ValidationResult {
108
isValid: boolean;
109
errors: ValidationError[];
110
warnings: ValidationWarning[];
111
}
112
113
interface ValidationError {
114
code: string;
115
message: string;
116
path: string[];
117
trace?: number;
118
}
119
120
interface ValidationWarning {
121
code: string;
122
message: string;
123
path: string[];
124
trace?: number;
125
}
126
```
127
128
**Usage Examples:**
129
130
```javascript
131
// Validate trace data
132
const data = [{
133
x: [1, 2, 3],
134
y: [1, 4, 9],
135
type: 'scatter',
136
invalidProperty: 'should cause warning'
137
}];
138
139
const layout = {
140
title: 'My Chart',
141
xaxis: { title: 'X Axis' },
142
yaxis: { title: 'Y Axis' }
143
};
144
145
const validation = Plotly.validate(data, layout);
146
147
if (!validation.isValid) {
148
console.log('Validation errors:');
149
validation.errors.forEach(error => {
150
console.log(`- ${error.message} at ${error.path.join('.')}`);
151
});
152
}
153
154
if (validation.warnings.length > 0) {
155
console.log('Validation warnings:');
156
validation.warnings.forEach(warning => {
157
console.log(`- ${warning.message} at ${warning.path.join('.')}`);
158
});
159
}
160
161
// Validate before creating plot
162
function safePlot(gd, data, layout) {
163
const validation = Plotly.validate(data, layout);
164
165
if (validation.isValid) {
166
return Plotly.newPlot(gd, data, layout);
167
} else {
168
console.error('Invalid plot data:', validation.errors);
169
throw new Error('Plot validation failed');
170
}
171
}
172
```
173
174
### Template System
175
176
Create and manage plot templates for consistent styling across multiple plots.
177
178
```javascript { .api }
179
/**
180
* Generate a template from existing plot
181
* @param gd - Graph div element to extract template from
182
* @returns Template object with layout and trace defaults
183
*/
184
function makeTemplate(gd: any): PlotTemplate;
185
186
/**
187
* Validate a plot template
188
* @param template - Template object to validate
189
* @returns Validation result for the template
190
*/
191
function validateTemplate(template: PlotTemplate): ValidationResult;
192
193
interface PlotTemplate {
194
layout?: Partial<Layout>;
195
data?: {
196
[traceType: string]: Partial<any>;
197
};
198
}
199
```
200
201
**Usage Examples:**
202
203
```javascript
204
// Create template from existing plot
205
const template = Plotly.makeTemplate(myDiv);
206
207
console.log('Generated template:', template);
208
209
// Use template for new plots
210
Plotly.newPlot(newDiv, newData, {
211
template: template,
212
title: 'Chart with Custom Template'
213
});
214
215
// Validate template
216
const validationResult = Plotly.validateTemplate(template);
217
if (validationResult.isValid) {
218
console.log('Template is valid');
219
} else {
220
console.log('Template validation errors:', validationResult.errors);
221
}
222
223
// Custom template creation
224
const customTemplate = {
225
layout: {
226
font: { family: 'Arial, sans-serif', size: 14, color: '#333' },
227
paper_bgcolor: '#f8f9fa',
228
plot_bgcolor: 'white',
229
colorway: ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728'],
230
xaxis: {
231
showgrid: true,
232
gridcolor: '#e6e6e6',
233
showline: true,
234
linecolor: '#333'
235
},
236
yaxis: {
237
showgrid: true,
238
gridcolor: '#e6e6e6',
239
showline: true,
240
linecolor: '#333'
241
}
242
},
243
data: {
244
scatter: {
245
marker: { size: 8 },
246
line: { width: 2 }
247
},
248
bar: {
249
marker: {
250
line: { width: 1, color: '#333' }
251
}
252
}
253
}
254
};
255
256
// Apply custom template
257
Plotly.newPlot(myDiv, data, {
258
template: customTemplate,
259
title: 'Chart with Custom Template'
260
});
261
```
262
263
### Plot Schema Access
264
265
Access the complete Plotly.js schema for dynamic plot generation and validation.
266
267
```javascript { .api }
268
/**
269
* Plot schema containing all trace types and attributes
270
*/
271
interface PlotSchemaAccess {
272
/**
273
* Get complete plot schema
274
* @returns Complete schema object with all traces and layout options
275
*/
276
get(): PlotSchema;
277
278
/**
279
* Traverse attribute tree with callback function
280
* @param attrs - Attribute object to traverse
281
* @param callback - Function called for each attribute
282
* @param level - Current traversal depth
283
* @param attrString - Full attribute path as string
284
*/
285
crawl(attrs: any, callback: Function, level?: number, attrString?: string): void;
286
287
/**
288
* Check if object is a validation object
289
* @param obj - Object to check
290
* @returns True if object is a validation object
291
*/
292
isValObject(obj: any): boolean;
293
294
/**
295
* Find array attributes in trace definition
296
* @param trace - Trace object to analyze
297
* @returns Array of attribute names that can contain arrays
298
*/
299
findArrayAttributes(trace: any): string[];
300
301
/**
302
* Get validation object for trace attribute
303
* @param trace - Trace object
304
* @param parts - Attribute path parts array
305
* @returns Validation object for the attribute
306
*/
307
getTraceValObject(trace: any, parts: string[]): any;
308
309
/**
310
* Get validation object for layout attribute
311
* @param fullLayout - Full layout object
312
* @param parts - Attribute path parts array
313
* @returns Validation object for the attribute
314
*/
315
getLayoutValObject(fullLayout: any, parts: string[]): any;
316
}
317
318
interface PlotSchema {
319
traces: {
320
[traceType: string]: TraceSchema;
321
};
322
layout: LayoutSchema;
323
frames: FrameSchema;
324
animation: AnimationSchema;
325
config: ConfigSchema;
326
}
327
328
interface TraceSchema {
329
attributes: {
330
[attributeName: string]: AttributeSchema;
331
};
332
meta: {
333
description: string;
334
categories: string[];
335
};
336
}
337
338
interface AttributeSchema {
339
valType: string;
340
description: string;
341
dflt?: any;
342
min?: number;
343
max?: number;
344
values?: any[];
345
arrayOk?: boolean;
346
role?: string;
347
}
348
```
349
350
**Usage Examples:**
351
352
```javascript
353
// Get complete schema
354
const schema = Plotly.PlotSchema.get();
355
356
console.log('Available trace types:', Object.keys(schema.traces));
357
358
// Explore scatter trace attributes
359
const scatterSchema = schema.traces.scatter;
360
console.log('Scatter trace attributes:', Object.keys(scatterSchema.attributes));
361
362
// Get attribute details
363
const markerColorAttr = scatterSchema.attributes['marker.color'];
364
console.log('Marker color attribute:', {
365
type: markerColorAttr.valType,
366
description: markerColorAttr.description,
367
default: markerColorAttr.dflt
368
});
369
370
// Dynamic plot generation using schema
371
function generateRandomPlot(traceType) {
372
const traceSchema = schema.traces[traceType];
373
if (!traceSchema) {
374
throw new Error(`Unknown trace type: ${traceType}`);
375
}
376
377
// Generate trace based on schema
378
const trace = { type: traceType };
379
380
// Add required attributes
381
if (traceSchema.attributes.x) {
382
trace.x = [1, 2, 3, 4, 5];
383
}
384
if (traceSchema.attributes.y) {
385
trace.y = [1, 4, 2, 8, 5];
386
}
387
388
return trace;
389
}
390
391
// Traverse schema attributes with callback
392
Plotly.PlotSchema.crawl(schema.traces.scatter.attributes, function(attr, attrName, attrs, level, fullAttrString) {
393
if (Plotly.PlotSchema.isValObject(attr)) {
394
console.log(`Found attribute: ${fullAttrString} (level ${level})`);
395
console.log(`Type: ${attr.valType}, Default: ${attr.dflt}`);
396
}
397
});
398
399
// Find array attributes in a trace
400
const arrayAttrs = Plotly.PlotSchema.findArrayAttributes({
401
type: 'scatter',
402
x: [1, 2, 3],
403
y: [1, 4, 9],
404
marker: { color: ['red', 'blue', 'green'] }
405
});
406
console.log('Array attributes found:', arrayAttrs);
407
408
// Get validation object for specific attribute
409
const markerColorValidation = Plotly.PlotSchema.getTraceValObject(
410
{ type: 'scatter' },
411
['marker', 'color']
412
);
413
console.log('Marker color validation:', markerColorValidation);
414
415
// Get layout validation object
416
const titleValidation = Plotly.PlotSchema.getLayoutValObject(
417
{ title: 'My Chart' },
418
['title']
419
);
420
console.log('Title validation:', titleValidation);
421
```
422
423
### Plot Serialization
424
425
Methods for serializing and deserializing complete plots.
426
427
```javascript { .api }
428
/**
429
* Serialize plot to JSON
430
* @param gd - Graph div element
431
* @param dataOnly - Include only data, not layout
432
* @param layout - Layout object to include
433
* @param data - Data array to include
434
* @param frames - Animation frames to include
435
* @returns JSON representation of the plot
436
*/
437
function graphJson(
438
gd: any,
439
dataOnly?: boolean,
440
layout?: any,
441
data?: any[],
442
frames?: any[]
443
): string;
444
```
445
446
**Usage Examples:**
447
448
```javascript
449
// Serialize complete plot
450
const plotJson = Plotly.Plots.graphJson(myDiv);
451
console.log('Serialized plot:', plotJson);
452
453
// Parse and recreate plot
454
const plotData = JSON.parse(plotJson);
455
Plotly.newPlot(newDiv, plotData.data, plotData.layout);
456
457
// Serialize only data
458
const dataJson = Plotly.Plots.graphJson(myDiv, true);
459
console.log('Data only:', dataJson);
460
461
// Save plot state for later restoration
462
function savePlotState(gd, stateName) {
463
const state = Plotly.Plots.graphJson(gd);
464
localStorage.setItem(`plot-state-${stateName}`, state);
465
}
466
467
function restorePlotState(gd, stateName) {
468
const state = localStorage.getItem(`plot-state-${stateName}`);
469
if (state) {
470
const plotData = JSON.parse(state);
471
return Plotly.react(gd, plotData.data, plotData.layout);
472
}
473
}
474
```
475
476
### Utility Functions
477
478
Various utility functions for plot manipulation and analysis.
479
480
```javascript { .api }
481
/**
482
* Resize plot to fit container
483
* @param gd - Graph div element
484
* @returns Promise resolving when resize is complete
485
*/
486
function resize(gd: any): Promise<void>;
487
488
/**
489
* Send plot data to Plotly cloud
490
* @param gd - Graph div element
491
* @param options - Cloud upload options
492
* @returns Promise resolving with cloud URL
493
*/
494
function sendDataToCloud(gd: any, options?: CloudOptions): Promise<string>;
495
496
interface CloudOptions {
497
filename?: string;
498
fileopt?: 'overwrite' | 'new';
499
world_readable?: boolean;
500
sharing?: 'public' | 'private' | 'secret';
501
}
502
```
503
504
**Usage Examples:**
505
506
```javascript
507
// Resize plot (useful after container size changes)
508
window.addEventListener('resize', function() {
509
Plotly.Plots.resize(myDiv);
510
});
511
512
// Manual resize
513
function resizePlot() {
514
return Plotly.Plots.resize(myDiv).then(function() {
515
console.log('Plot resized');
516
});
517
}
518
519
// Cloud upload (requires Plotly account)
520
Plotly.Plots.sendDataToCloud(myDiv, {
521
filename: 'my-chart',
522
fileopt: 'overwrite',
523
sharing: 'public'
524
}).then(function(url) {
525
console.log('Plot uploaded to:', url);
526
}).catch(function(error) {
527
console.error('Upload failed:', error);
528
});
529
```
530
531
### Snapshot System
532
533
Advanced export and cloning capabilities.
534
535
```javascript { .api }
536
/**
537
* Snapshot system for advanced export operations
538
*/
539
interface SnapshotSystem {
540
/**
541
* Clone plot for export without affecting original
542
* @param gd - Graph div element
543
* @param options - Clone options
544
* @returns Cloned plot element
545
*/
546
clone(gd: any, options?: CloneOptions): HTMLElement;
547
548
/**
549
* Convert plot to SVG
550
* @param gd - Graph div element
551
* @param format - Output format
552
* @param scale - Resolution scale
553
* @returns Promise resolving to SVG data
554
*/
555
toSVG(gd: any, format?: string, scale?: number): Promise<string>;
556
557
/**
558
* Convert SVG to raster image
559
* @param svg - SVG data
560
* @param format - Target format
561
* @param scale - Resolution scale
562
* @returns Promise resolving to image data
563
*/
564
svgToImg(svg: string, format: string, scale?: number): Promise<string>;
565
}
566
567
interface CloneOptions {
568
format?: string;
569
height?: number;
570
width?: number;
571
scale?: number;
572
}
573
```
574
575
**Usage Examples:**
576
577
```javascript
578
// Clone plot for export
579
const clonedPlot = Plotly.Snapshot.clone(myDiv, {
580
width: 1200,
581
height: 800,
582
scale: 2
583
});
584
585
// Convert to SVG
586
Plotly.Snapshot.toSVG(myDiv, 'svg', 2).then(function(svgData) {
587
console.log('SVG generated');
588
589
// Convert SVG to PNG
590
return Plotly.Snapshot.svgToImg(svgData, 'png', 2);
591
}).then(function(pngData) {
592
console.log('PNG generated from SVG');
593
});
594
595
// Advanced export workflow
596
async function advancedExport(gd, options) {
597
try {
598
// Clone plot with specific dimensions
599
const clone = Plotly.Snapshot.clone(gd, {
600
width: options.width,
601
height: options.height,
602
scale: options.scale
603
});
604
605
// Generate SVG
606
const svg = await Plotly.Snapshot.toSVG(clone, 'svg', options.scale);
607
608
// Convert to desired format
609
const imageData = await Plotly.Snapshot.svgToImg(
610
svg,
611
options.format,
612
options.scale
613
);
614
615
return imageData;
616
} catch (error) {
617
console.error('Export failed:', error);
618
throw error;
619
}
620
}
621
```
622
623
## Configuration for Export
624
625
### Global Export Settings
626
627
```javascript { .api }
628
/**
629
* Global configuration options affecting export behavior
630
*/
631
interface ExportConfig {
632
plotlyServerURL?: string;
633
showSendToCloud?: boolean;
634
showEditInChartStudio?: boolean;
635
toImageButtonOptions?: {
636
format?: 'png' | 'svg' | 'jpeg' | 'webp';
637
filename?: string;
638
height?: number;
639
width?: number;
640
scale?: number;
641
};
642
}
643
```
644
645
**Usage Examples:**
646
647
```javascript
648
// Configure default export options
649
Plotly.setPlotConfig({
650
toImageButtonOptions: {
651
format: 'png',
652
filename: 'custom-chart',
653
height: 800,
654
width: 1200,
655
scale: 2
656
}
657
});
658
659
// Custom export button in mode bar
660
const config = {
661
modeBarButtonsToAdd: [{
662
name: 'Export PNG',
663
icon: Plotly.Icons.camera,
664
click: function(gd) {
665
Plotly.downloadImage(gd, {
666
format: 'png',
667
filename: 'my-chart',
668
width: 1920,
669
height: 1080,
670
scale: 2
671
});
672
}
673
}]
674
};
675
676
Plotly.newPlot(myDiv, data, layout, config);
677
```