
Function Reference in JavaScript
Plotly.js function reference. How to create, update, and modify graphs drawn with Plotly's JavaScript Graphing Library.
Plotly Studio: Transform any dataset into an interactive data application in minutes with AI.Sign up for early access now.
Common parameters
graphDiv
- The functions documented here all create or modify a plot that is drawn into a
<div>
element on the page, commonly referred to asgraphDiv
orplotDiv
. The first argument to each function on this page is a reference to this element, and it can be either a DOM node, i.e. the output ofdocument.getElementById()
, or a string, in which case it will be treated as theid
of thediv
. A note on sizing: You can either supply height and width in thelayout
object (see below), or give the<div>
a height and width in CSS. data
- The data to be plotted is described in an array usually called
data
, whose elements are trace objects of various types (e.g.scatter
,bar
etc) as documentedin the Full Reference. layout
- The layout of the plot – non-data-related visual attributes such as the title, annotations etc – is described in an object usually called
layout
, as documentedin/ the Full Reference. config
- High-level configuration options for the plot, such as the scroll/zoom/hover behaviour, is described in an object usually called
config
, asdocumented here. The difference betweenconfig
andlayout
is thatlayout
relates to the content of the plot, whereasconfig
relates to the context in which the plot is being shown. frames
- Animation frames are described in an object usually called
frames
as per theexample here. They can containdata
andlayout
objects, which define any changes to be animated, and atraces
object that defines which traces to animate. Additionally, frames containingname
and/orgroup
attributes can be referenced byPlotly.animate after they are added byPlotly.addFrames
Plotly.newPlot
Draws a new plot in an<div>
element,overwriting any existing plot. To update an existing plot in a<div>
, it is much more efficient to usePlotly.react
than to overwrite it.After plotting, the
data
orlayout
can always be retrieved from the<div>
element in which the plot was drawn:var graphDiv = document.getElementById('id_of_the_div')var data = [{ x: [1999, 2000, 2001, 2002], y: [10, 15, 13, 17], type: 'scatter'}];var layout = { title: { text: 'Sales Growth' }, xaxis: { title: { text: 'Year' }, showgrid: false, zeroline: false }, yaxis: { title: { text: 'Percent' }, showline: false }};Plotly.newPlot(graphDiv, data, layout);...var dataRetrievedLater = graphDiv.data;var layoutRetrievedLater = graphDiv.layout;
Plotly.react
Plotly.react
has the same signature asPlotly.newPlot
above, and can be used in its place to create a plot, but when called again on the same<div>
will update it far more efficiently thanPlotly.newPlot
, which would destroy and recreate the plot.Plotly.react
is as fast asPlotly.restyle
/Plotly.relayout
documented below.Important Note: In order to use this method to plot new items in arrays under
data
such asx
ormarker.color
etc, these items must either have been added immutably (i.e. the identity of the parent array must have changed) or the value oflayout.datarevision
must have changed.Plotly.restyle
This function has comparable performance toPlotly.react
and is faster than redrawing the whole plot withPlotly.newPlot
.An efficient means of changing attributes in the
data
array in an existing plot. When restyling, you may choose to have the specified changes affect as many traces as desired. The update is given as a single object and the traces that are affected are given as a list of traces indices. Note, leaving the trace indices unspecified assumes that you want to restyleall the traces.// restyle a single trace using attribute stringsvar update = { opacity: 0.4, 'marker.color': 'red'};Plotly.restyle(graphDiv, update, 0);// restyle all traces using attribute stringsvar update = { opacity: 0.4, 'marker.color': 'red'};Plotly.restyle(graphDiv, update);// restyle two traces using attribute stringsvar update = { opacity: 0.4, 'marker.color': 'red'};Plotly.restyle(graphDiv, update, [1, 2]);
See the PenPlotly.restyle by plotly (@plotly) onCodePen.
The above examples have applied values across single or multiple traces. However, you can also specifyarrays of values to apply to tracesin turn.
// restyle the first trace's marker color 'red' and the second's 'green'var update = { 'marker.color': ['red', 'green']};Plotly.restyle(graphDiv, update, [0, 1])// alternate between red and green for all traces (note omission of traces)var update = { 'marker.color': ['red', 'green']};Plotly.restyle(graphDiv, update)
See the PenPlotly.restyle Traces in Turn by plotly (@plotly) onCodePen.
In restyle, arrays are assumed to be used in conjunction with the trace indices provided. Therefore, to apply an arrayas a value, you need to wrap it in an additional array. For example:
// update the color attribute of the first trace so that the markers within the same trace// have different colorsvar update = { 'marker.color': [['red', 'green']]}Plotly.restyle(graphDiv, update, [0])// update two traces with new z datavar update = {z: [[[1,2,3], [2,1,2], [1,1,1]], [[0,1,1], [0,2,1], [3,2,1]]]};Plotly.restyle(graphDiv, update, [1, 2])
See the PenPlotly.restyle Arrays by plotly (@plotly) onCodePen.
The termattribute strings is used above to meanflattened (e.g.,
{marker: {color: 'red'}}
vs.{'marker.color': red}
). When you pass an attribute string to restyle inside the update object, it’s assumed to meanupdate only this attribute. Therefore, if you wish to replace and entire sub-object, you may simply specifyone less level of nesting.// replace the entire marker object with the one providedvar update = { marker: {color: 'red'}};Plotly.restyle(graphDiv, update, [0])
See the PenPlotly.restyle Attribute strings by plotly (@plotly) onCodePen.
Finally, you may wish to selectively reset or ignore certain properties when restyling. This may be useful when specifying multiple properties for multiple traces so that you can carefully target what is and is not affected. In general `null` resets a property to the default while `undefined` applies no change to the current state.
// Set the first trace's line to red, the second to the default, and ignore the thirdPlotly.restyle(graphDiv, { 'line.color': ['red', null, undefined]}, [0, 1, 2])
See the Pennull vs. undefined in Plotly.restyle by plotly (@plotly) onCodePen.
Plotly.relayout
This function has comparable performance toPlotly.react
and is faster than redrawing the whole plot withPlotly.newPlot
.An efficient means of updating the
layout
object of an existing plot. The call signature and arguments for relayout are similar (but simpler) to restyle. Because there are no indices to deal with, arrays need not be wrapped. Also, no argument specifying applicable trace indices is passed in.// update only values within nested objectsvar update = { title: {text: 'some new title'}, // updates the title 'xaxis.range': [0, 5], // updates the xaxis range 'yaxis.range[1]': 15 // updates the end of the yaxis range};Plotly.relayout(graphDiv, update)
See the PenPlotly.relayout by plotly (@plotly) onCodePen.
Plotly.update
This function has comparable performance toPlotly.react
and is faster than redrawing the whole plot withPlotly.newPlot
.An efficient means of updating both the
data
array andlayout
object in an existing plot, basically a combination ofPlotly.restyle
andPlotly.relayout
.//update the layout and all the tracesvar layout_update = { title: {text: 'some new title'}, // updates the title};var data_update = { 'marker.color': 'red'};Plotly.update(graphDiv, data_update, layout_update)//update the layout and a single tracevar layout_update = { title: {text: 'some new title'}, // updates the title};var data_update = { 'marker.color': 'red'};Plotly.update(graphDiv, data_update, layout_update,0)//update the layout and two specific tracesvar layout_update = { title: {text: 'some new title'}, // updates the title};var data_update = { 'marker.color': 'red'};Plotly.update(graphDiv, data_update, layout_update, [0,2])
See the PenPlotly.update by plotly (@plotly) onCodePen.
Plotly.validate
Plotly.validate
allows users to validate their inputdata
array andlayout
object. This can be done on thedata
array andlayout
object passed intoPlotly.newPlot
or on an updatedgraphDiv
withPlotly.validate(graphDiv.data, graphDiv.layout)
.var data = [{ type: 'bar', y: [2, 1, 3, 2], orientation: 'horizontal'}];var out = Plotly.validate(data, layout);console.log(out[0].msg)// "In data trace 0, key orientation is set to an invalid value (horizontal)"
Plotly.makeTemplate
Plotly.makeTemplate
copies the style information from a figure. It does this by returning atemplate
object which can be passed to thelayout.template
attribute of another figure.var figure = { data: [{ type: 'bar', marker: {color: 'red'}, y: [2, 1, 3, 2], }], layout:{ title: { text: 'Quarterly Earnings' } }};var template = Plotly.makeTemplate(figure);var newData = [{ type:'bar', y:[3,2,5,8]}]var layout = {template:template}Plotly.newPlot(graphDiv,newData,layout)
Plotly.validateTemplate
Plotly.validateTemplate
allows users to Test for consistency between the given figure and a template,either already included in the figure or given separately. Note that not every issue identified here is necessarilya problem, it depends on what you're using the template for.var out = Plotly.validateTemplate(figure, template);console.log(out[0].msg)// "The template has 1 traces of type bar but there are none in the data."
Plotly.addTraces
This function has comparable performance toPlotly.react
and is faster than redrawing the whole plot withPlotly.newPlot
.This allows you to addnew traces to an existing
graphDiv
at any location in itsdata array. EverygraphDiv
object has adata
component which is an array of JSON blobs that each describe one trace. The full list of trace types can be foundin the Full Reference.// add a single trace to an existing graphDivPlotly.addTraces(graphDiv, {y: [2,1,2]});// add two tracesPlotly.addTraces(graphDiv, [{y: [2,1,2]}, {y: [4, 5, 7]}]);// add a trace at the beginning of the data arrayPlotly.addTraces(graphDiv, {y: [1, 5, 7]}, 0);
See the PenPlotly.addtraces by plotly (@plotly) onCodePen.
Plotly.deleteTraces
This function has comparable performance toPlotly.react
and is faster than redrawing the whole plot withPlotly.newPlot
.This allows you to remove traces from an existing
graphDiv
by specifying the indices of the traces to be removed.// remove the first tracePlotly.deleteTraces(graphDiv, 0);// remove the last two tracesPlotly.deleteTraces(graphDiv, [-2, -1]);
See the PenPlotly.deleteTraces by plotly (@plotly) onCodePen.
Plotly.moveTraces
This function has comparable performance toPlotly.react
and is faster than redrawing the whole plot withPlotly.newPlot
.This allows you to reorder traces in an existing
graphDiv
. This will change the ordering of the layering and the legend.All traces defined ingraphDiv
are ordered in an array. They are drawn one by one from first to last. Each time a new layer or trace is drawn to the canvas the new trace is drawn directly over the current canvas, replacing the colors of the traces and background. This algorithm to image stacking/drawing is known as thePainter's Algorithm. As its name implies the Painter's Algorithm is typically the manner in which a painter paints a landscape, starting from objects with the most perspective depth and progressively moving forward and layering over the background objects.// move the first trace (at index 0) the the end of the data arrayPlotly.moveTraces(graphDiv, 0);// move selected traces (at indices [0, 3, 5]) to the end of the data arrayPlotly.moveTraces(graphDiv, [0, 3, 5]);// move last trace (at index -1) to the beginning of the data array (index 0)Plotly.moveTraces(graphDiv, -1, 0);// move selected traces (at indices [1, 4, 5]) to new indices [0, 3, 2]Plotly.moveTraces(graphDiv, [1, 4, 5], [0, 3, 2]);
See the PenPlotly.moveTraces by plotly (@plotly) onCodePen.
Plotly.extendTraces
This function has comparable performance toPlotly.react
and is faster than redrawing the whole plot withPlotly.newPlot
.This allows you to add data to traces in an existing
graphDiv
.// extend one tracePlotly.extendTraces(graphDiv, {y: [[rand()]]}, [0])// extend multiple tracesPlotly.extendTraces(graphDiv, {y: [[rand()], [rand()]]}, [0, 1])// extend multiple traces up to a maximum of 10 points per tracePlotly.extendTraces(graphDiv, {y: [[rand()], [rand()]]}, [0, 1], 10)
See the PenPlotly.extendTraces by plotly (@plotly) onCodePen.
Plotly.prependTraces
This function has comparable performance toPlotly.react
and is faster than redrawing the whole plot withPlotly.newPlot
.This allows you to prepend data to an existing trace
graphDiv
.// prepend one tracePlotly.prependTraces(graphDiv, {y: [[rand()]]}, [0])// prepend multiple tracesPlotly.prependTraces(graphDiv, {y: [[rand()], [rand()]]}, [0, 1])// prepend multiple traces up to a maximum of 10 points per tracePlotly.prependTraces(graphDiv, {y: [[rand()], [rand()]]}, [0, 1], 10)
Plotly.addFrames
This function has comparable performance toPlotly.react
and is faster than redrawing the whole plot withPlotly.newPlot
.This allows you to add animation frames to a
graphDiv
. Thegroup
orname
attribute of a frame canbe used byPlotly.animate in place of a frame object (or array offrame objects).Seeexample here.Plotly.animate
Add dynamic behaviour to plotly graphs withPlotly.animate
.Plotly.newPlot('graph', [{ x: [1, 2, 3], y: [0, 0.5, 1], line: {simplify: false},}]);function randomize() { Plotly.animate('graph', { data: [{y: [Math.random(), Math.random(), Math.random()]}], traces: [0], layout: {} }, { transition: { duration: 500, easing: 'cubic-in-out' }, frame: { duration: 500 } })}
See the PenPlotly.animate by plotly (@plotly) onCodePen.
Plotly.purge
Usingpurge
will clear the div, and remove any Plotly plots that have been placed in it.// purge will be used on the div that you wish clear of Plotly plotsPlotly.purge(graphDiv);
See the PenPlotly.purge by plotly (@plotly) onCodePen.
Plotly.toImage
toImage
will generate a promise to an image of the plot in data URL format.// Plotly.toImage will turn the plot in the given div into a data URL string// toImage takes the div as the first argument and an object specifying image properties as the otherPlotly.toImage(graphDiv, {format: 'png', width: 800, height: 600}).then(function(dataUrl) { // use the dataUrl})
See the PenPlotly.toImage by plotly (@plotly) onCodePen.
Plotly.downloadImage
downloadImage
will trigger a request to download the image of a Plotly plot.// downloadImage will accept the div as the first argument and an object specifying image properties as the otherPlotly.downloadImage(graphDiv, {format: 'png', width: 800, height: 600, filename: 'newplot'});
See the PenPlotly.toImage by plotly (@plotly) onCodePen.
Using events
Plots emit events prefixed withplotly_
when clicked or hovered over, and event handlers can be bound to events using theon
method that is exposed by the plot div object. For more information and examples of how to use Plotly events see:https://plotly.com/javascript/plotlyjs-events/.