重感情的黄花菜 · 抗战史上的今天:1月5日· 3 周前 · |
面冷心慈的马克杯 · 有道云笔记|亿万用户的选择· 3 月前 · |
才高八斗的移动电源 · 已解决:PhotoShop导出发生未知错误! ...· 3 月前 · |
直爽的墨镜 · 盐选文库 - OpenI· 4 月前 · |
冷静的茶壶 · “洋记者”国潮之旅:“新中式”,新消费_新闻 ...· 4 月前 · |
plotly.express
: high-level interface for data visualization
plotly.graph_objects
: low-level interface to figures, traces and layout
plotly.subplots
: helper function for laying out multi-plot figures
plotly.figure_factory
: helper methods for building specific complex charts
plotly.io
: low-level interface for displaying, reading and writing figures
Plotly’s Python API allows users to programmatically access Plotly’s server resources.
This package is organized as follows:
Subpackages:
plotly: all functionality that requires access to Plotly’s servers
graph_objects: objects for designing figures and visualizing data
matplotlylib: tools to convert matplotlib figures
Modules:
tools: some helpful tools that do not require access to Plotly’s servers
utils: functions that you probably won’t need, but that subpackages use
version: holds the current API version
exceptions: defines our custom exception classes
plotly.animation.
EasingValidator
(
plotly_name
=
'easing'
,
parent_name
=
'batch_animate'
,
**
_
)
¶
Bases:
_plotly_utils.basevalidators.EnumeratedValidator
plotly.basedatatypes.
BaseFigure
(
data
=
None
,
layout_plotly
=
None
,
frames
=
None
,
skip_invalid
=
False
,
**
kwargs
)
¶
Bases:
object
Base class for all figure types (both widget and non-widget)
add_hline
(
y
,
row
=
'all'
,
col
=
'all'
,
exclude_empty_subplots
=
True
,
annotation
=
None
,
**
kwargs
)
¶
Add a horizontal line to a plot or subplot that extends infinitely in the x-dimension.
y ( float or int ) – A number representing the y coordinate of the horizontal line.
exclude_empty_subplots ( Boolean ) – If True (default) do not place the shape on subplots that have no data plotted on them.
row ( None , int or 'all' ) – Subplot row for shape indexed starting at 1. If ‘all’, addresses all rows in the specified column(s). If both row and col are None, addresses the first subplot if subplots exist, or the only plot. By default is “all”.
col ( None , int or 'all' ) – Subplot column for shape indexed starting at 1. If ‘all’, addresses all rows in the specified column(s). If both row and col are None, addresses the first subplot if subplots exist, or the only plot. By default is “all”.
annotation ( dict or plotly.graph_objects.layout.Annotation. If dict ( ) , ) – it is interpreted as describing an annotation. The annotation is placed relative to the shape based on annotation_position (see below) unless its x or y value has been specified for the annotation passed here. xref and yref are always the same as for the added shape and cannot be overridden.
annotation_position ( a string containing optionally [ "top" , "bottom" ] ) – and [“left”, “right”] specifying where the text should be anchored to on the line. Example positions are “bottom left”, “right top”, “right”, “bottom”. If an annotation is added but annotation_position is not specified, this defaults to “top right”.
annotation_* ( any parameters to go.layout.Annotation can be passed as ) – keywords by prefixing them with “ annotation_ ”. For example, to specify the annotation text “example” you can pass annotation_text=”example” as a keyword argument.
**kwargs – Any named function parameters that can be passed to ‘add_shape’, except for x0, x1, y0, y1 or type.
add_hrect
(
y0
,
y1
,
row
=
'all'
,
col
=
'all'
,
exclude_empty_subplots
=
True
,
annotation
=
None
,
**
kwargs
)
¶
Add a rectangle to a plot or subplot that extends infinitely in the x-dimension.
y0 ( float or int ) – A number representing the y coordinate of one side of the rectangle.
y1 ( float or int ) – A number representing the y coordinate of the other side of the rectangle.
exclude_empty_subplots ( Boolean ) – If True (default) do not place the shape on subplots that have no data plotted on them.
row ( None , int or 'all' ) – Subplot row for shape indexed starting at 1. If ‘all’, addresses all rows in the specified column(s). If both row and col are None, addresses the first subplot if subplots exist, or the only plot. By default is “all”.
col ( None , int or 'all' ) – Subplot column for shape indexed starting at 1. If ‘all’, addresses all rows in the specified column(s). If both row and col are None, addresses the first subplot if subplots exist, or the only plot. By default is “all”.
annotation ( dict or plotly.graph_objects.layout.Annotation. If dict ( ) , ) – it is interpreted as describing an annotation. The annotation is placed relative to the shape based on annotation_position (see below) unless its x or y value has been specified for the annotation passed here. xref and yref are always the same as for the added shape and cannot be overridden.
annotation_position ( a string containing optionally [ "inside" , "outside" ] , [ "top" , "bottom" ] ) – and [“left”, “right”] specifying where the text should be anchored to on the rectangle. Example positions are “outside top left”, “inside bottom”, “right”, “inside left”, “inside” (“outside” is not supported). If an annotation is added but annotation_position is not specified this defaults to “inside top right”.
annotation_* ( any parameters to go.layout.Annotation can be passed as ) – keywords by prefixing them with “ annotation_ ”. For example, to specify the annotation text “example” you can pass annotation_text=”example” as a keyword argument.
**kwargs – Any named function parameters that can be passed to ‘add_shape’, except for x0, x1, y0, y1 or type.
add_trace
(
trace
,
row
=
None
,
col
=
None
,
secondary_y
=
None
,
exclude_empty_subplots
=
False
)
¶
Add a trace to the figure
trace ( BaseTraceType or dict ) –
An instances of a trace classe from the plotly.graph_objects package (e.g plotly.graph_objects.Scatter, plotly.graph_objects.Bar)
or a dicts where:
The ‘type’ property specifies the trace type (e.g. ‘scatter’, ‘bar’, ‘area’, etc.). If the dict has no ‘type’ property then ‘scatter’ is assumed.
All remaining properties are passed to the constructor of the specified trace type.
row
(
'all'
,
int
or
None
(
default
)
) – Subplot row index (starting from 1) for the trace to be
added. Only valid if figure was created using
plotly.tools.make_subplots
.
If ‘all’, addresses all rows in the specified column(s).
col
(
'all'
,
int
or
None
(
default
)
) – Subplot col index (starting from 1) for the trace to be
added. Only valid if figure was created using
plotly.tools.make_subplots
.
If ‘all’, addresses all columns in the specified row(s).
secondary_y ( boolean or None ( default None ) ) –
If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied:
The figure was created using
plotly.subplots.make_subplots
.
The row and col arguments are not None
The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info.
The trace argument is a 2D cartesian trace (scatter, bar, etc.)
exclude_empty_subplots ( boolean ) – If True, the trace will not be added to subplots that don’t already have traces.
The Figure that add_trace was called on
Examples
>>> from plotly import subplots
>>> import plotly.graph_objects as go
Add two Scatter traces to a figure
>>> fig = go.Figure()
>>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]))
Figure(...)
>>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]))
Figure(...)
Add two Scatter traces to vertically stacked subplots
>>> fig = subplots.make_subplots(rows=2)
>>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=1, col=1)
Figure(...)
>>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=2, col=1)
Figure(...)
add_traces
(data, rows=None, cols=None, secondary_ys=None, exclude_empty_subplots=False)¶
Add traces to the figure
- Parameters
data (list[BaseTraceType or dict]) –
A list of trace specifications to be added.
Trace specifications may be either:
Instances of trace classes from the plotly.graph_objects
package (e.g plotly.graph_objects.Scatter, plotly.graph_objects.Bar)
Dicts where:
The ‘type’ property specifies the trace type (e.g.
‘scatter’, ‘bar’, ‘area’, etc.). If the dict has no ‘type’
property then ‘scatter’ is assumed.
All remaining properties are passed to the constructor
of the specified trace type.
rows (None, list[int], or int (default None)) – List of subplot row indexes (starting from 1) for the traces to be
added. Only valid if figure was created using
plotly.tools.make_subplots
If a single integer is passed, all traces will be added to row number
cols (None or list[int] (default None)) – List of subplot column indexes (starting from 1) for the traces
to be added. Only valid if figure was created using
plotly.tools.make_subplots
If a single integer is passed, all traces will be added to column number
- secondary_ys: None or list[boolean] (default None)
List of secondary_y booleans for traces to be added. See the
docstring for add_trace
for more info.
- exclude_empty_subplots: boolean
If True, the trace will not be added to subplots that don’t already
have traces.
- Returns
The Figure that add_traces was called on
- Return type
-
Examples
>>> from plotly import subplots
>>> import plotly.graph_objects as go
Add two Scatter traces to a figure
>>> fig = go.Figure()
>>> fig.add_traces([go.Scatter(x=[1,2,3], y=[2,1,2]),
... go.Scatter(x=[1,2,3], y=[2,1,2])])
Figure(...)
Add two Scatter traces to vertically stacked subplots
>>> fig = subplots.make_subplots(rows=2)
>>> fig.add_traces([go.Scatter(x=[1,2,3], y=[2,1,2]),
... go.Scatter(x=[1,2,3], y=[2,1,2])],
... rows=[1, 2], cols=[1, 1])
Figure(...)
add_vline
(x, row='all', col='all', exclude_empty_subplots=True, annotation=None, **kwargs)¶
Add a vertical line to a plot or subplot that extends infinitely in the
y-dimension.
- Parameters
x (float or int) – A number representing the x coordinate of the vertical line.
exclude_empty_subplots (Boolean) – If True (default) do not place the shape on subplots that have no data
plotted on them.
row (None, int or 'all') – Subplot row for shape indexed starting at 1. If ‘all’, addresses all rows in
the specified column(s). If both row and col are None, addresses the
first subplot if subplots exist, or the only plot. By default is “all”.
col (None, int or 'all') – Subplot column for shape indexed starting at 1. If ‘all’, addresses all rows in
the specified column(s). If both row and col are None, addresses the
first subplot if subplots exist, or the only plot. By default is “all”.
annotation (dict or plotly.graph_objects.layout.Annotation. If dict(),) – it is interpreted as describing an annotation. The annotation is
placed relative to the shape based on annotation_position (see
below) unless its x or y value has been specified for the annotation
passed here. xref and yref are always the same as for the added
shape and cannot be overridden.
annotation_position (a string containing optionally ["top", "bottom"]) – and [“left”, “right”] specifying where the text should be anchored
to on the line. Example positions are “bottom left”, “right top”,
“right”, “bottom”. If an annotation is added but annotation_position is
not specified, this defaults to “top right”.
annotation_* (any parameters to go.layout.Annotation can be passed as) – keywords by prefixing them with “annotation_”. For example, to specify the
annotation text “example” you can pass annotation_text=”example” as a
keyword argument.
**kwargs – Any named function parameters that can be passed to ‘add_shape’,
except for x0, x1, y0, y1 or type.
add_vrect
(x0, x1, row='all', col='all', exclude_empty_subplots=True, annotation=None, **kwargs)¶
Add a rectangle to a plot or subplot that extends infinitely in the
y-dimension.
- Parameters
x0 (float or int) – A number representing the x coordinate of one side of the rectangle.
x1 (float or int) – A number representing the x coordinate of the other side of the rectangle.
exclude_empty_subplots (Boolean) – If True (default) do not place the shape on subplots that have no data
plotted on them.
row (None, int or 'all') – Subplot row for shape indexed starting at 1. If ‘all’, addresses all rows in
the specified column(s). If both row and col are None, addresses the
first subplot if subplots exist, or the only plot. By default is “all”.
col (None, int or 'all') – Subplot column for shape indexed starting at 1. If ‘all’, addresses all rows in
the specified column(s). If both row and col are None, addresses the
first subplot if subplots exist, or the only plot. By default is “all”.
annotation (dict or plotly.graph_objects.layout.Annotation. If dict(),) – it is interpreted as describing an annotation. The annotation is
placed relative to the shape based on annotation_position (see
below) unless its x or y value has been specified for the annotation
passed here. xref and yref are always the same as for the added
shape and cannot be overridden.
annotation_position (a string containing optionally ["inside", "outside"], ["top", "bottom"]) – and [“left”, “right”] specifying where the text should be anchored
to on the rectangle. Example positions are “outside top left”, “inside
bottom”, “right”, “inside left”, “inside” (“outside” is not supported). If
an annotation is added but annotation_position is not specified this
defaults to “inside top right”.
annotation_* (any parameters to go.layout.Annotation can be passed as) – keywords by prefixing them with “annotation_”. For example, to specify the
annotation text “example” you can pass annotation_text=”example” as a
keyword argument.
**kwargs – Any named function parameters that can be passed to ‘add_shape’,
except for x0, x1, y0, y1 or type.
append_trace
(trace, row, col)¶
Add a trace to the figure bound to axes at the specified row,
col index.
A row, col index grid is generated for figures created with
plotly.tools.make_subplots, and can be viewed with the print_grid
method
- Parameters
trace – The data trace to be bound
row (int) – Subplot row index (see Figure.print_grid)
col (int) – Subplot column index (see Figure.print_grid)
Examples
>>> from plotly import tools
>>> import plotly.graph_objects as go
>>> # stack two subplots vertically
>>> fig = tools.make_subplots(rows=2)
This is the format of your plot grid:
[ (1,1) x1,y1 ]
[ (2,1) x2,y2 ]
>>> fig.append_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=1, col=1)
>>> fig.append_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=2, col=1)
batch_animate
(duration=500, easing='cubic-in-out')¶
Context manager to animate trace / layout updates
- Parameters
duration (number) – The duration of the transition, in milliseconds.
If equal to zero, updates are synchronous.
easing (string) –
The easing function used for the transition.
One of:
linear
cubic
circle
elastic
bounce
linear-in
quad-in
cubic-in
sin-in
exp-in
circle-in
elastic-in
back-in
bounce-in
linear-out
quad-out
cubic-out
sin-out
exp-out
circle-out
elastic-out
back-out
bounce-out
linear-in-out
quad-in-out
cubic-in-out
sin-in-out
exp-in-out
circle-in-out
elastic-in-out
back-in-out
bounce-in-out
Examples
Suppose we have a figure widget, fig
, with a single trace.
>>> import plotly.graph_objects as go
>>> fig = go.FigureWidget(data=[{'y': [3, 4, 2]}])
1) Animate a change in the xaxis and yaxis ranges using default
duration and easing parameters.
>>> with fig.batch_animate():
... fig.layout.xaxis.range = [0, 5]
... fig.layout.yaxis.range = [0, 10]
2) Animate a change in the size and color of the trace’s markers
over 2 seconds using the elastic-in-out easing method
>>> with fig.batch_animate(duration=2000, easing='elastic-in-out'):
... fig.data[0].marker.color = 'green'
... fig.data[0].marker.size = 20
batch_update
()¶
A context manager that batches up trace and layout assignment
operations into a singe plotly_update message that is executed when
the context exits.
Examples
For example, suppose we have a figure widget, fig
, with a single
trace.
>>> import plotly.graph_objects as go
>>> fig = go.FigureWidget(data=[{'y': [3, 4, 2]}])
If we want to update the xaxis range, the yaxis range, and the
marker color, we could do so using a series of three property
assignments as follows:
>>> fig.layout.xaxis.range = [0, 5]
>>> fig.layout.yaxis.range = [0, 10]
>>> fig.data[0].marker.color = 'green'
This will work, however it will result in three messages being
sent to the front end (two relayout messages for the axis range
updates followed by one restyle message for the marker color
update). This can cause the plot to appear to stutter as the
three updates are applied incrementally.
We can avoid this problem by performing these three assignments in a
batch_update
context as follows:
>>> with fig.batch_update():
... fig.layout.xaxis.range = [0, 5]
... fig.layout.yaxis.range = [0, 10]
... fig.data[0].marker.color = 'green'
Now, these three property updates will be sent to the frontend in a
single update message, and they will be applied by the front end
simultaneously.
for_each_trace
(fn, selector=None, row=None, col=None, secondary_y=None)¶
Apply a function to all traces that satisfy the specified selection
criteria
- Parameters
fn – Function that inputs a single trace object.
selector (dict, function, int, str or None (default None)) – Dict to use as selection criteria.
Traces will be selected if they contain properties corresponding
to all of the dictionary’s keys, with values that exactly match
the supplied values. If None (the default), all traces are
selected. If a function, it must be a function accepting a single
argument and returning a boolean. The function will be called on
each trace and those for which the function returned True
will be in the selection. If an int N, the Nth trace matching row
and col will be selected (N can be negative). If a string S, the selector
is equivalent to dict(type=S).
row (int or None (default None)) – Subplot row and column index of traces to select.
To select traces by row and column, the Figure must have been
created using plotly.subplots.make_subplots. If None
(the default), all traces are selected.
col (int or None (default None)) – Subplot row and column index of traces to select.
To select traces by row and column, the Figure must have been
created using plotly.subplots.make_subplots. If None
(the default), all traces are selected.
secondary_y (boolean or None (default None)) –
If True, only select traces associated with the secondary
y-axis of the subplot.
If False, only select traces associated with the primary
y-axis of the subplot.
If None (the default), do not filter traces based on secondary
y-axis.
To select traces by secondary y-axis, the Figure must have been
created using plotly.subplots.make_subplots. See the docstring
for the specs argument to make_subplots for more info on
creating subplots with secondary y-axes.
- Returns
Returns the Figure object that the method was called on
- Return type
full_figure_for_development
(warn=True, as_dict=False)¶
Compute default values for all attributes not specified in the input figure and
returns the output as a “full” figure. This function calls Plotly.js via Kaleido
to populate unspecified attributes. This function is intended for interactive use
during development to learn more about how Plotly.js computes default values and is
not generally necessary or recommended for production use.
- Parameters
fig – Figure object or dict representing a figure
warn (bool) – If False, suppress warnings about not using this in production.
as_dict (bool) – If True, output is a dict with some keys that go.Figure can’t parse.
If False, output is a go.Figure with unparseable keys skipped.
- Returns
The full figure
- Return type
plotly.graph_objects.Figure or dict
get_subplot
(row, col, secondary_y=False)¶
Return an object representing the subplot at the specified row
and column. May only be used on Figures created using
plotly.tools.make_subplots
- Parameters
row (int) – 1-based index of subplot row
col (int) – 1-based index of subplot column
secondary_y (bool) – If True, select the subplot that consists of the x-axis and the
secondary y-axis at the specified row/col. Only valid if the
subplot at row/col is an 2D cartesian subplot that was created
with a secondary y-axis. See the docstring for the specs argument
to make_subplots for more info on creating a subplot with a
secondary y-axis.
- Returns
None: if subplot is empty
plotly.graph_objects.layout.Scene: if subplot type is ‘scene’
plotly.graph_objects.layout.Polar: if subplot type is ‘polar’
plotly.graph_objects.layout.Ternary: if subplot type is ‘ternary’
plotly.graph_objects.layout.Mapbox: if subplot type is ‘ternary’
SubplotDomain namedtuple with x
and y
fields:
if subplot type is ‘domain’.
x: length 2 list of the subplot start and stop width
y: length 2 list of the subplot start and stop height
SubplotXY namedtuple with xaxis
and yaxis
fields:
if subplot type is ‘xy’.
xaxis: plotly.graph_objects.layout.XAxis instance for subplot
yaxis: plotly.graph_objects.layout.YAxis instance for subplot
plotly_relayout
(relayout_data, **kwargs)¶
Perform a Plotly relayout operation on the figure’s layout
- Parameters
relayout_data (dict) –
Dict of layout updates
dict keys are strings that specify the properties to be updated.
Nested properties are expressed by joining successive keys on
‘.’ characters (e.g. ‘xaxis.range’)
dict values are the values to use to update the layout.
- Returns
- Return type
plotly_restyle
(restyle_data, trace_indexes=None, **kwargs)¶
Perform a Plotly restyle operation on the figure’s traces
- Parameters
restyle_data (dict) –
Dict of trace style updates.
Keys are strings that specify the properties to be updated.
Nested properties are expressed by joining successive keys on
‘.’ characters (e.g. ‘marker.color’).
Values may be scalars or lists. When values are scalars,
that scalar value is applied to all traces specified by the
trace_indexes
parameter. When values are lists,
the restyle operation will cycle through the elements
of the list as it cycles through the traces specified by the
trace_indexes
parameter.
Caution: To use plotly_restyle to update a list property (e.g.
the x
property of the scatter trace), the property value
should be a scalar list containing the list to update with. For
example, the following command would be used to update the ‘x’
property of the first trace to the list [1, 2, 3]
>>> import plotly.graph_objects as go
>>> fig = go.Figure(go.Scatter(x=[2, 4, 6]))
>>> fig.plotly_restyle({'x': [[1, 2, 3]]}, 0)
trace_indexes (int or list of int) – Trace index, or list of trace indexes, that the restyle operation
applies to. Defaults to all trace indexes.
- Returns
- Return type
plotly_update
(restyle_data=None, relayout_data=None, trace_indexes=None, **kwargs)¶
Perform a Plotly update operation on the figure.
Note: This operation both mutates and returns the figure
- Parameters
restyle_data (dict) – Traces update specification. See the docstring for the
plotly_restyle
method for details
relayout_data (dict) – Layout update specification. See the docstring for the
plotly_relayout
method for details
trace_indexes – Trace index, or list of trace indexes, that the update operation
applies to. Defaults to all trace indexes.
- Returns
- Return type
-
key (str) – Property name
dflt – The default value to return if key was not found in figure
- Returns
The removed value that was previously associated with key
- Return type
value
- Raises
KeyError – If key is not in object and no dflt argument specified
print_grid
()¶
Print a visual layout of the figure’s axes arrangement.
This is only valid for figures that are created
with plotly.tools.make_subplots.
select_traces
(selector=None, row=None, col=None, secondary_y=None)¶
Select traces from a particular subplot cell and/or traces
that satisfy custom selection criteria.
- Parameters
selector (dict, function, int, str or None (default None)) – Dict to use as selection criteria.
Traces will be selected if they contain properties corresponding
to all of the dictionary’s keys, with values that exactly match
the supplied values. If None (the default), all traces are
selected. If a function, it must be a function accepting a single
argument and returning a boolean. The function will be called on
each trace and those for which the function returned True
will be in the selection. If an int N, the Nth trace matching row
and col will be selected (N can be negative). If a string S, the selector
is equivalent to dict(type=S).
row (int or None (default None)) – Subplot row and column index of traces to select.
To select traces by row and column, the Figure must have been
created using plotly.subplots.make_subplots. If None
(the default), all traces are selected.
col (int or None (default None)) – Subplot row and column index of traces to select.
To select traces by row and column, the Figure must have been
created using plotly.subplots.make_subplots. If None
(the default), all traces are selected.
secondary_y (boolean or None (default None)) –
If True, only select traces associated with the secondary
y-axis of the subplot.
If False, only select traces associated with the primary
y-axis of the subplot.
If None (the default), do not filter traces based on secondary
y-axis.
To select traces by secondary y-axis, the Figure must have been
created using plotly.subplots.make_subplots. See the docstring
for the specs argument to make_subplots for more info on
creating subplots with secondary y-axes.
- Returns
Generator that iterates through all of the traces that satisfy
all of the specified selection criteria
- Return type
generator
set_subplots
(rows=None, cols=None, **make_subplots_args)¶
Add subplots to this figure. If the figure already contains subplots,
then this throws an error. Accepts any keyword arguments that
plotly.subplots.make_subplots accepts.
show
(*args, **kwargs)¶
Show a figure using either the default renderer(s) or the renderer(s)
specified by the renderer argument
- Parameters
renderer (str or None (default None)) – A string containing the names of one or more registered renderers
(separated by ‘+’ characters) or None. If None, then the default
renderers specified in plotly.io.renderers.default are used.
validate (bool (default True)) – True if the figure should be validated before being shown,
False otherwise.
width (int or float) – An integer or float that determines the number of pixels wide the
plot is. The default is set in plotly.js.
height (int or float) – An integer or float that determines the number of pixels wide the
plot is. The default is set in plotly.js.
config (dict) – A dict of parameters to configure the figure. The defaults are set
in plotly.js.
- Returns
- Return type
to_dict
()¶
Convert figure to a dictionary
Note: the dictionary includes the properties explicitly set by the
user, it does not include default values of unspecified properties
- Returns
- Return type
config (dict or None (default None)) – Plotly.js figure config options
auto_play (bool (default=True)) – Whether to automatically start the animation sequence on page load
if the figure contains frames. Has no effect if the figure does not
contain frames.
include_plotlyjs (bool or string (default True)) –
Specifies how the plotly.js library is included/loaded in the output
div string.
If True, a script tag containing the plotly.js source code (~3MB)
is included in the output. HTML files generated with this option are
fully self-contained and can be used offline.
If ‘cdn’, a script tag that references the plotly.js CDN is included
in the output. HTML files generated with this option are about 3MB
smaller than those generated with include_plotlyjs=True, but they
require an active internet connection in order to load the plotly.js
library.
If ‘directory’, a script tag is included that references an external
plotly.min.js bundle that is assumed to reside in the same
directory as the HTML file.
If ‘require’, Plotly.js is loaded using require.js. This option
assumes that require.js is globally available and that it has been
globally configured to know how to find Plotly.js as ‘plotly’.
This option is not advised when full_html=True as it will result
in a non-functional html file.
If a string that ends in ‘.js’, a script tag is included that
references the specified path. This approach can be used to point
the resulting HTML file to an alternative CDN or local bundle.
If False, no script tag referencing plotly.js is included. This is
useful when the resulting div string will be placed inside an HTML
document that already loads plotly.js. This option is not advised
when full_html=True as it will result in a non-functional html file.
include_mathjax (bool or string (default False)) –
Specifies how the MathJax.js library is included in the output html
div string. MathJax is required in order to display labels
with LaTeX typesetting.
If False, no script tag referencing MathJax.js will be included in the
output.
If ‘cdn’, a script tag that references a MathJax CDN location will be
included in the output. HTML div strings generated with this option
will be able to display LaTeX typesetting as long as internet access
is available.
If a string that ends in ‘.js’, a script tag is included that
references the specified path. This approach can be used to point the
resulting HTML div string to an alternative CDN.
post_script (str or list or None (default None)) – JavaScript snippet(s) to be included in the resulting div just after
plot creation. The string(s) may include ‘{plot_id}’ placeholders
that will then be replaced by the id
of the div element that the
plotly.js figure is associated with. One application for this script
is to install custom plotly.js event handlers.
full_html (bool (default True)) – If True, produce a string containing a complete HTML document
starting with an <html> tag. If False, produce a string containing
a single <div> element.
animation_opts (dict or None (default None)) – dict of custom animation parameters to be passed to the function
Plotly.animate in Plotly.js. See
https://github.com/plotly/plotly.js/blob/master/src/plots/animation_attributes.js
for available options. Has no effect if the figure does not contain
frames, or auto_play is False.
default_width (number or str (default '100%')) – The default figure width/height to use if the provided figure does not
specify its own layout.width/layout.height property. May be
specified in pixels as an integer (e.g. 500), or as a css width style
string (e.g. ‘500px’, ‘100%’).
default_height (number or str (default '100%')) – The default figure width/height to use if the provided figure does not
specify its own layout.width/layout.height property. May be
specified in pixels as an integer (e.g. 500), or as a css width style
string (e.g. ‘500px’, ‘100%’).
validate (bool (default True)) – True if the figure should be validated before being converted to
JSON, False otherwise.
div_id (str (default None)) – If provided, this is the value of the id attribute of the div tag. If None, the
id attribute is a UUID.
- Returns
Representation of figure as an HTML div string
- Return type
If not specified, will default to plotly.io.config.default_format
The width of the exported image in layout pixels. If the scale
property is 1.0, this will also be the width of the exported image
in physical pixels.
If not specified, will default to plotly.io.config.default_width
The height of the exported image in layout pixels. If the scale
property is 1.0, this will also be the height of the exported image
in physical pixels.
If not specified, will default to plotly.io.config.default_height
scale (int or float or None) –
The scale factor to use when exporting the figure. A scale factor
larger than 1.0 will increase the image resolution with respect
to the figure’s layout pixel dimensions. Whereas as scale factor of
less than 1.0 will decrease the image resolution.
If not specified, will default to plotly.io.config.default_scale
validate (bool) – True if the figure should be validated before being converted to
an image, False otherwise.
engine (str) –
- Image export engine to use:
”kaleido”: Use Kaleido for image export
”orca”: Use Orca for image export
”auto” (default): Use Kaleido if installed, otherwise use orca
- Parameters
validate (bool (default True)) – True if the figure should be validated before being converted to
JSON, False otherwise.
pretty (bool (default False)) – True if JSON representation should be pretty-printed, False if
representation should be as compact as possible.
remove_uids (bool (default True)) – True if trace UIDs should be omitted from the JSON representation
engine (str (default None)) –
- The JSON encoding engine to use. One of:
”json” for an encoder based on the built-in Python json module
”orjson” for a fast encoder the requires the orjson package
If not specified, the default encoder is set to the current value of
plotly.io.json.config.default_encoder.
- Returns
Representation of figure as a JSON string
- Return type
to_plotly_json
()¶
Convert figure to a JSON representation as a Python dict
Note: May include some JSON-invalid data types, use the PlotlyJSONEncoder
util
or the to_json
method to encode to a string.
- Returns
- Return type
update
(dict1=None, overwrite=False, **kwargs)¶
Update the properties of the figure with a dict and/or with
keyword arguments.
This recursively updates the structure of the figure
object with the values in the input dict / keyword arguments.
- Parameters
dict1 (dict) – Dictionary of properties to be updated
overwrite (bool) – If True, overwrite existing properties. If False, apply updates
to existing properties recursively, preserving existing
properties that are not specified in the update operation.
kwargs – Keyword/value pair of properties to be updated
Examples
>>> import plotly.graph_objects as go
>>> fig = go.Figure(data=[{'y': [1, 2, 3]}])
>>> fig.update(data=[{'y': [4, 5, 6]}])
Figure(...)
>>> fig.to_plotly_json()
{'data': [{'type': 'scatter',
'uid': 'e86a7c7a-346a-11e8-8aa8-a0999b0c017b',
'y': array([4, 5, 6], dtype=int32)}],
'layout': {}}
>>> fig = go.Figure(layout={'xaxis':
... {'color': 'green',
... 'range': [0, 1]}})
>>> fig.update({'layout': {'xaxis': {'color': 'pink'}}})
Figure(...)
>>> fig.to_plotly_json()
{'data': [],
'layout': {'xaxis':
{'color': 'pink',
'range': [0, 1]}}}
- Returns
Updated figure
- Return type
-
update_layout
(dict1=None, overwrite=False, **kwargs)¶
Update the properties of the figure’s layout with a dict and/or with
keyword arguments.
This recursively updates the structure of the original
layout with the values in the input dict / keyword arguments.
- Parameters
dict1 (dict) – Dictionary of properties to be updated
overwrite (bool) – If True, overwrite existing properties. If False, apply updates
to existing properties recursively, preserving existing
properties that are not specified in the update operation.
kwargs – Keyword/value pair of properties to be updated
- Returns
The Figure object that the update_layout method was called on
- Return type
-
update_traces
(patch=None, selector=None, row=None, col=None, secondary_y=None, overwrite=False, **kwargs)¶
Perform a property update operation on all traces that satisfy the
specified selection criteria
- Parameters
patch (dict or None (default None)) – Dictionary of property updates to be applied to all traces that
satisfy the selection criteria.
selector (dict, function, int, str or None (default None)) – Dict to use as selection criteria.
Traces will be selected if they contain properties corresponding
to all of the dictionary’s keys, with values that exactly match
the supplied values. If None (the default), all traces are
selected. If a function, it must be a function accepting a single
argument and returning a boolean. The function will be called on
each trace and those for which the function returned True
will be in the selection. If an int N, the Nth trace matching row
and col will be selected (N can be negative). If a string S, the selector
is equivalent to dict(type=S).
row (int or None (default None)) – Subplot row and column index of traces to select.
To select traces by row and column, the Figure must have been
created using plotly.subplots.make_subplots. If None
(the default), all traces are selected.
col (int or None (default None)) – Subplot row and column index of traces to select.
To select traces by row and column, the Figure must have been
created using plotly.subplots.make_subplots. If None
(the default), all traces are selected.
secondary_y (boolean or None (default None)) –
If True, only select traces associated with the secondary
y-axis of the subplot.
If False, only select traces associated with the primary
y-axis of the subplot.
If None (the default), do not filter traces based on secondary
y-axis.
To select traces by secondary y-axis, the Figure must have been
created using plotly.subplots.make_subplots. See the docstring
for the specs argument to make_subplots for more info on
creating subplots with secondary y-axes.
overwrite (bool) – If True, overwrite existing properties. If False, apply updates
to existing properties recursively, preserving existing
properties that are not specified in the update operation.
**kwargs – Additional property updates to apply to each selected trace. If
a property is specified in both patch and in **kwargs then the
one in **kwargs takes precedence.
- Returns
Returns the Figure object that the method was called on
- Return type
- Parameters
file (str or writeable) – A string representing a local file path or a writeable object
(e.g. a pathlib.Path object or an open file descriptor)
config (dict or None (default None)) – Plotly.js figure config options
auto_play (bool (default=True)) – Whether to automatically start the animation sequence on page load
if the figure contains frames. Has no effect if the figure does not
contain frames.
include_plotlyjs (bool or string (default True)) –
Specifies how the plotly.js library is included/loaded in the output
div string.
If True, a script tag containing the plotly.js source code (~3MB)
is included in the output. HTML files generated with this option are
fully self-contained and can be used offline.
If ‘cdn’, a script tag that references the plotly.js CDN is included
in the output. HTML files generated with this option are about 3MB
smaller than those generated with include_plotlyjs=True, but they
require an active internet connection in order to load the plotly.js
library.
If ‘directory’, a script tag is included that references an external
plotly.min.js bundle that is assumed to reside in the same
directory as the HTML file. If file
is a string to a local file path
and full_html
is True then
If ‘directory’, a script tag is included that references an external
plotly.min.js bundle that is assumed to reside in the same
directory as the HTML file. If file
is a string to a local file
path and full_html
is True, then the plotly.min.js bundle is copied
into the directory of the resulting HTML file. If a file named
plotly.min.js already exists in the output directory then this file
is left unmodified and no copy is performed. HTML files generated
with this option can be used offline, but they require a copy of
the plotly.min.js bundle in the same directory. This option is
useful when many figures will be saved as HTML files in the same
directory because the plotly.js source code will be included only
once per output directory, rather than once per output file.
If ‘require’, Plotly.js is loaded using require.js. This option
assumes that require.js is globally available and that it has been
globally configured to know how to find Plotly.js as ‘plotly’.
This option is not advised when full_html=True as it will result
in a non-functional html file.
If a string that ends in ‘.js’, a script tag is included that
references the specified path. This approach can be used to point
the resulting HTML file to an alternative CDN or local bundle.
If False, no script tag referencing plotly.js is included. This is
useful when the resulting div string will be placed inside an HTML
document that already loads plotly.js. This option is not advised
when full_html=True as it will result in a non-functional html file.
include_mathjax (bool or string (default False)) –
Specifies how the MathJax.js library is included in the output html
div string. MathJax is required in order to display labels
with LaTeX typesetting.
If False, no script tag referencing MathJax.js will be included in the
output.
If ‘cdn’, a script tag that references a MathJax CDN location will be
included in the output. HTML div strings generated with this option
will be able to display LaTeX typesetting as long as internet access
is available.
If a string that ends in ‘.js’, a script tag is included that
references the specified path. This approach can be used to point the
resulting HTML div string to an alternative CDN.
post_script (str or list or None (default None)) – JavaScript snippet(s) to be included in the resulting div just after
plot creation. The string(s) may include ‘{plot_id}’ placeholders
that will then be replaced by the id
of the div element that the
plotly.js figure is associated with. One application for this script
is to install custom plotly.js event handlers.
full_html (bool (default True)) – If True, produce a string containing a complete HTML document
starting with an <html> tag. If False, produce a string containing
a single <div> element.
animation_opts (dict or None (default None)) – dict of custom animation parameters to be passed to the function
Plotly.animate in Plotly.js. See
https://github.com/plotly/plotly.js/blob/master/src/plots/animation_attributes.js
for available options. Has no effect if the figure does not contain
frames, or auto_play is False.
default_width (number or str (default '100%')) – The default figure width/height to use if the provided figure does not
specify its own layout.width/layout.height property. May be
specified in pixels as an integer (e.g. 500), or as a css width style
string (e.g. ‘500px’, ‘100%’).
default_height (number or str (default '100%')) – The default figure width/height to use if the provided figure does not
specify its own layout.width/layout.height property. May be
specified in pixels as an integer (e.g. 500), or as a css width style
string (e.g. ‘500px’, ‘100%’).
validate (bool (default True)) – True if the figure should be validated before being converted to
JSON, False otherwise.
auto_open (bool (default True)) – If True, open the saved file in a web browser after saving.
This argument only applies if full_html
is True.
div_id (str (default None)) – If provided, this is the value of the id attribute of the div tag. If None, the
id attribute is a UUID.
- Returns
Representation of figure as an HTML div string
- Return type
write_image
(*args, **kwargs)¶
Convert a figure to a static image and write it to a file or writeable
object
- Parameters
file (str or writeable) – A string representing a local file path or a writeable object
(e.g. a pathlib.Path object or an open file descriptor)
- The desired image format. One of
’png’
’jpg’ or ‘jpeg’
’webp’
’svg’
’pdf’
’eps’ (Requires the poppler library to be installed)
If not specified and file
is a string then this will default to the
file extension. If not specified and file
is not a string then this
will default to plotly.io.config.default_format
The width of the exported image in layout pixels. If the scale
property is 1.0, this will also be the width of the exported image
in physical pixels.
If not specified, will default to plotly.io.config.default_width
The height of the exported image in layout pixels. If the scale
property is 1.0, this will also be the height of the exported image
in physical pixels.
If not specified, will default to plotly.io.config.default_height
scale (int or float or None) –
The scale factor to use when exporting the figure. A scale factor
larger than 1.0 will increase the image resolution with respect
to the figure’s layout pixel dimensions. Whereas as scale factor of
less than 1.0 will decrease the image resolution.
If not specified, will default to plotly.io.config.default_scale
validate (bool) – True if the figure should be validated before being converted to
an image, False otherwise.
engine (str) –
- Image export engine to use:
”kaleido”: Use Kaleido for image export
”orca”: Use Orca for image export
”auto” (default): Use Kaleido if installed, otherwise use orca
write_json
(*args, **kwargs)¶
Convert a figure to JSON and write it to a file or writeable
object
- Parameters
file (str or writeable) – A string representing a local file path or a writeable object
(e.g. an open file descriptor)
pretty (bool (default False)) – True if JSON representation should be pretty-printed, False if
representation should be as compact as possible.
remove_uids (bool (default True)) – True if trace UIDs should be omitted from the JSON representation
engine (str (default None)) –
- The JSON encoding engine to use. One of:
”json” for an encoder based on the built-in Python json module
”orjson” for a fast encoder the requires the orjson package
If not specified, the default encoder is set to the current value of
plotly.io.json.config.default_encoder.
- Returns
- Return type
class plotly.basedatatypes.
BaseFrameHierarchyType
(plotly_name, **kwargs)¶
Bases: plotly.basedatatypes.BasePlotlyType
Base class for all types in the trace hierarchy
on_change
(callback, *args)¶
Register callback function to be called when certain properties or
subproperties of this object are modified.
Callback will be invoked whenever ANY of these properties is
modified. Furthermore, the callback will only be invoked once even
if multiple properties are modified during the same restyle /
relayout / update operation.
- Parameters
callback (function) – Function that accepts 1 + len(args
) parameters. First parameter
is this object. Second through last parameters are the
property / subpropery values referenced by args.
args (list[str|tuple[int|str]]) –
List of property references where each reference may be one of:
A property name string (e.g. ‘foo’) for direct properties
A property path string (e.g. ‘foo[0].bar’) for
subproperties
A property path tuple (e.g. (‘foo’, 0, ‘bar’)) for
subproperties
append (bool) – True if callback should be appended to previously registered
callback on the same properties, False if callback should replace
previously registered callbacks on the same properties. Defaults
to False.
Examples
Register callback that prints out the range extents of the xaxis and
yaxis whenever either either of them changes.
>>> import plotly.graph_objects as go
>>> fig = go.Figure(go.Scatter(x=[1, 2], y=[1, 0]))
>>> fig.layout.on_change(
... lambda obj, xrange, yrange: print("%s-%s" % (xrange, yrange)),
... ('xaxis', 'range'), ('yaxis', 'range'))
- Returns
- Return type
class plotly.basedatatypes.
BaseLayoutHierarchyType
(plotly_name, **kwargs)¶
Bases: plotly.basedatatypes.BasePlotlyType
Base class for all types in the layout hierarchy
class plotly.basedatatypes.
BaseLayoutType
(plotly_name, **kwargs)¶
Bases: plotly.basedatatypes.BaseLayoutHierarchyType
Base class for the layout type. The Layout class itself is a
code-generated subclass.
class plotly.basedatatypes.
BasePlotlyType
(plotly_name, **kwargs)¶
Bases: object
BasePlotlyType is the base class for all objects in the trace, layout,
and frame object hierarchies
property figure
¶
Reference to the top-level Figure or FigureWidget that this object
belongs to. None if the object does not belong to a Figure
- Returns
- Return type
Union[BaseFigure, None]
on_change
(callback, *args, **kwargs)¶
Register callback function to be called when certain properties or
subproperties of this object are modified.
Callback will be invoked whenever ANY of these properties is
modified. Furthermore, the callback will only be invoked once even
if multiple properties are modified during the same restyle /
relayout / update operation.
- Parameters
callback (function) – Function that accepts 1 + len(args
) parameters. First parameter
is this object. Second through last parameters are the
property / subpropery values referenced by args.
args (list[str|tuple[int|str]]) –
List of property references where each reference may be one of:
A property name string (e.g. ‘foo’) for direct properties
A property path string (e.g. ‘foo[0].bar’) for
subproperties
A property path tuple (e.g. (‘foo’, 0, ‘bar’)) for
subproperties
append (bool) – True if callback should be appended to previously registered
callback on the same properties, False if callback should replace
previously registered callbacks on the same properties. Defaults
to False.
Examples
Register callback that prints out the range extents of the xaxis and
yaxis whenever either either of them changes.
>>> import plotly.graph_objects as go
>>> fig = go.Figure(go.Scatter(x=[1, 2], y=[1, 0]))
>>> fig.layout.on_change(
... lambda obj, xrange, yrange: print("%s-%s" % (xrange, yrange)),
... ('xaxis', 'range'), ('yaxis', 'range'))
- Returns
- Return type
property parent
¶
Return the object’s parent, or None if the object has no parent
:returns:
:rtype: BasePlotlyType|BaseFigure
key (str) – Property name
dflt – The default value to return if key was not found in object
- Returns
The removed value that was previously associated with key
- Return type
value
- Raises
KeyError – If key is not in object and no dflt argument specified
- Parameters
validate (bool (default True)) – True if the object should be validated before being converted to
JSON, False otherwise.
pretty (bool (default False)) – True if JSON representation should be pretty-printed, False if
representation should be as compact as possible.
remove_uids (bool (default True)) – True if trace UIDs should be omitted from the JSON representation
engine (str (default None)) –
- The JSON encoding engine to use. One of:
”json” for an encoder based on the built-in Python json module
”orjson” for a fast encoder the requires the orjson package
If not specified, the default encoder is set to the current value of
plotly.io.json.config.default_encoder.
- Returns
Representation of object as a JSON string
- Return type
to_plotly_json
()¶
Return plotly JSON representation of object as a Python dict
Note: May include some JSON-invalid data types, use the PlotlyJSONEncoder
util
or the to_json
method to encode to a string.
- Returns
- Return type
update
(dict1=None, overwrite=False, **kwargs)¶
Update the properties of an object with a dict and/or with
keyword arguments.
This recursively updates the structure of the original
object with the values in the input dict / keyword arguments.
- Parameters
dict1 (dict) – Dictionary of properties to be updated
overwrite (bool) – If True, overwrite existing properties. If False, apply updates
to existing properties recursively, preserving existing
properties that are not specified in the update operation.
kwargs – Keyword/value pair of properties to be updated
- Returns
Updated plotly object
- Return type
-
class
plotly.basedatatypes.
BaseTraceHierarchyType
(plotly_name, **kwargs)¶
Bases: plotly.basedatatypes.BasePlotlyType
Base class for all types in the trace hierarchy
class plotly.basedatatypes.
BaseTraceType
(plotly_name, **kwargs)¶
Bases: plotly.basedatatypes.BaseTraceHierarchyType
Base class for the all trace types.
Specific trace type classes (Scatter, Bar, etc.) are code generated as
subclasses of this class.
on_click
(callback, append=False)¶
Register function to be called when the user clicks on one or more
points in this trace.
Note: Callbacks will only be triggered when the trace belongs to a
instance of plotly.graph_objects.FigureWidget and it is displayed in an
ipywidget context. Callbacks will not be triggered on figures
that are displayed using plot/iplot.
- Parameters
callback –
Callable function that accepts 3 arguments
this trace
plotly.callbacks.Points object
plotly.callbacks.InputDeviceState object
append (bool) – If False (the default), this callback replaces any previously
defined on_click callbacks for this trace. If True,
this callback is appended to the list of any previously defined
callbacks.
- Returns
- Return type
Examples
>>> import plotly.graph_objects as go
>>> from plotly.callbacks import Points, InputDeviceState
>>> points, state = Points(), InputDeviceState()
>>> def click_fn(trace, points, state):
... inds = points.point_inds
... # Do something
>>> trace = go.Scatter(x=[1, 2], y=[3, 0])
>>> trace.on_click(click_fn)
Note: The creation of the points
and state
objects is optional,
it’s simply a convenience to help the text editor perform completion
on the arguments inside click_fn
on_deselect
(callback, append=False)¶
Register function to be called when the user deselects points
in this trace using doubleclick.
Note: Callbacks will only be triggered when the trace belongs to a
instance of plotly.graph_objects.FigureWidget and it is displayed in an
ipywidget context. Callbacks will not be triggered on figures
that are displayed using plot/iplot.
- Parameters
callback –
Callable function that accepts 3 arguments
this trace
plotly.callbacks.Points object
append (bool) – If False (the default), this callback replaces any previously
defined on_deselect callbacks for this trace. If True,
this callback is appended to the list of any previously defined
callbacks.
- Returns
- Return type
Examples
>>> import plotly.graph_objects as go
>>> from plotly.callbacks import Points
>>> points = Points()