repository
stringclasses 11
values | repo_id
stringlengths 1
3
| target_module_path
stringlengths 16
72
| prompt
stringlengths 298
21.7k
| relavent_test_path
stringlengths 50
99
| full_function
stringlengths 336
33.8k
| function_name
stringlengths 2
51
|
---|---|---|---|---|---|---|
more-itertools | 80 | more_itertools/recipes.py | def powerset(iterable):
"""Yields all possible subsets of the iterable.
>>> list(powerset([1, 2, 3]))
[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
:func:`powerset` will operate on iterables that aren't :class:`set`
instances, so repeated elements in the input will produce repeated elements
in the output.
>>> seq = [1, 1, 0]
>>> list(powerset(seq))
[(), (1,), (1,), (0,), (1, 1), (1, 0), (1, 0), (1, 1, 0)]
For a variant that efficiently yields actual :class:`set` instances, see
:func:`powerset_of_sets`.
"""
| /usr/src/app/target_test_cases/failed_tests_recipes.powerset.txt | def powerset(iterable):
"""Yields all possible subsets of the iterable.
>>> list(powerset([1, 2, 3]))
[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
:func:`powerset` will operate on iterables that aren't :class:`set`
instances, so repeated elements in the input will produce repeated elements
in the output.
>>> seq = [1, 1, 0]
>>> list(powerset(seq))
[(), (1,), (1,), (0,), (1, 1), (1, 0), (1, 0), (1, 1, 0)]
For a variant that efficiently yields actual :class:`set` instances, see
:func:`powerset_of_sets`.
"""
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))
| recipes.powerset |
more-itertools | 81 | more_itertools/recipes.py | def random_product(*args, repeat=1):
"""Draw an item at random from each of the input iterables.
>>> random_product('abc', range(4), 'XYZ') # doctest:+SKIP
('c', 3, 'Z')
If *repeat* is provided as a keyword argument, that many items will be
drawn from each iterable.
>>> random_product('abcd', range(4), repeat=2) # doctest:+SKIP
('a', 2, 'd', 3)
This equivalent to taking a random selection from
``itertools.product(*args, **kwarg)``.
"""
| /usr/src/app/target_test_cases/failed_tests_recipes.random_product.txt | def random_product(*args, repeat=1):
"""Draw an item at random from each of the input iterables.
>>> random_product('abc', range(4), 'XYZ') # doctest:+SKIP
('c', 3, 'Z')
If *repeat* is provided as a keyword argument, that many items will be
drawn from each iterable.
>>> random_product('abcd', range(4), repeat=2) # doctest:+SKIP
('a', 2, 'd', 3)
This equivalent to taking a random selection from
``itertools.product(*args, **kwarg)``.
"""
pools = [tuple(pool) for pool in args] * repeat
return tuple(choice(pool) for pool in pools)
| recipes.random_product |
more-itertools | 82 | more_itertools/recipes.py | def repeatfunc(func, times=None, *args):
"""Call *func* with *args* repeatedly, returning an iterable over the
results.
If *times* is specified, the iterable will terminate after that many
repetitions:
>>> from operator import add
>>> times = 4
>>> args = 3, 5
>>> list(repeatfunc(add, times, *args))
[8, 8, 8, 8]
If *times* is ``None`` the iterable will not terminate:
>>> from random import randrange
>>> times = None
>>> args = 1, 11
>>> take(6, repeatfunc(randrange, times, *args)) # doctest:+SKIP
[2, 4, 8, 1, 8, 4]
"""
| /usr/src/app/target_test_cases/failed_tests_recipes.repeatfunc.txt | def repeatfunc(func, times=None, *args):
"""Call *func* with *args* repeatedly, returning an iterable over the
results.
If *times* is specified, the iterable will terminate after that many
repetitions:
>>> from operator import add
>>> times = 4
>>> args = 3, 5
>>> list(repeatfunc(add, times, *args))
[8, 8, 8, 8]
If *times* is ``None`` the iterable will not terminate:
>>> from random import randrange
>>> times = None
>>> args = 1, 11
>>> take(6, repeatfunc(randrange, times, *args)) # doctest:+SKIP
[2, 4, 8, 1, 8, 4]
"""
if times is None:
return starmap(func, repeat(args))
return starmap(func, repeat(args, times))
| recipes.repeatfunc |
more-itertools | 83 | more_itertools/recipes.py | def tabulate(function, start=0):
"""Return an iterator over the results of ``func(start)``,
``func(start + 1)``, ``func(start + 2)``...
*func* should be a function that accepts one integer argument.
If *start* is not specified it defaults to 0. It will be incremented each
time the iterator is advanced.
>>> square = lambda x: x ** 2
>>> iterator = tabulate(square, -3)
>>> take(4, iterator)
[9, 4, 1, 0]
"""
| /usr/src/app/target_test_cases/failed_tests_recipes.tabulate.txt | def tabulate(function, start=0):
"""Return an iterator over the results of ``func(start)``,
``func(start + 1)``, ``func(start + 2)``...
*func* should be a function that accepts one integer argument.
If *start* is not specified it defaults to 0. It will be incremented each
time the iterator is advanced.
>>> square = lambda x: x ** 2
>>> iterator = tabulate(square, -3)
>>> take(4, iterator)
[9, 4, 1, 0]
"""
return map(function, count(start))
| recipes.tabulate |
more-itertools | 84 | more_itertools/recipes.py | def unique(iterable, key=None, reverse=False):
"""Yields unique elements in sorted order.
>>> list(unique([[1, 2], [3, 4], [1, 2]]))
[[1, 2], [3, 4]]
*key* and *reverse* are passed to :func:`sorted`.
>>> list(unique('ABBcCAD', str.casefold))
['A', 'B', 'c', 'D']
>>> list(unique('ABBcCAD', str.casefold, reverse=True))
['D', 'c', 'B', 'A']
The elements in *iterable* need not be hashable, but they must be
comparable for sorting to work.
"""
| /usr/src/app/target_test_cases/failed_tests_recipes.unique.txt | def unique(iterable, key=None, reverse=False):
"""Yields unique elements in sorted order.
>>> list(unique([[1, 2], [3, 4], [1, 2]]))
[[1, 2], [3, 4]]
*key* and *reverse* are passed to :func:`sorted`.
>>> list(unique('ABBcCAD', str.casefold))
['A', 'B', 'c', 'D']
>>> list(unique('ABBcCAD', str.casefold, reverse=True))
['D', 'c', 'B', 'A']
The elements in *iterable* need not be hashable, but they must be
comparable for sorting to work.
"""
return unique_justseen(sorted(iterable, key=key, reverse=reverse), key=key)
| recipes.unique |
more-itertools | 85 | more_itertools/recipes.py | def unique_everseen(iterable, key=None):
"""
Yield unique elements, preserving order.
>>> list(unique_everseen('AAAABBBCCDAABBB'))
['A', 'B', 'C', 'D']
>>> list(unique_everseen('ABBCcAD', str.lower))
['A', 'B', 'C', 'D']
Sequences with a mix of hashable and unhashable items can be used.
The function will be slower (i.e., `O(n^2)`) for unhashable items.
Remember that ``list`` objects are unhashable - you can use the *key*
parameter to transform the list to a tuple (which is hashable) to
avoid a slowdown.
>>> iterable = ([1, 2], [2, 3], [1, 2])
>>> list(unique_everseen(iterable)) # Slow
[[1, 2], [2, 3]]
>>> list(unique_everseen(iterable, key=tuple)) # Faster
[[1, 2], [2, 3]]
Similarly, you may want to convert unhashable ``set`` objects with
``key=frozenset``. For ``dict`` objects,
``key=lambda x: frozenset(x.items())`` can be used.
"""
| /usr/src/app/target_test_cases/failed_tests_recipes.unique_everseen.txt | def unique_everseen(iterable, key=None):
"""
Yield unique elements, preserving order.
>>> list(unique_everseen('AAAABBBCCDAABBB'))
['A', 'B', 'C', 'D']
>>> list(unique_everseen('ABBCcAD', str.lower))
['A', 'B', 'C', 'D']
Sequences with a mix of hashable and unhashable items can be used.
The function will be slower (i.e., `O(n^2)`) for unhashable items.
Remember that ``list`` objects are unhashable - you can use the *key*
parameter to transform the list to a tuple (which is hashable) to
avoid a slowdown.
>>> iterable = ([1, 2], [2, 3], [1, 2])
>>> list(unique_everseen(iterable)) # Slow
[[1, 2], [2, 3]]
>>> list(unique_everseen(iterable, key=tuple)) # Faster
[[1, 2], [2, 3]]
Similarly, you may want to convert unhashable ``set`` objects with
``key=frozenset``. For ``dict`` objects,
``key=lambda x: frozenset(x.items())`` can be used.
"""
seenset = set()
seenset_add = seenset.add
seenlist = []
seenlist_add = seenlist.append
use_key = key is not None
for element in iterable:
k = key(element) if use_key else element
try:
if k not in seenset:
seenset_add(k)
yield element
except TypeError:
if k not in seenlist:
seenlist_add(k)
yield element
| recipes.unique_everseen |
plotly.py | 0 | packages/python/plotly/plotly/graph_objs/_bar.py | def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.bar.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Supported dict properties:
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.colorscale`. Has an
effect only if in `marker.color` is set to a
numerical array. In case `colorscale` is
unspecified or `autocolorscale` is true, the
default palette will be chosen according to
whether numbers in the `color` array are all
positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `marker.color`) or the bounds set in
`marker.cmin` and `marker.cmax` Has an effect
only if in `marker.color` is set to a numerical
array. Defaults to `false` when `marker.cmin`
and `marker.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `marker.cmin` and/or `marker.cmax` to
be equidistant to this point. Has an effect
only if in `marker.color` is set to a numerical
array. Value should have the same units as in
`marker.color`. Has no effect when
`marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmax` must be set as well.
color
Sets the marker color. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`marker.cmin` and `marker.cmax` if set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.bar.marker.ColorBa
r` instance or dict with compatible properties
colorscale
Sets the colorscale. Has an effect only if in
`marker.color` is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `marker.cmin` and
`marker.cmax`. Alternatively, `colorscale` may
be a palette name string of the following list:
Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud
for `color`.
cornerradius
Sets the rounding of corners. May be an integer
number of pixels, or a percentage of bar width
(as a string ending in %). Defaults to
`layout.barcornerradius`. In stack or relative
barmode, the first trace to set cornerradius is
used for the whole stack.
line
:class:`plotly.graph_objects.bar.marker.Line`
instance or dict with compatible properties
opacity
Sets the opacity of the bars.
opacitysrc
Sets the source reference on Chart Studio Cloud
for `opacity`.
pattern
Sets the pattern within the marker.
reversescale
Reverses the color mapping if true. Has an
effect only if in `marker.color` is set to a
numerical array. If true, `marker.cmin` will
correspond to the last color in the array and
`marker.cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
in `marker.color` is set to a numerical array.
Returns
-------
plotly.graph_objs.bar.Marker
"""
| /usr/src/app/target_test_cases/failed_tests__bar.marker.txt | def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.bar.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Supported dict properties:
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.colorscale`. Has an
effect only if in `marker.color` is set to a
numerical array. In case `colorscale` is
unspecified or `autocolorscale` is true, the
default palette will be chosen according to
whether numbers in the `color` array are all
positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `marker.color`) or the bounds set in
`marker.cmin` and `marker.cmax` Has an effect
only if in `marker.color` is set to a numerical
array. Defaults to `false` when `marker.cmin`
and `marker.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `marker.cmin` and/or `marker.cmax` to
be equidistant to this point. Has an effect
only if in `marker.color` is set to a numerical
array. Value should have the same units as in
`marker.color`. Has no effect when
`marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmax` must be set as well.
color
Sets the marker color. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`marker.cmin` and `marker.cmax` if set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.bar.marker.ColorBa
r` instance or dict with compatible properties
colorscale
Sets the colorscale. Has an effect only if in
`marker.color` is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `marker.cmin` and
`marker.cmax`. Alternatively, `colorscale` may
be a palette name string of the following list:
Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud
for `color`.
cornerradius
Sets the rounding of corners. May be an integer
number of pixels, or a percentage of bar width
(as a string ending in %). Defaults to
`layout.barcornerradius`. In stack or relative
barmode, the first trace to set cornerradius is
used for the whole stack.
line
:class:`plotly.graph_objects.bar.marker.Line`
instance or dict with compatible properties
opacity
Sets the opacity of the bars.
opacitysrc
Sets the source reference on Chart Studio Cloud
for `opacity`.
pattern
Sets the pattern within the marker.
reversescale
Reverses the color mapping if true. Has an
effect only if in `marker.color` is set to a
numerical array. If true, `marker.cmin` will
correspond to the last color in the array and
`marker.cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
in `marker.color` is set to a numerical array.
Returns
-------
plotly.graph_objs.bar.Marker
"""
return self["marker"]
| _bar.marker |
plotly.py | 1 | packages/python/plotly/plotly/figure_factory/_bullet.py | def create_bullet(
data,
markers=None,
measures=None,
ranges=None,
subtitles=None,
titles=None,
orientation="h",
range_colors=("rgb(200, 200, 200)", "rgb(245, 245, 245)"),
measure_colors=("rgb(31, 119, 180)", "rgb(176, 196, 221)"),
horizontal_spacing=None,
vertical_spacing=None,
scatter_options={},
**layout_options,
):
"""
**deprecated**, use instead the plotly.graph_objects trace
:class:`plotly.graph_objects.Indicator`.
:param (pd.DataFrame | list | tuple) data: either a list/tuple of
dictionaries or a pandas DataFrame.
:param (str) markers: the column name or dictionary key for the markers in
each subplot.
:param (str) measures: the column name or dictionary key for the measure
bars in each subplot. This bar usually represents the quantitative
measure of performance, usually a list of two values [a, b] and are
the blue bars in the foreground of each subplot by default.
:param (str) ranges: the column name or dictionary key for the qualitative
ranges of performance, usually a 3-item list [bad, okay, good]. They
correspond to the grey bars in the background of each chart.
:param (str) subtitles: the column name or dictionary key for the subtitle
of each subplot chart. The subplots are displayed right underneath
each title.
:param (str) titles: the column name or dictionary key for the main label
of each subplot chart.
:param (bool) orientation: if 'h', the bars are placed horizontally as
rows. If 'v' the bars are placed vertically in the chart.
:param (list) range_colors: a tuple of two colors between which all
the rectangles for the range are drawn. These rectangles are meant to
be qualitative indicators against which the marker and measure bars
are compared.
Default=('rgb(200, 200, 200)', 'rgb(245, 245, 245)')
:param (list) measure_colors: a tuple of two colors which is used to color
the thin quantitative bars in the bullet chart.
Default=('rgb(31, 119, 180)', 'rgb(176, 196, 221)')
:param (float) horizontal_spacing: see the 'horizontal_spacing' param in
plotly.tools.make_subplots. Ranges between 0 and 1.
:param (float) vertical_spacing: see the 'vertical_spacing' param in
plotly.tools.make_subplots. Ranges between 0 and 1.
:param (dict) scatter_options: describes attributes for the scatter trace
in each subplot such as name and marker size. Call
help(plotly.graph_objs.Scatter) for more information on valid params.
:param layout_options: describes attributes for the layout of the figure
such as title, height and width. Call help(plotly.graph_objs.Layout)
for more information on valid params.
Example 1: Use a Dictionary
>>> import plotly.figure_factory as ff
>>> data = [
... {"label": "revenue", "sublabel": "us$, in thousands",
... "range": [150, 225, 300], "performance": [220,270], "point": [250]},
... {"label": "Profit", "sublabel": "%", "range": [20, 25, 30],
... "performance": [21, 23], "point": [26]},
... {"label": "Order Size", "sublabel":"US$, average","range": [350, 500, 600],
... "performance": [100,320],"point": [550]},
... {"label": "New Customers", "sublabel": "count", "range": [1400, 2000, 2500],
... "performance": [1000, 1650],"point": [2100]},
... {"label": "Satisfaction", "sublabel": "out of 5","range": [3.5, 4.25, 5],
... "performance": [3.2, 4.7], "point": [4.4]}
... ]
>>> fig = ff.create_bullet(
... data, titles='label', subtitles='sublabel', markers='point',
... measures='performance', ranges='range', orientation='h',
... title='my simple bullet chart'
... )
>>> fig.show()
Example 2: Use a DataFrame with Custom Colors
>>> import plotly.figure_factory as ff
>>> import pandas as pd
>>> data = pd.read_json('https://cdn.rawgit.com/plotly/datasets/master/BulletData.json')
>>> fig = ff.create_bullet(
... data, titles='title', markers='markers', measures='measures',
... orientation='v', measure_colors=['rgb(14, 52, 75)', 'rgb(31, 141, 127)'],
... scatter_options={'marker': {'symbol': 'circle'}}, width=700)
>>> fig.show()
"""
| /usr/src/app/target_test_cases/failed_tests__bullet.create_bullet.txt | def create_bullet(
data,
markers=None,
measures=None,
ranges=None,
subtitles=None,
titles=None,
orientation="h",
range_colors=("rgb(200, 200, 200)", "rgb(245, 245, 245)"),
measure_colors=("rgb(31, 119, 180)", "rgb(176, 196, 221)"),
horizontal_spacing=None,
vertical_spacing=None,
scatter_options={},
**layout_options,
):
"""
**deprecated**, use instead the plotly.graph_objects trace
:class:`plotly.graph_objects.Indicator`.
:param (pd.DataFrame | list | tuple) data: either a list/tuple of
dictionaries or a pandas DataFrame.
:param (str) markers: the column name or dictionary key for the markers in
each subplot.
:param (str) measures: the column name or dictionary key for the measure
bars in each subplot. This bar usually represents the quantitative
measure of performance, usually a list of two values [a, b] and are
the blue bars in the foreground of each subplot by default.
:param (str) ranges: the column name or dictionary key for the qualitative
ranges of performance, usually a 3-item list [bad, okay, good]. They
correspond to the grey bars in the background of each chart.
:param (str) subtitles: the column name or dictionary key for the subtitle
of each subplot chart. The subplots are displayed right underneath
each title.
:param (str) titles: the column name or dictionary key for the main label
of each subplot chart.
:param (bool) orientation: if 'h', the bars are placed horizontally as
rows. If 'v' the bars are placed vertically in the chart.
:param (list) range_colors: a tuple of two colors between which all
the rectangles for the range are drawn. These rectangles are meant to
be qualitative indicators against which the marker and measure bars
are compared.
Default=('rgb(200, 200, 200)', 'rgb(245, 245, 245)')
:param (list) measure_colors: a tuple of two colors which is used to color
the thin quantitative bars in the bullet chart.
Default=('rgb(31, 119, 180)', 'rgb(176, 196, 221)')
:param (float) horizontal_spacing: see the 'horizontal_spacing' param in
plotly.tools.make_subplots. Ranges between 0 and 1.
:param (float) vertical_spacing: see the 'vertical_spacing' param in
plotly.tools.make_subplots. Ranges between 0 and 1.
:param (dict) scatter_options: describes attributes for the scatter trace
in each subplot such as name and marker size. Call
help(plotly.graph_objs.Scatter) for more information on valid params.
:param layout_options: describes attributes for the layout of the figure
such as title, height and width. Call help(plotly.graph_objs.Layout)
for more information on valid params.
Example 1: Use a Dictionary
>>> import plotly.figure_factory as ff
>>> data = [
... {"label": "revenue", "sublabel": "us$, in thousands",
... "range": [150, 225, 300], "performance": [220,270], "point": [250]},
... {"label": "Profit", "sublabel": "%", "range": [20, 25, 30],
... "performance": [21, 23], "point": [26]},
... {"label": "Order Size", "sublabel":"US$, average","range": [350, 500, 600],
... "performance": [100,320],"point": [550]},
... {"label": "New Customers", "sublabel": "count", "range": [1400, 2000, 2500],
... "performance": [1000, 1650],"point": [2100]},
... {"label": "Satisfaction", "sublabel": "out of 5","range": [3.5, 4.25, 5],
... "performance": [3.2, 4.7], "point": [4.4]}
... ]
>>> fig = ff.create_bullet(
... data, titles='label', subtitles='sublabel', markers='point',
... measures='performance', ranges='range', orientation='h',
... title='my simple bullet chart'
... )
>>> fig.show()
Example 2: Use a DataFrame with Custom Colors
>>> import plotly.figure_factory as ff
>>> import pandas as pd
>>> data = pd.read_json('https://cdn.rawgit.com/plotly/datasets/master/BulletData.json')
>>> fig = ff.create_bullet(
... data, titles='title', markers='markers', measures='measures',
... orientation='v', measure_colors=['rgb(14, 52, 75)', 'rgb(31, 141, 127)'],
... scatter_options={'marker': {'symbol': 'circle'}}, width=700)
>>> fig.show()
"""
# validate df
if not pd:
raise ImportError("'pandas' must be installed for this figure factory.")
if utils.is_sequence(data):
if not all(isinstance(item, dict) for item in data):
raise exceptions.PlotlyError(
"Every entry of the data argument list, tuple, etc must "
"be a dictionary."
)
elif not isinstance(data, pd.DataFrame):
raise exceptions.PlotlyError(
"You must input a pandas DataFrame, or a list of dictionaries."
)
# make DataFrame from data with correct column headers
col_names = ["titles", "subtitle", "markers", "measures", "ranges"]
if utils.is_sequence(data):
df = pd.DataFrame(
[
[d[titles] for d in data] if titles else [""] * len(data),
[d[subtitles] for d in data] if subtitles else [""] * len(data),
[d[markers] for d in data] if markers else [[]] * len(data),
[d[measures] for d in data] if measures else [[]] * len(data),
[d[ranges] for d in data] if ranges else [[]] * len(data),
],
index=col_names,
)
elif isinstance(data, pd.DataFrame):
df = pd.DataFrame(
[
data[titles].tolist() if titles else [""] * len(data),
data[subtitles].tolist() if subtitles else [""] * len(data),
data[markers].tolist() if markers else [[]] * len(data),
data[measures].tolist() if measures else [[]] * len(data),
data[ranges].tolist() if ranges else [[]] * len(data),
],
index=col_names,
)
df = pd.DataFrame.transpose(df)
# make sure ranges, measures, 'markers' are not NAN or NONE
for needed_key in ["ranges", "measures", "markers"]:
for idx, r in enumerate(df[needed_key]):
try:
r_is_nan = math.isnan(r)
if r_is_nan or r is None:
df[needed_key][idx] = []
except TypeError:
pass
# validate custom colors
for colors_list in [range_colors, measure_colors]:
if colors_list:
if len(colors_list) != 2:
raise exceptions.PlotlyError(
"Both 'range_colors' or 'measure_colors' must be a list "
"of two valid colors."
)
clrs.validate_colors(colors_list)
colors_list = clrs.convert_colors_to_same_type(colors_list, "rgb")[0]
# default scatter options
default_scatter = {
"marker": {"size": 12, "symbol": "diamond-tall", "color": "rgb(0, 0, 0)"}
}
if scatter_options == {}:
scatter_options.update(default_scatter)
else:
# add default options to scatter_options if they are not present
for k in default_scatter["marker"]:
if k not in scatter_options["marker"]:
scatter_options["marker"][k] = default_scatter["marker"][k]
fig = _bullet(
df,
markers,
measures,
ranges,
subtitles,
titles,
orientation,
range_colors,
measure_colors,
horizontal_spacing,
vertical_spacing,
scatter_options,
layout_options,
)
return fig
| _bullet.create_bullet |
plotly.py | 2 | packages/python/plotly/plotly/figure_factory/_candlestick.py | def create_candlestick(open, high, low, close, dates=None, direction="both", **kwargs):
"""
**deprecated**, use instead the plotly.graph_objects trace
:class:`plotly.graph_objects.Candlestick`
:param (list) open: opening values
:param (list) high: high values
:param (list) low: low values
:param (list) close: closing values
:param (list) dates: list of datetime objects. Default: None
:param (string) direction: direction can be 'increasing', 'decreasing',
or 'both'. When the direction is 'increasing', the returned figure
consists of all candlesticks where the close value is greater than
the corresponding open value, and when the direction is
'decreasing', the returned figure consists of all candlesticks
where the close value is less than or equal to the corresponding
open value. When the direction is 'both', both increasing and
decreasing candlesticks are returned. Default: 'both'
:param kwargs: kwargs passed through plotly.graph_objs.Scatter.
These kwargs describe other attributes about the ohlc Scatter trace
such as the color or the legend name. For more information on valid
kwargs call help(plotly.graph_objs.Scatter)
:rtype (dict): returns a representation of candlestick chart figure.
Example 1: Simple candlestick chart from a Pandas DataFrame
>>> from plotly.figure_factory import create_candlestick
>>> from datetime import datetime
>>> import pandas as pd
>>> df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
>>> fig = create_candlestick(df['AAPL.Open'], df['AAPL.High'], df['AAPL.Low'], df['AAPL.Close'],
... dates=df.index)
>>> fig.show()
Example 2: Customize the candlestick colors
>>> from plotly.figure_factory import create_candlestick
>>> from plotly.graph_objs import Line, Marker
>>> from datetime import datetime
>>> import pandas as pd
>>> df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
>>> # Make increasing candlesticks and customize their color and name
>>> fig_increasing = create_candlestick(df['AAPL.Open'], df['AAPL.High'], df['AAPL.Low'], df['AAPL.Close'],
... dates=df.index,
... direction='increasing', name='AAPL',
... marker=Marker(color='rgb(150, 200, 250)'),
... line=Line(color='rgb(150, 200, 250)'))
>>> # Make decreasing candlesticks and customize their color and name
>>> fig_decreasing = create_candlestick(df['AAPL.Open'], df['AAPL.High'], df['AAPL.Low'], df['AAPL.Close'],
... dates=df.index,
... direction='decreasing',
... marker=Marker(color='rgb(128, 128, 128)'),
... line=Line(color='rgb(128, 128, 128)'))
>>> # Initialize the figure
>>> fig = fig_increasing
>>> # Add decreasing data with .extend()
>>> fig.add_trace(fig_decreasing['data']) # doctest: +SKIP
>>> fig.show()
Example 3: Candlestick chart with datetime objects
>>> from plotly.figure_factory import create_candlestick
>>> from datetime import datetime
>>> # Add data
>>> open_data = [33.0, 33.3, 33.5, 33.0, 34.1]
>>> high_data = [33.1, 33.3, 33.6, 33.2, 34.8]
>>> low_data = [32.7, 32.7, 32.8, 32.6, 32.8]
>>> close_data = [33.0, 32.9, 33.3, 33.1, 33.1]
>>> dates = [datetime(year=2013, month=10, day=10),
... datetime(year=2013, month=11, day=10),
... datetime(year=2013, month=12, day=10),
... datetime(year=2014, month=1, day=10),
... datetime(year=2014, month=2, day=10)]
>>> # Create ohlc
>>> fig = create_candlestick(open_data, high_data,
... low_data, close_data, dates=dates)
>>> fig.show()
"""
| /usr/src/app/target_test_cases/failed_tests__candlestick.create_candlestick.txt | def create_candlestick(open, high, low, close, dates=None, direction="both", **kwargs):
"""
**deprecated**, use instead the plotly.graph_objects trace
:class:`plotly.graph_objects.Candlestick`
:param (list) open: opening values
:param (list) high: high values
:param (list) low: low values
:param (list) close: closing values
:param (list) dates: list of datetime objects. Default: None
:param (string) direction: direction can be 'increasing', 'decreasing',
or 'both'. When the direction is 'increasing', the returned figure
consists of all candlesticks where the close value is greater than
the corresponding open value, and when the direction is
'decreasing', the returned figure consists of all candlesticks
where the close value is less than or equal to the corresponding
open value. When the direction is 'both', both increasing and
decreasing candlesticks are returned. Default: 'both'
:param kwargs: kwargs passed through plotly.graph_objs.Scatter.
These kwargs describe other attributes about the ohlc Scatter trace
such as the color or the legend name. For more information on valid
kwargs call help(plotly.graph_objs.Scatter)
:rtype (dict): returns a representation of candlestick chart figure.
Example 1: Simple candlestick chart from a Pandas DataFrame
>>> from plotly.figure_factory import create_candlestick
>>> from datetime import datetime
>>> import pandas as pd
>>> df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
>>> fig = create_candlestick(df['AAPL.Open'], df['AAPL.High'], df['AAPL.Low'], df['AAPL.Close'],
... dates=df.index)
>>> fig.show()
Example 2: Customize the candlestick colors
>>> from plotly.figure_factory import create_candlestick
>>> from plotly.graph_objs import Line, Marker
>>> from datetime import datetime
>>> import pandas as pd
>>> df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
>>> # Make increasing candlesticks and customize their color and name
>>> fig_increasing = create_candlestick(df['AAPL.Open'], df['AAPL.High'], df['AAPL.Low'], df['AAPL.Close'],
... dates=df.index,
... direction='increasing', name='AAPL',
... marker=Marker(color='rgb(150, 200, 250)'),
... line=Line(color='rgb(150, 200, 250)'))
>>> # Make decreasing candlesticks and customize their color and name
>>> fig_decreasing = create_candlestick(df['AAPL.Open'], df['AAPL.High'], df['AAPL.Low'], df['AAPL.Close'],
... dates=df.index,
... direction='decreasing',
... marker=Marker(color='rgb(128, 128, 128)'),
... line=Line(color='rgb(128, 128, 128)'))
>>> # Initialize the figure
>>> fig = fig_increasing
>>> # Add decreasing data with .extend()
>>> fig.add_trace(fig_decreasing['data']) # doctest: +SKIP
>>> fig.show()
Example 3: Candlestick chart with datetime objects
>>> from plotly.figure_factory import create_candlestick
>>> from datetime import datetime
>>> # Add data
>>> open_data = [33.0, 33.3, 33.5, 33.0, 34.1]
>>> high_data = [33.1, 33.3, 33.6, 33.2, 34.8]
>>> low_data = [32.7, 32.7, 32.8, 32.6, 32.8]
>>> close_data = [33.0, 32.9, 33.3, 33.1, 33.1]
>>> dates = [datetime(year=2013, month=10, day=10),
... datetime(year=2013, month=11, day=10),
... datetime(year=2013, month=12, day=10),
... datetime(year=2014, month=1, day=10),
... datetime(year=2014, month=2, day=10)]
>>> # Create ohlc
>>> fig = create_candlestick(open_data, high_data,
... low_data, close_data, dates=dates)
>>> fig.show()
"""
if dates is not None:
utils.validate_equal_length(open, high, low, close, dates)
else:
utils.validate_equal_length(open, high, low, close)
validate_ohlc(open, high, low, close, direction, **kwargs)
if direction == "increasing":
candle_incr_data = make_increasing_candle(
open, high, low, close, dates, **kwargs
)
data = candle_incr_data
elif direction == "decreasing":
candle_decr_data = make_decreasing_candle(
open, high, low, close, dates, **kwargs
)
data = candle_decr_data
else:
candle_incr_data = make_increasing_candle(
open, high, low, close, dates, **kwargs
)
candle_decr_data = make_decreasing_candle(
open, high, low, close, dates, **kwargs
)
data = candle_incr_data + candle_decr_data
layout = graph_objs.Layout()
return graph_objs.Figure(data=data, layout=layout)
| _candlestick.create_candlestick |
plotly.py | 3 | packages/python/plotly/plotly/graph_objs/layout/_coloraxis.py | def colorbar(self):
"""
The 'colorbar' property is an instance of ColorBar
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.coloraxis.ColorBar`
- A dict of string/value properties that will be passed
to the ColorBar constructor
Supported dict properties:
bgcolor
Sets the color of padded area.
bordercolor
Sets the axis line color.
borderwidth
Sets the width (in px) or the border enclosing
this color bar.
dtick
Sets the step in-between ticks on this axis.
Use with `tick0`. Must be a positive number, or
special strings available to "log" and "date"
axes. If the axis `type` is "log", then ticks
are set every 10^(n*dtick) where n is the tick
number. For example, to set a tick mark at 1,
10, 100, 1000, ... set dtick to 1. To set tick
marks at 1, 100, 10000, ... set dtick to 2. To
set tick marks at 1, 5, 25, 125, 625, 3125, ...
set dtick to log_10(5), or 0.69897000433. "log"
has several special values; "L<f>", where `f`
is a positive number, gives ticks linearly
spaced in value (but not position). For example
`tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10
plus small digits between, use "D1" (all
digits) or "D2" (only 2 and 5). `tick0` is
ignored for "D1" and "D2". If the axis `type`
is "date", then you must convert the time to
milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to
86400000.0. "date" also has special values
"M<n>" gives ticks spaced by a number of
months. `n` must be a positive integer. To set
ticks on the 15th of every third month, set
`tick0` to "2000-01-15" and `dtick` to "M3". To
set ticks every 4 years, set `dtick` to "M48"
exponentformat
Determines a formatting rule for the tick
exponents. For example, consider the number
1,000,000,000. If "none", it appears as
1,000,000,000. If "e", 1e+9. If "E", 1E+9. If
"power", 1x10^9 (with 9 in a super script). If
"SI", 1G. If "B", 1B.
labelalias
Replacement text for specific tick or hover
labels. For example using {US: 'USA', CA:
'Canada'} changes US to USA and CA to Canada.
The labels we would have shown must match the
keys exactly, after adding any tickprefix or
ticksuffix. For negative numbers the minus sign
symbol used (U+2212) is wider than the regular
ascii dash. That means you need to use −1
instead of -1. labelalias can be used with any
axis type, and both keys (if needed) and values
(if desired) can include html-like tags or
MathJax.
len
Sets the length of the color bar This measure
excludes the padding of both ends. That is, the
color bar length is this length minus the
padding on both ends.
lenmode
Determines whether this color bar's length
(i.e. the measure in the color variation
direction) is set in units of plot "fraction"
or in *pixels. Use `len` to set the value.
minexponent
Hide SI prefix for 10^n if |n| is below this
number. This only has an effect when
`tickformat` is "SI" or "B".
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks
will be chosen automatically to be less than or
equal to `nticks`. Has an effect only if
`tickmode` is set to "auto".
orientation
Sets the orientation of the colorbar.
outlinecolor
Sets the axis line color.
outlinewidth
Sets the width (in px) of the axis line.
separatethousands
If "true", even 4-digit integers are separated
showexponent
If "all", all exponents are shown besides their
significands. If "first", only the exponent of
the first tick is shown. If "last", only the
exponent of the last tick is shown. If "none",
no exponents appear.
showticklabels
Determines whether or not the tick labels are
drawn.
showtickprefix
If "all", all tick labels are displayed with a
prefix. If "first", only the first tick is
displayed with a prefix. If "last", only the
last tick is displayed with a suffix. If
"none", tick prefixes are hidden.
showticksuffix
Same as `showtickprefix` but for tick suffixes.
thickness
Sets the thickness of the color bar This
measure excludes the size of the padding, ticks
and labels.
thicknessmode
Determines whether this color bar's thickness
(i.e. the measure in the constant color
direction) is set in units of plot "fraction"
or in "pixels". Use `thickness` to set the
value.
tick0
Sets the placement of the first tick on this
axis. Use with `dtick`. If the axis `type` is
"log", then you must take the log of your
starting tick (e.g. to set the starting tick to
100, set the `tick0` to 2) except when
`dtick`=*L<f>* (see `dtick` for more info). If
the axis `type` is "date", it should be a date
string, like date data. If the axis `type` is
"category", it should be a number, using the
scale where each category is assigned a serial
number from zero in the order it appears.
tickangle
Sets the angle of the tick labels with respect
to the horizontal. For example, a `tickangle`
of -90 draws the tick labels vertically.
tickcolor
Sets the tick color.
tickfont
Sets the color bar's tick label font
tickformat
Sets the tick label formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see: h
ttps://github.com/d3/d3-format/tree/v1.4.5#d3-
format. And for dates see:
https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two
items to d3's date formatter: "%h" for half of
the year as a decimal number as well as "%{n}f"
for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with
tickformat "%H~%M~%S.%2f" would display
"09~15~23.46"
tickformatstops
A tuple of :class:`plotly.graph_objects.layout.
coloraxis.colorbar.Tickformatstop` instances or
dicts with compatible properties
tickformatstopdefaults
When used in a template (as layout.template.lay
out.coloraxis.colorbar.tickformatstopdefaults),
sets the default property values to use for
elements of
layout.coloraxis.colorbar.tickformatstops
ticklabeloverflow
Determines how we handle tick labels that would
overflow either the graph div or the domain of
the axis. The default value for inside tick
labels is *hide past domain*. In other cases
the default is *hide past div*.
ticklabelposition
Determines where tick labels are drawn relative
to the ticks. Left and right options are used
when `orientation` is "h", top and bottom when
`orientation` is "v".
ticklabelstep
Sets the spacing between tick labels as
compared to the spacing between ticks. A value
of 1 (default) means each tick gets a label. A
value of 2 means shows every 2nd label. A
larger value n means only every nth tick is
labeled. `tick0` determines which labels are
shown. Not implemented for axes with `type`
"log" or "multicategory", or when `tickmode` is
"array".
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto",
the number of ticks is set via `nticks`. If
"linear", the placement of the ticks is
determined by a starting position `tick0` and a
tick step `dtick` ("linear" is the default
value if `tick0` and `dtick` are provided). If
"array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`.
("array" is the default value if `tickvals` is
provided).
tickprefix
Sets a tick label prefix.
ticks
Determines whether ticks are drawn or not. If
"", this axis' ticks are not drawn. If
"outside" ("inside"), this axis' are drawn
outside (inside) the axis lines.
ticksuffix
Sets a tick label suffix.
ticktext
Sets the text displayed at the ticks position
via `tickvals`. Only has an effect if
`tickmode` is set to "array". Used with
`tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud
for `ticktext`.
tickvals
Sets the values at which ticks on this axis
appear. Only has an effect if `tickmode` is set
to "array". Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud
for `tickvals`.
tickwidth
Sets the tick width (in px).
title
:class:`plotly.graph_objects.layout.coloraxis.c
olorbar.Title` instance or dict with compatible
properties
titlefont
Deprecated: Please use
layout.coloraxis.colorbar.title.font instead.
Sets this color bar's title font. Note that the
title's font used to be set by the now
deprecated `titlefont` attribute.
titleside
Deprecated: Please use
layout.coloraxis.colorbar.title.side instead.
Determines the location of color bar's title
with respect to the color bar. Defaults to
"top" when `orientation` if "v" and defaults
to "right" when `orientation` if "h". Note that
the title's location used to be set by the now
deprecated `titleside` attribute.
x
Sets the x position with respect to `xref` of
the color bar (in plot fraction). When `xref`
is "paper", defaults to 1.02 when `orientation`
is "v" and 0.5 when `orientation` is "h". When
`xref` is "container", defaults to 1 when
`orientation` is "v" and 0.5 when `orientation`
is "h". Must be between 0 and 1 if `xref` is
"container" and between "-2" and 3 if `xref` is
"paper".
xanchor
Sets this color bar's horizontal position
anchor. This anchor binds the `x` position to
the "left", "center" or "right" of the color
bar. Defaults to "left" when `orientation` is
"v" and "center" when `orientation` is "h".
xpad
Sets the amount of padding (in px) along the x
direction.
xref
Sets the container `x` refers to. "container"
spans the entire `width` of the plot. "paper"
refers to the width of the plotting area only.
y
Sets the y position with respect to `yref` of
the color bar (in plot fraction). When `yref`
is "paper", defaults to 0.5 when `orientation`
is "v" and 1.02 when `orientation` is "h". When
`yref` is "container", defaults to 0.5 when
`orientation` is "v" and 1 when `orientation`
is "h". Must be between 0 and 1 if `yref` is
"container" and between "-2" and 3 if `yref` is
"paper".
yanchor
Sets this color bar's vertical position anchor
This anchor binds the `y` position to the
"top", "middle" or "bottom" of the color bar.
Defaults to "middle" when `orientation` is "v"
and "bottom" when `orientation` is "h".
ypad
Sets the amount of padding (in px) along the y
direction.
yref
Sets the container `y` refers to. "container"
spans the entire `height` of the plot. "paper"
refers to the height of the plotting area only.
Returns
-------
plotly.graph_objs.layout.coloraxis.ColorBar
"""
| /usr/src/app/target_test_cases/failed_tests__coloraxis.colorbar.txt | def colorbar(self):
"""
The 'colorbar' property is an instance of ColorBar
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.coloraxis.ColorBar`
- A dict of string/value properties that will be passed
to the ColorBar constructor
Supported dict properties:
bgcolor
Sets the color of padded area.
bordercolor
Sets the axis line color.
borderwidth
Sets the width (in px) or the border enclosing
this color bar.
dtick
Sets the step in-between ticks on this axis.
Use with `tick0`. Must be a positive number, or
special strings available to "log" and "date"
axes. If the axis `type` is "log", then ticks
are set every 10^(n*dtick) where n is the tick
number. For example, to set a tick mark at 1,
10, 100, 1000, ... set dtick to 1. To set tick
marks at 1, 100, 10000, ... set dtick to 2. To
set tick marks at 1, 5, 25, 125, 625, 3125, ...
set dtick to log_10(5), or 0.69897000433. "log"
has several special values; "L<f>", where `f`
is a positive number, gives ticks linearly
spaced in value (but not position). For example
`tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10
plus small digits between, use "D1" (all
digits) or "D2" (only 2 and 5). `tick0` is
ignored for "D1" and "D2". If the axis `type`
is "date", then you must convert the time to
milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to
86400000.0. "date" also has special values
"M<n>" gives ticks spaced by a number of
months. `n` must be a positive integer. To set
ticks on the 15th of every third month, set
`tick0` to "2000-01-15" and `dtick` to "M3". To
set ticks every 4 years, set `dtick` to "M48"
exponentformat
Determines a formatting rule for the tick
exponents. For example, consider the number
1,000,000,000. If "none", it appears as
1,000,000,000. If "e", 1e+9. If "E", 1E+9. If
"power", 1x10^9 (with 9 in a super script). If
"SI", 1G. If "B", 1B.
labelalias
Replacement text for specific tick or hover
labels. For example using {US: 'USA', CA:
'Canada'} changes US to USA and CA to Canada.
The labels we would have shown must match the
keys exactly, after adding any tickprefix or
ticksuffix. For negative numbers the minus sign
symbol used (U+2212) is wider than the regular
ascii dash. That means you need to use −1
instead of -1. labelalias can be used with any
axis type, and both keys (if needed) and values
(if desired) can include html-like tags or
MathJax.
len
Sets the length of the color bar This measure
excludes the padding of both ends. That is, the
color bar length is this length minus the
padding on both ends.
lenmode
Determines whether this color bar's length
(i.e. the measure in the color variation
direction) is set in units of plot "fraction"
or in *pixels. Use `len` to set the value.
minexponent
Hide SI prefix for 10^n if |n| is below this
number. This only has an effect when
`tickformat` is "SI" or "B".
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks
will be chosen automatically to be less than or
equal to `nticks`. Has an effect only if
`tickmode` is set to "auto".
orientation
Sets the orientation of the colorbar.
outlinecolor
Sets the axis line color.
outlinewidth
Sets the width (in px) of the axis line.
separatethousands
If "true", even 4-digit integers are separated
showexponent
If "all", all exponents are shown besides their
significands. If "first", only the exponent of
the first tick is shown. If "last", only the
exponent of the last tick is shown. If "none",
no exponents appear.
showticklabels
Determines whether or not the tick labels are
drawn.
showtickprefix
If "all", all tick labels are displayed with a
prefix. If "first", only the first tick is
displayed with a prefix. If "last", only the
last tick is displayed with a suffix. If
"none", tick prefixes are hidden.
showticksuffix
Same as `showtickprefix` but for tick suffixes.
thickness
Sets the thickness of the color bar This
measure excludes the size of the padding, ticks
and labels.
thicknessmode
Determines whether this color bar's thickness
(i.e. the measure in the constant color
direction) is set in units of plot "fraction"
or in "pixels". Use `thickness` to set the
value.
tick0
Sets the placement of the first tick on this
axis. Use with `dtick`. If the axis `type` is
"log", then you must take the log of your
starting tick (e.g. to set the starting tick to
100, set the `tick0` to 2) except when
`dtick`=*L<f>* (see `dtick` for more info). If
the axis `type` is "date", it should be a date
string, like date data. If the axis `type` is
"category", it should be a number, using the
scale where each category is assigned a serial
number from zero in the order it appears.
tickangle
Sets the angle of the tick labels with respect
to the horizontal. For example, a `tickangle`
of -90 draws the tick labels vertically.
tickcolor
Sets the tick color.
tickfont
Sets the color bar's tick label font
tickformat
Sets the tick label formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see: h
ttps://github.com/d3/d3-format/tree/v1.4.5#d3-
format. And for dates see:
https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two
items to d3's date formatter: "%h" for half of
the year as a decimal number as well as "%{n}f"
for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with
tickformat "%H~%M~%S.%2f" would display
"09~15~23.46"
tickformatstops
A tuple of :class:`plotly.graph_objects.layout.
coloraxis.colorbar.Tickformatstop` instances or
dicts with compatible properties
tickformatstopdefaults
When used in a template (as layout.template.lay
out.coloraxis.colorbar.tickformatstopdefaults),
sets the default property values to use for
elements of
layout.coloraxis.colorbar.tickformatstops
ticklabeloverflow
Determines how we handle tick labels that would
overflow either the graph div or the domain of
the axis. The default value for inside tick
labels is *hide past domain*. In other cases
the default is *hide past div*.
ticklabelposition
Determines where tick labels are drawn relative
to the ticks. Left and right options are used
when `orientation` is "h", top and bottom when
`orientation` is "v".
ticklabelstep
Sets the spacing between tick labels as
compared to the spacing between ticks. A value
of 1 (default) means each tick gets a label. A
value of 2 means shows every 2nd label. A
larger value n means only every nth tick is
labeled. `tick0` determines which labels are
shown. Not implemented for axes with `type`
"log" or "multicategory", or when `tickmode` is
"array".
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto",
the number of ticks is set via `nticks`. If
"linear", the placement of the ticks is
determined by a starting position `tick0` and a
tick step `dtick` ("linear" is the default
value if `tick0` and `dtick` are provided). If
"array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`.
("array" is the default value if `tickvals` is
provided).
tickprefix
Sets a tick label prefix.
ticks
Determines whether ticks are drawn or not. If
"", this axis' ticks are not drawn. If
"outside" ("inside"), this axis' are drawn
outside (inside) the axis lines.
ticksuffix
Sets a tick label suffix.
ticktext
Sets the text displayed at the ticks position
via `tickvals`. Only has an effect if
`tickmode` is set to "array". Used with
`tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud
for `ticktext`.
tickvals
Sets the values at which ticks on this axis
appear. Only has an effect if `tickmode` is set
to "array". Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud
for `tickvals`.
tickwidth
Sets the tick width (in px).
title
:class:`plotly.graph_objects.layout.coloraxis.c
olorbar.Title` instance or dict with compatible
properties
titlefont
Deprecated: Please use
layout.coloraxis.colorbar.title.font instead.
Sets this color bar's title font. Note that the
title's font used to be set by the now
deprecated `titlefont` attribute.
titleside
Deprecated: Please use
layout.coloraxis.colorbar.title.side instead.
Determines the location of color bar's title
with respect to the color bar. Defaults to
"top" when `orientation` if "v" and defaults
to "right" when `orientation` if "h". Note that
the title's location used to be set by the now
deprecated `titleside` attribute.
x
Sets the x position with respect to `xref` of
the color bar (in plot fraction). When `xref`
is "paper", defaults to 1.02 when `orientation`
is "v" and 0.5 when `orientation` is "h". When
`xref` is "container", defaults to 1 when
`orientation` is "v" and 0.5 when `orientation`
is "h". Must be between 0 and 1 if `xref` is
"container" and between "-2" and 3 if `xref` is
"paper".
xanchor
Sets this color bar's horizontal position
anchor. This anchor binds the `x` position to
the "left", "center" or "right" of the color
bar. Defaults to "left" when `orientation` is
"v" and "center" when `orientation` is "h".
xpad
Sets the amount of padding (in px) along the x
direction.
xref
Sets the container `x` refers to. "container"
spans the entire `width` of the plot. "paper"
refers to the width of the plotting area only.
y
Sets the y position with respect to `yref` of
the color bar (in plot fraction). When `yref`
is "paper", defaults to 0.5 when `orientation`
is "v" and 1.02 when `orientation` is "h". When
`yref` is "container", defaults to 0.5 when
`orientation` is "v" and 1 when `orientation`
is "h". Must be between 0 and 1 if `yref` is
"container" and between "-2" and 3 if `yref` is
"paper".
yanchor
Sets this color bar's vertical position anchor
This anchor binds the `y` position to the
"top", "middle" or "bottom" of the color bar.
Defaults to "middle" when `orientation` is "v"
and "bottom" when `orientation` is "h".
ypad
Sets the amount of padding (in px) along the y
direction.
yref
Sets the container `y` refers to. "container"
spans the entire `height` of the plot. "paper"
refers to the height of the plotting area only.
Returns
-------
plotly.graph_objs.layout.coloraxis.ColorBar
"""
return self["colorbar"]
| _coloraxis.colorbar |
plotly.py | 4 | packages/python/plotly/plotly/graph_objs/histogram2dcontour/_contours.py | def __init__(
self,
arg=None,
coloring=None,
end=None,
labelfont=None,
labelformat=None,
operation=None,
showlabels=None,
showlines=None,
size=None,
start=None,
type=None,
value=None,
**kwargs,
):
"""
Construct a new Contours object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.histogram2dcontour.Contours`
coloring
Determines the coloring method showing the contour
values. If "fill", coloring is done evenly between each
contour level If "heatmap", a heatmap gradient coloring
is applied between each contour level. If "lines",
coloring is done on the contour lines. If "none", no
coloring is applied on this trace.
end
Sets the end contour level value. Must be more than
`contours.start`
labelfont
Sets the font used for labeling the contour levels. The
default color comes from the lines, if shown. The
default family and size come from `layout.font`.
labelformat
Sets the contour label formatting rule using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
operation
Sets the constraint operation. "=" keeps regions equal
to `value` "<" and "<=" keep regions less than `value`
">" and ">=" keep regions greater than `value` "[]",
"()", "[)", and "(]" keep regions inside `value[0]` to
`value[1]` "][", ")(", "](", ")[" keep regions outside
`value[0]` to value[1]` Open vs. closed intervals make
no difference to constraint display, but all versions
are allowed for consistency with filter transforms.
showlabels
Determines whether to label the contour lines with
their values.
showlines
Determines whether or not the contour lines are drawn.
Has an effect only if `contours.coloring` is set to
"fill".
size
Sets the step between each contour level. Must be
positive.
start
Sets the starting contour level value. Must be less
than `contours.end`
type
If `levels`, the data is represented as a contour plot
with multiple levels displayed. If `constraint`, the
data is represented as constraints with the invalid
region shaded as specified by the `operation` and
`value` parameters.
value
Sets the value or values of the constraint boundary.
When `operation` is set to one of the comparison values
(=,<,>=,>,<=) "value" is expected to be a number. When
`operation` is set to one of the interval values
([],(),[),(],][,)(,](,)[) "value" is expected to be an
array of two numbers where the first is the lower bound
and the second is the upper bound.
Returns
-------
Contours
"""
| /usr/src/app/target_test_cases/failed_tests__contours.Contours.__init__.txt | def __init__(
self,
arg=None,
coloring=None,
end=None,
labelfont=None,
labelformat=None,
operation=None,
showlabels=None,
showlines=None,
size=None,
start=None,
type=None,
value=None,
**kwargs,
):
"""
Construct a new Contours object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.histogram2dcontour.Contours`
coloring
Determines the coloring method showing the contour
values. If "fill", coloring is done evenly between each
contour level If "heatmap", a heatmap gradient coloring
is applied between each contour level. If "lines",
coloring is done on the contour lines. If "none", no
coloring is applied on this trace.
end
Sets the end contour level value. Must be more than
`contours.start`
labelfont
Sets the font used for labeling the contour levels. The
default color comes from the lines, if shown. The
default family and size come from `layout.font`.
labelformat
Sets the contour label formatting rule using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
operation
Sets the constraint operation. "=" keeps regions equal
to `value` "<" and "<=" keep regions less than `value`
">" and ">=" keep regions greater than `value` "[]",
"()", "[)", and "(]" keep regions inside `value[0]` to
`value[1]` "][", ")(", "](", ")[" keep regions outside
`value[0]` to value[1]` Open vs. closed intervals make
no difference to constraint display, but all versions
are allowed for consistency with filter transforms.
showlabels
Determines whether to label the contour lines with
their values.
showlines
Determines whether or not the contour lines are drawn.
Has an effect only if `contours.coloring` is set to
"fill".
size
Sets the step between each contour level. Must be
positive.
start
Sets the starting contour level value. Must be less
than `contours.end`
type
If `levels`, the data is represented as a contour plot
with multiple levels displayed. If `constraint`, the
data is represented as constraints with the invalid
region shaded as specified by the `operation` and
`value` parameters.
value
Sets the value or values of the constraint boundary.
When `operation` is set to one of the comparison values
(=,<,>=,>,<=) "value" is expected to be a number. When
`operation` is set to one of the interval values
([],(),[),(],][,)(,](,)[) "value" is expected to be an
array of two numbers where the first is the lower bound
and the second is the upper bound.
Returns
-------
Contours
"""
super(Contours, self).__init__("contours")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.histogram2dcontour.Contours
constructor must be a dict or
an instance of :class:`plotly.graph_objs.histogram2dcontour.Contours`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("coloring", None)
_v = coloring if coloring is not None else _v
if _v is not None:
self["coloring"] = _v
_v = arg.pop("end", None)
_v = end if end is not None else _v
if _v is not None:
self["end"] = _v
_v = arg.pop("labelfont", None)
_v = labelfont if labelfont is not None else _v
if _v is not None:
self["labelfont"] = _v
_v = arg.pop("labelformat", None)
_v = labelformat if labelformat is not None else _v
if _v is not None:
self["labelformat"] = _v
_v = arg.pop("operation", None)
_v = operation if operation is not None else _v
if _v is not None:
self["operation"] = _v
_v = arg.pop("showlabels", None)
_v = showlabels if showlabels is not None else _v
if _v is not None:
self["showlabels"] = _v
_v = arg.pop("showlines", None)
_v = showlines if showlines is not None else _v
if _v is not None:
self["showlines"] = _v
_v = arg.pop("size", None)
_v = size if size is not None else _v
if _v is not None:
self["size"] = _v
_v = arg.pop("start", None)
_v = start if start is not None else _v
if _v is not None:
self["start"] = _v
_v = arg.pop("type", None)
_v = type if type is not None else _v
if _v is not None:
self["type"] = _v
_v = arg.pop("value", None)
_v = value if value is not None else _v
if _v is not None:
self["value"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| _contours.Contours.__init__ |
plotly.py | 5 | packages/python/plotly/plotly/figure_factory/_county_choropleth.py | def create_choropleth(
fips,
values,
scope=["usa"],
binning_endpoints=None,
colorscale=None,
order=None,
simplify_county=0.02,
simplify_state=0.02,
asp=None,
show_hover=True,
show_state_data=True,
state_outline=None,
county_outline=None,
centroid_marker=None,
round_legend_values=False,
exponent_format=False,
legend_title="",
**layout_options,
):
"""
**deprecated**, use instead
:func:`plotly.express.choropleth` with custom GeoJSON.
This function also requires `shapely`, `geopandas` and `plotly-geo` to be installed.
Returns figure for county choropleth. Uses data from package_data.
:param (list) fips: list of FIPS values which correspond to the con
catination of state and county ids. An example is '01001'.
:param (list) values: list of numbers/strings which correspond to the
fips list. These are the values that will determine how the counties
are colored.
:param (list) scope: list of states and/or states abbreviations. Fits
all states in the camera tightly. Selecting ['usa'] is the equivalent
of appending all 50 states into your scope list. Selecting only 'usa'
does not include 'Alaska', 'Puerto Rico', 'American Samoa',
'Commonwealth of the Northern Mariana Islands', 'Guam',
'United States Virgin Islands'. These must be added manually to the
list.
Default = ['usa']
:param (list) binning_endpoints: ascending numbers which implicitly define
real number intervals which are used as bins. The colorscale used must
have the same number of colors as the number of bins and this will
result in a categorical colormap.
:param (list) colorscale: a list of colors with length equal to the
number of categories of colors. The length must match either all
unique numbers in the 'values' list or if endpoints is being used, the
number of categories created by the endpoints.\n
For example, if binning_endpoints = [4, 6, 8], then there are 4 bins:
[-inf, 4), [4, 6), [6, 8), [8, inf)
:param (list) order: a list of the unique categories (numbers/bins) in any
desired order. This is helpful if you want to order string values to
a chosen colorscale.
:param (float) simplify_county: determines the simplification factor
for the counties. The larger the number, the fewer vertices and edges
each polygon has. See
http://toblerity.org/shapely/manual.html#object.simplify for more
information.
Default = 0.02
:param (float) simplify_state: simplifies the state outline polygon.
See http://toblerity.org/shapely/manual.html#object.simplify for more
information.
Default = 0.02
:param (float) asp: the width-to-height aspect ratio for the camera.
Default = 2.5
:param (bool) show_hover: show county hover and centroid info
:param (bool) show_state_data: reveals state boundary lines
:param (dict) state_outline: dict of attributes of the state outline
including width and color. See
https://plot.ly/python/reference/#scatter-marker-line for all valid
params
:param (dict) county_outline: dict of attributes of the county outline
including width and color. See
https://plot.ly/python/reference/#scatter-marker-line for all valid
params
:param (dict) centroid_marker: dict of attributes of the centroid marker.
The centroid markers are invisible by default and appear visible on
selection. See https://plot.ly/python/reference/#scatter-marker for
all valid params
:param (bool) round_legend_values: automatically round the numbers that
appear in the legend to the nearest integer.
Default = False
:param (bool) exponent_format: if set to True, puts numbers in the K, M,
B number format. For example 4000.0 becomes 4.0K
Default = False
:param (str) legend_title: title that appears above the legend
:param **layout_options: a **kwargs argument for all layout parameters
Example 1: Florida::
import plotly.plotly as py
import plotly.figure_factory as ff
import numpy as np
import pandas as pd
df_sample = pd.read_csv(
'https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv'
)
df_sample_r = df_sample[df_sample['STNAME'] == 'Florida']
values = df_sample_r['TOT_POP'].tolist()
fips = df_sample_r['FIPS'].tolist()
binning_endpoints = list(np.mgrid[min(values):max(values):4j])
colorscale = ["#030512","#1d1d3b","#323268","#3d4b94","#3e6ab0",
"#4989bc","#60a7c7","#85c5d3","#b7e0e4","#eafcfd"]
fig = ff.create_choropleth(
fips=fips, values=values, scope=['Florida'], show_state_data=True,
colorscale=colorscale, binning_endpoints=binning_endpoints,
round_legend_values=True, plot_bgcolor='rgb(229,229,229)',
paper_bgcolor='rgb(229,229,229)', legend_title='Florida Population',
county_outline={'color': 'rgb(255,255,255)', 'width': 0.5},
exponent_format=True,
)
Example 2: New England::
import plotly.figure_factory as ff
import pandas as pd
NE_states = ['Connecticut', 'Maine', 'Massachusetts',
'New Hampshire', 'Rhode Island']
df_sample = pd.read_csv(
'https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv'
)
df_sample_r = df_sample[df_sample['STNAME'].isin(NE_states)]
colorscale = ['rgb(68.0, 1.0, 84.0)',
'rgb(66.0, 64.0, 134.0)',
'rgb(38.0, 130.0, 142.0)',
'rgb(63.0, 188.0, 115.0)',
'rgb(216.0, 226.0, 25.0)']
values = df_sample_r['TOT_POP'].tolist()
fips = df_sample_r['FIPS'].tolist()
fig = ff.create_choropleth(
fips=fips, values=values, scope=NE_states, show_state_data=True
)
fig.show()
Example 3: California and Surrounding States::
import plotly.figure_factory as ff
import pandas as pd
df_sample = pd.read_csv(
'https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv'
)
df_sample_r = df_sample[df_sample['STNAME'] == 'California']
values = df_sample_r['TOT_POP'].tolist()
fips = df_sample_r['FIPS'].tolist()
colorscale = [
'rgb(193, 193, 193)',
'rgb(239,239,239)',
'rgb(195, 196, 222)',
'rgb(144,148,194)',
'rgb(101,104,168)',
'rgb(65, 53, 132)'
]
fig = ff.create_choropleth(
fips=fips, values=values, colorscale=colorscale,
scope=['CA', 'AZ', 'Nevada', 'Oregon', ' Idaho'],
binning_endpoints=[14348, 63983, 134827, 426762, 2081313],
county_outline={'color': 'rgb(255,255,255)', 'width': 0.5},
legend_title='California Counties',
title='California and Nearby States'
)
fig.show()
Example 4: USA::
import plotly.figure_factory as ff
import numpy as np
import pandas as pd
df_sample = pd.read_csv(
'https://raw.githubusercontent.com/plotly/datasets/master/laucnty16.csv'
)
df_sample['State FIPS Code'] = df_sample['State FIPS Code'].apply(
lambda x: str(x).zfill(2)
)
df_sample['County FIPS Code'] = df_sample['County FIPS Code'].apply(
lambda x: str(x).zfill(3)
)
df_sample['FIPS'] = (
df_sample['State FIPS Code'] + df_sample['County FIPS Code']
)
binning_endpoints = list(np.linspace(1, 12, len(colorscale) - 1))
colorscale = ["#f7fbff", "#ebf3fb", "#deebf7", "#d2e3f3", "#c6dbef",
"#b3d2e9", "#9ecae1", "#85bcdb", "#6baed6", "#57a0ce",
"#4292c6", "#3082be", "#2171b5", "#1361a9", "#08519c",
"#0b4083","#08306b"]
fips = df_sample['FIPS']
values = df_sample['Unemployment Rate (%)']
fig = ff.create_choropleth(
fips=fips, values=values, scope=['usa'],
binning_endpoints=binning_endpoints, colorscale=colorscale,
show_hover=True, centroid_marker={'opacity': 0},
asp=2.9, title='USA by Unemployment %',
legend_title='Unemployment %'
)
fig.show()
"""
| /usr/src/app/target_test_cases/failed_tests__county_choropleth.create_choropleth.txt | def create_choropleth(
fips,
values,
scope=["usa"],
binning_endpoints=None,
colorscale=None,
order=None,
simplify_county=0.02,
simplify_state=0.02,
asp=None,
show_hover=True,
show_state_data=True,
state_outline=None,
county_outline=None,
centroid_marker=None,
round_legend_values=False,
exponent_format=False,
legend_title="",
**layout_options,
):
"""
**deprecated**, use instead
:func:`plotly.express.choropleth` with custom GeoJSON.
This function also requires `shapely`, `geopandas` and `plotly-geo` to be installed.
Returns figure for county choropleth. Uses data from package_data.
:param (list) fips: list of FIPS values which correspond to the con
catination of state and county ids. An example is '01001'.
:param (list) values: list of numbers/strings which correspond to the
fips list. These are the values that will determine how the counties
are colored.
:param (list) scope: list of states and/or states abbreviations. Fits
all states in the camera tightly. Selecting ['usa'] is the equivalent
of appending all 50 states into your scope list. Selecting only 'usa'
does not include 'Alaska', 'Puerto Rico', 'American Samoa',
'Commonwealth of the Northern Mariana Islands', 'Guam',
'United States Virgin Islands'. These must be added manually to the
list.
Default = ['usa']
:param (list) binning_endpoints: ascending numbers which implicitly define
real number intervals which are used as bins. The colorscale used must
have the same number of colors as the number of bins and this will
result in a categorical colormap.
:param (list) colorscale: a list of colors with length equal to the
number of categories of colors. The length must match either all
unique numbers in the 'values' list or if endpoints is being used, the
number of categories created by the endpoints.\n
For example, if binning_endpoints = [4, 6, 8], then there are 4 bins:
[-inf, 4), [4, 6), [6, 8), [8, inf)
:param (list) order: a list of the unique categories (numbers/bins) in any
desired order. This is helpful if you want to order string values to
a chosen colorscale.
:param (float) simplify_county: determines the simplification factor
for the counties. The larger the number, the fewer vertices and edges
each polygon has. See
http://toblerity.org/shapely/manual.html#object.simplify for more
information.
Default = 0.02
:param (float) simplify_state: simplifies the state outline polygon.
See http://toblerity.org/shapely/manual.html#object.simplify for more
information.
Default = 0.02
:param (float) asp: the width-to-height aspect ratio for the camera.
Default = 2.5
:param (bool) show_hover: show county hover and centroid info
:param (bool) show_state_data: reveals state boundary lines
:param (dict) state_outline: dict of attributes of the state outline
including width and color. See
https://plot.ly/python/reference/#scatter-marker-line for all valid
params
:param (dict) county_outline: dict of attributes of the county outline
including width and color. See
https://plot.ly/python/reference/#scatter-marker-line for all valid
params
:param (dict) centroid_marker: dict of attributes of the centroid marker.
The centroid markers are invisible by default and appear visible on
selection. See https://plot.ly/python/reference/#scatter-marker for
all valid params
:param (bool) round_legend_values: automatically round the numbers that
appear in the legend to the nearest integer.
Default = False
:param (bool) exponent_format: if set to True, puts numbers in the K, M,
B number format. For example 4000.0 becomes 4.0K
Default = False
:param (str) legend_title: title that appears above the legend
:param **layout_options: a **kwargs argument for all layout parameters
Example 1: Florida::
import plotly.plotly as py
import plotly.figure_factory as ff
import numpy as np
import pandas as pd
df_sample = pd.read_csv(
'https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv'
)
df_sample_r = df_sample[df_sample['STNAME'] == 'Florida']
values = df_sample_r['TOT_POP'].tolist()
fips = df_sample_r['FIPS'].tolist()
binning_endpoints = list(np.mgrid[min(values):max(values):4j])
colorscale = ["#030512","#1d1d3b","#323268","#3d4b94","#3e6ab0",
"#4989bc","#60a7c7","#85c5d3","#b7e0e4","#eafcfd"]
fig = ff.create_choropleth(
fips=fips, values=values, scope=['Florida'], show_state_data=True,
colorscale=colorscale, binning_endpoints=binning_endpoints,
round_legend_values=True, plot_bgcolor='rgb(229,229,229)',
paper_bgcolor='rgb(229,229,229)', legend_title='Florida Population',
county_outline={'color': 'rgb(255,255,255)', 'width': 0.5},
exponent_format=True,
)
Example 2: New England::
import plotly.figure_factory as ff
import pandas as pd
NE_states = ['Connecticut', 'Maine', 'Massachusetts',
'New Hampshire', 'Rhode Island']
df_sample = pd.read_csv(
'https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv'
)
df_sample_r = df_sample[df_sample['STNAME'].isin(NE_states)]
colorscale = ['rgb(68.0, 1.0, 84.0)',
'rgb(66.0, 64.0, 134.0)',
'rgb(38.0, 130.0, 142.0)',
'rgb(63.0, 188.0, 115.0)',
'rgb(216.0, 226.0, 25.0)']
values = df_sample_r['TOT_POP'].tolist()
fips = df_sample_r['FIPS'].tolist()
fig = ff.create_choropleth(
fips=fips, values=values, scope=NE_states, show_state_data=True
)
fig.show()
Example 3: California and Surrounding States::
import plotly.figure_factory as ff
import pandas as pd
df_sample = pd.read_csv(
'https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv'
)
df_sample_r = df_sample[df_sample['STNAME'] == 'California']
values = df_sample_r['TOT_POP'].tolist()
fips = df_sample_r['FIPS'].tolist()
colorscale = [
'rgb(193, 193, 193)',
'rgb(239,239,239)',
'rgb(195, 196, 222)',
'rgb(144,148,194)',
'rgb(101,104,168)',
'rgb(65, 53, 132)'
]
fig = ff.create_choropleth(
fips=fips, values=values, colorscale=colorscale,
scope=['CA', 'AZ', 'Nevada', 'Oregon', ' Idaho'],
binning_endpoints=[14348, 63983, 134827, 426762, 2081313],
county_outline={'color': 'rgb(255,255,255)', 'width': 0.5},
legend_title='California Counties',
title='California and Nearby States'
)
fig.show()
Example 4: USA::
import plotly.figure_factory as ff
import numpy as np
import pandas as pd
df_sample = pd.read_csv(
'https://raw.githubusercontent.com/plotly/datasets/master/laucnty16.csv'
)
df_sample['State FIPS Code'] = df_sample['State FIPS Code'].apply(
lambda x: str(x).zfill(2)
)
df_sample['County FIPS Code'] = df_sample['County FIPS Code'].apply(
lambda x: str(x).zfill(3)
)
df_sample['FIPS'] = (
df_sample['State FIPS Code'] + df_sample['County FIPS Code']
)
binning_endpoints = list(np.linspace(1, 12, len(colorscale) - 1))
colorscale = ["#f7fbff", "#ebf3fb", "#deebf7", "#d2e3f3", "#c6dbef",
"#b3d2e9", "#9ecae1", "#85bcdb", "#6baed6", "#57a0ce",
"#4292c6", "#3082be", "#2171b5", "#1361a9", "#08519c",
"#0b4083","#08306b"]
fips = df_sample['FIPS']
values = df_sample['Unemployment Rate (%)']
fig = ff.create_choropleth(
fips=fips, values=values, scope=['usa'],
binning_endpoints=binning_endpoints, colorscale=colorscale,
show_hover=True, centroid_marker={'opacity': 0},
asp=2.9, title='USA by Unemployment %',
legend_title='Unemployment %'
)
fig.show()
"""
# ensure optional modules imported
if not _plotly_geo:
raise ValueError(
"""
The create_choropleth figure factory requires the plotly-geo package.
Install using pip with:
$ pip install plotly-geo
Or, install using conda with
$ conda install -c plotly plotly-geo
"""
)
if not gp or not shapefile or not shapely:
raise ImportError(
"geopandas, pyshp and shapely must be installed for this figure "
"factory.\n\nRun the following commands to install the correct "
"versions of the following modules:\n\n"
"```\n"
"$ pip install geopandas==0.3.0\n"
"$ pip install pyshp==1.2.10\n"
"$ pip install shapely==1.6.3\n"
"```\n"
"If you are using Windows, follow this post to properly "
"install geopandas and dependencies:"
"http://geoffboeing.com/2014/09/using-geopandas-windows/\n\n"
"If you are using Anaconda, do not use PIP to install the "
"packages above. Instead use conda to install them:\n\n"
"```\n"
"$ conda install plotly\n"
"$ conda install geopandas\n"
"```"
)
df, df_state = _create_us_counties_df(st_to_state_name_dict, state_to_st_dict)
fips_polygon_map = dict(zip(df["FIPS"].tolist(), df["geometry"].tolist()))
if not state_outline:
state_outline = {"color": "rgb(240, 240, 240)", "width": 1}
if not county_outline:
county_outline = {"color": "rgb(0, 0, 0)", "width": 0}
if not centroid_marker:
centroid_marker = {"size": 3, "color": "white", "opacity": 1}
# ensure centroid markers appear on selection
if "opacity" not in centroid_marker:
centroid_marker.update({"opacity": 1})
if len(fips) != len(values):
raise PlotlyError("fips and values must be the same length")
# make fips, values into lists
if isinstance(fips, pd.core.series.Series):
fips = fips.tolist()
if isinstance(values, pd.core.series.Series):
values = values.tolist()
# make fips numeric
fips = map(lambda x: int(x), fips)
if binning_endpoints:
intervals = utils.endpts_to_intervals(binning_endpoints)
LEVELS = _intervals_as_labels(intervals, round_legend_values, exponent_format)
else:
if not order:
LEVELS = sorted(list(set(values)))
else:
# check if order is permutation
# of unique color col values
same_sets = sorted(list(set(values))) == set(order)
no_duplicates = not any(order.count(x) > 1 for x in order)
if same_sets and no_duplicates:
LEVELS = order
else:
raise PlotlyError(
"if you are using a custom order of unique values from "
"your color column, you must: have all the unique values "
"in your order and have no duplicate items"
)
if not colorscale:
colorscale = []
viridis_colors = clrs.colorscale_to_colors(clrs.PLOTLY_SCALES["Viridis"])
viridis_colors = clrs.color_parser(viridis_colors, clrs.hex_to_rgb)
viridis_colors = clrs.color_parser(viridis_colors, clrs.label_rgb)
viri_len = len(viridis_colors) + 1
viri_intervals = utils.endpts_to_intervals(list(np.linspace(0, 1, viri_len)))[
1:-1
]
for L in np.linspace(0, 1, len(LEVELS)):
for idx, inter in enumerate(viri_intervals):
if L == 0:
break
elif inter[0] < L <= inter[1]:
break
intermed = (L - viri_intervals[idx][0]) / (
viri_intervals[idx][1] - viri_intervals[idx][0]
)
float_color = clrs.find_intermediate_color(
viridis_colors[idx], viridis_colors[idx], intermed, colortype="rgb"
)
# make R,G,B into int values
float_color = clrs.unlabel_rgb(float_color)
float_color = clrs.unconvert_from_RGB_255(float_color)
int_rgb = clrs.convert_to_RGB_255(float_color)
int_rgb = clrs.label_rgb(int_rgb)
colorscale.append(int_rgb)
if len(colorscale) < len(LEVELS):
raise PlotlyError(
"You have {} LEVELS. Your number of colors in 'colorscale' must "
"be at least the number of LEVELS: {}. If you are "
"using 'binning_endpoints' then 'colorscale' must have at "
"least len(binning_endpoints) + 2 colors".format(
len(LEVELS), min(LEVELS, LEVELS[:20])
)
)
color_lookup = dict(zip(LEVELS, colorscale))
x_traces = dict(zip(LEVELS, [[] for i in range(len(LEVELS))]))
y_traces = dict(zip(LEVELS, [[] for i in range(len(LEVELS))]))
# scope
if isinstance(scope, str):
raise PlotlyError("'scope' must be a list/tuple/sequence")
scope_names = []
extra_states = [
"Alaska",
"Commonwealth of the Northern Mariana Islands",
"Puerto Rico",
"Guam",
"United States Virgin Islands",
"American Samoa",
]
for state in scope:
if state.lower() == "usa":
scope_names = df["STATE_NAME"].unique()
scope_names = list(scope_names)
for ex_st in extra_states:
try:
scope_names.remove(ex_st)
except ValueError:
pass
else:
if state in st_to_state_name_dict.keys():
state = st_to_state_name_dict[state]
scope_names.append(state)
df_state = df_state[df_state["STATE_NAME"].isin(scope_names)]
plot_data = []
x_centroids = []
y_centroids = []
centroid_text = []
fips_not_in_shapefile = []
if not binning_endpoints:
for index, f in enumerate(fips):
level = values[index]
try:
fips_polygon_map[f].type
(
x_traces,
y_traces,
x_centroids,
y_centroids,
centroid_text,
) = _calculations(
df,
fips,
values,
index,
f,
simplify_county,
level,
x_centroids,
y_centroids,
centroid_text,
x_traces,
y_traces,
fips_polygon_map,
)
except KeyError:
fips_not_in_shapefile.append(f)
else:
for index, f in enumerate(fips):
for j, inter in enumerate(intervals):
if inter[0] < values[index] <= inter[1]:
break
level = LEVELS[j]
try:
fips_polygon_map[f].type
(
x_traces,
y_traces,
x_centroids,
y_centroids,
centroid_text,
) = _calculations(
df,
fips,
values,
index,
f,
simplify_county,
level,
x_centroids,
y_centroids,
centroid_text,
x_traces,
y_traces,
fips_polygon_map,
)
except KeyError:
fips_not_in_shapefile.append(f)
if len(fips_not_in_shapefile) > 0:
msg = (
"Unrecognized FIPS Values\n\nWhoops! It looks like you are "
"trying to pass at least one FIPS value that is not in "
"our shapefile of FIPS and data for the counties. Your "
"choropleth will still show up but these counties cannot "
"be shown.\nUnrecognized FIPS are: {}".format(fips_not_in_shapefile)
)
warnings.warn(msg)
x_states = []
y_states = []
for index, row in df_state.iterrows():
if df_state["geometry"][index].type == "Polygon":
x = row.geometry.simplify(simplify_state).exterior.xy[0].tolist()
y = row.geometry.simplify(simplify_state).exterior.xy[1].tolist()
x_states = x_states + x
y_states = y_states + y
elif df_state["geometry"][index].type == "MultiPolygon":
x = [
poly.simplify(simplify_state).exterior.xy[0].tolist()
for poly in df_state["geometry"][index].geoms
]
y = [
poly.simplify(simplify_state).exterior.xy[1].tolist()
for poly in df_state["geometry"][index].geoms
]
for segment in range(len(x)):
x_states = x_states + x[segment]
y_states = y_states + y[segment]
x_states.append(np.nan)
y_states.append(np.nan)
x_states.append(np.nan)
y_states.append(np.nan)
for lev in LEVELS:
county_data = dict(
type="scatter",
mode="lines",
x=x_traces[lev],
y=y_traces[lev],
line=county_outline,
fill="toself",
fillcolor=color_lookup[lev],
name=lev,
hoverinfo="none",
)
plot_data.append(county_data)
if show_hover:
hover_points = dict(
type="scatter",
showlegend=False,
legendgroup="centroids",
x=x_centroids,
y=y_centroids,
text=centroid_text,
name="US Counties",
mode="markers",
marker={"color": "white", "opacity": 0},
hoverinfo="text",
)
centroids_on_select = dict(
selected=dict(marker=centroid_marker),
unselected=dict(marker=dict(opacity=0)),
)
hover_points.update(centroids_on_select)
plot_data.append(hover_points)
if show_state_data:
state_data = dict(
type="scatter",
legendgroup="States",
line=state_outline,
x=x_states,
y=y_states,
hoverinfo="text",
showlegend=False,
mode="lines",
)
plot_data.append(state_data)
DEFAULT_LAYOUT = dict(
hovermode="closest",
xaxis=dict(
autorange=False,
range=USA_XRANGE,
showgrid=False,
zeroline=False,
fixedrange=True,
showticklabels=False,
),
yaxis=dict(
autorange=False,
range=USA_YRANGE,
showgrid=False,
zeroline=False,
fixedrange=True,
showticklabels=False,
),
margin=dict(t=40, b=20, r=20, l=20),
width=900,
height=450,
dragmode="select",
legend=dict(traceorder="reversed", xanchor="right", yanchor="top", x=1, y=1),
annotations=[],
)
fig = dict(data=plot_data, layout=DEFAULT_LAYOUT)
fig["layout"].update(layout_options)
fig["layout"]["annotations"].append(
dict(
x=1,
y=1.05,
xref="paper",
yref="paper",
xanchor="right",
showarrow=False,
text="<b>" + legend_title + "</b>",
)
)
if len(scope) == 1 and scope[0].lower() == "usa":
xaxis_range_low = -125.0
xaxis_range_high = -55.0
yaxis_range_low = 25.0
yaxis_range_high = 49.0
else:
xaxis_range_low = float("inf")
xaxis_range_high = float("-inf")
yaxis_range_low = float("inf")
yaxis_range_high = float("-inf")
for trace in fig["data"]:
if all(isinstance(n, Number) for n in trace["x"]):
calc_x_min = min(trace["x"] or [float("inf")])
calc_x_max = max(trace["x"] or [float("-inf")])
if calc_x_min < xaxis_range_low:
xaxis_range_low = calc_x_min
if calc_x_max > xaxis_range_high:
xaxis_range_high = calc_x_max
if all(isinstance(n, Number) for n in trace["y"]):
calc_y_min = min(trace["y"] or [float("inf")])
calc_y_max = max(trace["y"] or [float("-inf")])
if calc_y_min < yaxis_range_low:
yaxis_range_low = calc_y_min
if calc_y_max > yaxis_range_high:
yaxis_range_high = calc_y_max
# camera zoom
fig["layout"]["xaxis"]["range"] = [xaxis_range_low, xaxis_range_high]
fig["layout"]["yaxis"]["range"] = [yaxis_range_low, yaxis_range_high]
# aspect ratio
if asp is None:
usa_x_range = USA_XRANGE[1] - USA_XRANGE[0]
usa_y_range = USA_YRANGE[1] - USA_YRANGE[0]
asp = usa_x_range / usa_y_range
# based on your figure
width = float(
fig["layout"]["xaxis"]["range"][1] - fig["layout"]["xaxis"]["range"][0]
)
height = float(
fig["layout"]["yaxis"]["range"][1] - fig["layout"]["yaxis"]["range"][0]
)
center = (
sum(fig["layout"]["xaxis"]["range"]) / 2.0,
sum(fig["layout"]["yaxis"]["range"]) / 2.0,
)
if height / width > (1 / asp):
new_width = asp * height
fig["layout"]["xaxis"]["range"][0] = center[0] - new_width * 0.5
fig["layout"]["xaxis"]["range"][1] = center[0] + new_width * 0.5
else:
new_height = (1 / asp) * width
fig["layout"]["yaxis"]["range"][0] = center[1] - new_height * 0.5
fig["layout"]["yaxis"]["range"][1] = center[1] + new_height * 0.5
return go.Figure(fig)
| _county_choropleth.create_choropleth |
plotly.py | 6 | packages/python/plotly/plotly/graph_objs/parcoords/_dimension.py | def __init__(
self,
arg=None,
constraintrange=None,
label=None,
multiselect=None,
name=None,
range=None,
templateitemname=None,
tickformat=None,
ticktext=None,
ticktextsrc=None,
tickvals=None,
tickvalssrc=None,
values=None,
valuessrc=None,
visible=None,
**kwargs,
):
"""
Construct a new Dimension object
The dimensions (variables) of the parallel coordinates chart.
2..60 dimensions are supported.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.parcoords.Dimension`
constraintrange
The domain range to which the filter on the dimension
is constrained. Must be an array of `[fromValue,
toValue]` with `fromValue <= toValue`, or if
`multiselect` is not disabled, you may give an array of
arrays, where each inner array is `[fromValue,
toValue]`.
label
The shown name of the dimension.
multiselect
Do we allow multiple selection ranges or just a single
range?
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
range
The domain range that represents the full, shown axis
extent. Defaults to the `values` extent. Must be an
array of `[fromValue, toValue]` with finite numbers as
elements.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
tickformat
Sets the tick label formatting rule using d3 formatting
mini-languages which are very similar to those in
Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display "09~15~23.46"
ticktext
Sets the text displayed at the ticks position via
`tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud for
`ticktext`.
tickvals
Sets the values at which ticks on this axis appear.
tickvalssrc
Sets the source reference on Chart Studio Cloud for
`tickvals`.
values
Dimension values. `values[n]` represents the value of
the `n`th point in the dataset, therefore the `values`
vector for all dimensions must be the same (longer
vectors will be truncated). Each value must be a finite
number.
valuessrc
Sets the source reference on Chart Studio Cloud for
`values`.
visible
Shows the dimension when set to `true` (the default).
Hides the dimension for `false`.
Returns
-------
Dimension
"""
| /usr/src/app/target_test_cases/failed_tests__dimension.Dimension.__init__.txt | def __init__(
self,
arg=None,
constraintrange=None,
label=None,
multiselect=None,
name=None,
range=None,
templateitemname=None,
tickformat=None,
ticktext=None,
ticktextsrc=None,
tickvals=None,
tickvalssrc=None,
values=None,
valuessrc=None,
visible=None,
**kwargs,
):
"""
Construct a new Dimension object
The dimensions (variables) of the parallel coordinates chart.
2..60 dimensions are supported.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.parcoords.Dimension`
constraintrange
The domain range to which the filter on the dimension
is constrained. Must be an array of `[fromValue,
toValue]` with `fromValue <= toValue`, or if
`multiselect` is not disabled, you may give an array of
arrays, where each inner array is `[fromValue,
toValue]`.
label
The shown name of the dimension.
multiselect
Do we allow multiple selection ranges or just a single
range?
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
range
The domain range that represents the full, shown axis
extent. Defaults to the `values` extent. Must be an
array of `[fromValue, toValue]` with finite numbers as
elements.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
tickformat
Sets the tick label formatting rule using d3 formatting
mini-languages which are very similar to those in
Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display "09~15~23.46"
ticktext
Sets the text displayed at the ticks position via
`tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud for
`ticktext`.
tickvals
Sets the values at which ticks on this axis appear.
tickvalssrc
Sets the source reference on Chart Studio Cloud for
`tickvals`.
values
Dimension values. `values[n]` represents the value of
the `n`th point in the dataset, therefore the `values`
vector for all dimensions must be the same (longer
vectors will be truncated). Each value must be a finite
number.
valuessrc
Sets the source reference on Chart Studio Cloud for
`values`.
visible
Shows the dimension when set to `true` (the default).
Hides the dimension for `false`.
Returns
-------
Dimension
"""
super(Dimension, self).__init__("dimensions")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.parcoords.Dimension
constructor must be a dict or
an instance of :class:`plotly.graph_objs.parcoords.Dimension`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("constraintrange", None)
_v = constraintrange if constraintrange is not None else _v
if _v is not None:
self["constraintrange"] = _v
_v = arg.pop("label", None)
_v = label if label is not None else _v
if _v is not None:
self["label"] = _v
_v = arg.pop("multiselect", None)
_v = multiselect if multiselect is not None else _v
if _v is not None:
self["multiselect"] = _v
_v = arg.pop("name", None)
_v = name if name is not None else _v
if _v is not None:
self["name"] = _v
_v = arg.pop("range", None)
_v = range if range is not None else _v
if _v is not None:
self["range"] = _v
_v = arg.pop("templateitemname", None)
_v = templateitemname if templateitemname is not None else _v
if _v is not None:
self["templateitemname"] = _v
_v = arg.pop("tickformat", None)
_v = tickformat if tickformat is not None else _v
if _v is not None:
self["tickformat"] = _v
_v = arg.pop("ticktext", None)
_v = ticktext if ticktext is not None else _v
if _v is not None:
self["ticktext"] = _v
_v = arg.pop("ticktextsrc", None)
_v = ticktextsrc if ticktextsrc is not None else _v
if _v is not None:
self["ticktextsrc"] = _v
_v = arg.pop("tickvals", None)
_v = tickvals if tickvals is not None else _v
if _v is not None:
self["tickvals"] = _v
_v = arg.pop("tickvalssrc", None)
_v = tickvalssrc if tickvalssrc is not None else _v
if _v is not None:
self["tickvalssrc"] = _v
_v = arg.pop("values", None)
_v = values if values is not None else _v
if _v is not None:
self["values"] = _v
_v = arg.pop("valuessrc", None)
_v = valuessrc if valuessrc is not None else _v
if _v is not None:
self["valuessrc"] = _v
_v = arg.pop("visible", None)
_v = visible if visible is not None else _v
if _v is not None:
self["visible"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| _dimension.Dimension.__init__ |
plotly.py | 7 | packages/python/plotly/plotly/figure_factory/_distplot.py | def create_distplot(
hist_data,
group_labels,
bin_size=1.0,
curve_type="kde",
colors=None,
rug_text=None,
histnorm=DEFAULT_HISTNORM,
show_hist=True,
show_curve=True,
show_rug=True,
):
"""
Function that creates a distplot similar to seaborn.distplot;
**this function is deprecated**, use instead :mod:`plotly.express`
functions, for example
>>> import plotly.express as px
>>> tips = px.data.tips()
>>> fig = px.histogram(tips, x="total_bill", y="tip", color="sex", marginal="rug",
... hover_data=tips.columns)
>>> fig.show()
The distplot can be composed of all or any combination of the following
3 components: (1) histogram, (2) curve: (a) kernel density estimation
or (b) normal curve, and (3) rug plot. Additionally, multiple distplots
(from multiple datasets) can be created in the same plot.
:param (list[list]) hist_data: Use list of lists to plot multiple data
sets on the same plot.
:param (list[str]) group_labels: Names for each data set.
:param (list[float]|float) bin_size: Size of histogram bins.
Default = 1.
:param (str) curve_type: 'kde' or 'normal'. Default = 'kde'
:param (str) histnorm: 'probability density' or 'probability'
Default = 'probability density'
:param (bool) show_hist: Add histogram to distplot? Default = True
:param (bool) show_curve: Add curve to distplot? Default = True
:param (bool) show_rug: Add rug to distplot? Default = True
:param (list[str]) colors: Colors for traces.
:param (list[list]) rug_text: Hovertext values for rug_plot,
:return (dict): Representation of a distplot figure.
Example 1: Simple distplot of 1 data set
>>> from plotly.figure_factory import create_distplot
>>> hist_data = [[1.1, 1.1, 2.5, 3.0, 3.5,
... 3.5, 4.1, 4.4, 4.5, 4.5,
... 5.0, 5.0, 5.2, 5.5, 5.5,
... 5.5, 5.5, 5.5, 6.1, 7.0]]
>>> group_labels = ['distplot example']
>>> fig = create_distplot(hist_data, group_labels)
>>> fig.show()
Example 2: Two data sets and added rug text
>>> from plotly.figure_factory import create_distplot
>>> # Add histogram data
>>> hist1_x = [0.8, 1.2, 0.2, 0.6, 1.6,
... -0.9, -0.07, 1.95, 0.9, -0.2,
... -0.5, 0.3, 0.4, -0.37, 0.6]
>>> hist2_x = [0.8, 1.5, 1.5, 0.6, 0.59,
... 1.0, 0.8, 1.7, 0.5, 0.8,
... -0.3, 1.2, 0.56, 0.3, 2.2]
>>> # Group data together
>>> hist_data = [hist1_x, hist2_x]
>>> group_labels = ['2012', '2013']
>>> # Add text
>>> rug_text_1 = ['a1', 'b1', 'c1', 'd1', 'e1',
... 'f1', 'g1', 'h1', 'i1', 'j1',
... 'k1', 'l1', 'm1', 'n1', 'o1']
>>> rug_text_2 = ['a2', 'b2', 'c2', 'd2', 'e2',
... 'f2', 'g2', 'h2', 'i2', 'j2',
... 'k2', 'l2', 'm2', 'n2', 'o2']
>>> # Group text together
>>> rug_text_all = [rug_text_1, rug_text_2]
>>> # Create distplot
>>> fig = create_distplot(
... hist_data, group_labels, rug_text=rug_text_all, bin_size=.2)
>>> # Add title
>>> fig.update_layout(title='Dist Plot') # doctest: +SKIP
>>> fig.show()
Example 3: Plot with normal curve and hide rug plot
>>> from plotly.figure_factory import create_distplot
>>> import numpy as np
>>> x1 = np.random.randn(190)
>>> x2 = np.random.randn(200)+1
>>> x3 = np.random.randn(200)-1
>>> x4 = np.random.randn(210)+2
>>> hist_data = [x1, x2, x3, x4]
>>> group_labels = ['2012', '2013', '2014', '2015']
>>> fig = create_distplot(
... hist_data, group_labels, curve_type='normal',
... show_rug=False, bin_size=.4)
Example 4: Distplot with Pandas
>>> from plotly.figure_factory import create_distplot
>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame({'2012': np.random.randn(200),
... '2013': np.random.randn(200)+1})
>>> fig = create_distplot([df[c] for c in df.columns], df.columns)
>>> fig.show()
"""
| /usr/src/app/target_test_cases/failed_tests__distplot.create_distplot.txt | def create_distplot(
hist_data,
group_labels,
bin_size=1.0,
curve_type="kde",
colors=None,
rug_text=None,
histnorm=DEFAULT_HISTNORM,
show_hist=True,
show_curve=True,
show_rug=True,
):
"""
Function that creates a distplot similar to seaborn.distplot;
**this function is deprecated**, use instead :mod:`plotly.express`
functions, for example
>>> import plotly.express as px
>>> tips = px.data.tips()
>>> fig = px.histogram(tips, x="total_bill", y="tip", color="sex", marginal="rug",
... hover_data=tips.columns)
>>> fig.show()
The distplot can be composed of all or any combination of the following
3 components: (1) histogram, (2) curve: (a) kernel density estimation
or (b) normal curve, and (3) rug plot. Additionally, multiple distplots
(from multiple datasets) can be created in the same plot.
:param (list[list]) hist_data: Use list of lists to plot multiple data
sets on the same plot.
:param (list[str]) group_labels: Names for each data set.
:param (list[float]|float) bin_size: Size of histogram bins.
Default = 1.
:param (str) curve_type: 'kde' or 'normal'. Default = 'kde'
:param (str) histnorm: 'probability density' or 'probability'
Default = 'probability density'
:param (bool) show_hist: Add histogram to distplot? Default = True
:param (bool) show_curve: Add curve to distplot? Default = True
:param (bool) show_rug: Add rug to distplot? Default = True
:param (list[str]) colors: Colors for traces.
:param (list[list]) rug_text: Hovertext values for rug_plot,
:return (dict): Representation of a distplot figure.
Example 1: Simple distplot of 1 data set
>>> from plotly.figure_factory import create_distplot
>>> hist_data = [[1.1, 1.1, 2.5, 3.0, 3.5,
... 3.5, 4.1, 4.4, 4.5, 4.5,
... 5.0, 5.0, 5.2, 5.5, 5.5,
... 5.5, 5.5, 5.5, 6.1, 7.0]]
>>> group_labels = ['distplot example']
>>> fig = create_distplot(hist_data, group_labels)
>>> fig.show()
Example 2: Two data sets and added rug text
>>> from plotly.figure_factory import create_distplot
>>> # Add histogram data
>>> hist1_x = [0.8, 1.2, 0.2, 0.6, 1.6,
... -0.9, -0.07, 1.95, 0.9, -0.2,
... -0.5, 0.3, 0.4, -0.37, 0.6]
>>> hist2_x = [0.8, 1.5, 1.5, 0.6, 0.59,
... 1.0, 0.8, 1.7, 0.5, 0.8,
... -0.3, 1.2, 0.56, 0.3, 2.2]
>>> # Group data together
>>> hist_data = [hist1_x, hist2_x]
>>> group_labels = ['2012', '2013']
>>> # Add text
>>> rug_text_1 = ['a1', 'b1', 'c1', 'd1', 'e1',
... 'f1', 'g1', 'h1', 'i1', 'j1',
... 'k1', 'l1', 'm1', 'n1', 'o1']
>>> rug_text_2 = ['a2', 'b2', 'c2', 'd2', 'e2',
... 'f2', 'g2', 'h2', 'i2', 'j2',
... 'k2', 'l2', 'm2', 'n2', 'o2']
>>> # Group text together
>>> rug_text_all = [rug_text_1, rug_text_2]
>>> # Create distplot
>>> fig = create_distplot(
... hist_data, group_labels, rug_text=rug_text_all, bin_size=.2)
>>> # Add title
>>> fig.update_layout(title='Dist Plot') # doctest: +SKIP
>>> fig.show()
Example 3: Plot with normal curve and hide rug plot
>>> from plotly.figure_factory import create_distplot
>>> import numpy as np
>>> x1 = np.random.randn(190)
>>> x2 = np.random.randn(200)+1
>>> x3 = np.random.randn(200)-1
>>> x4 = np.random.randn(210)+2
>>> hist_data = [x1, x2, x3, x4]
>>> group_labels = ['2012', '2013', '2014', '2015']
>>> fig = create_distplot(
... hist_data, group_labels, curve_type='normal',
... show_rug=False, bin_size=.4)
Example 4: Distplot with Pandas
>>> from plotly.figure_factory import create_distplot
>>> import numpy as np
>>> import pandas as pd
>>> df = pd.DataFrame({'2012': np.random.randn(200),
... '2013': np.random.randn(200)+1})
>>> fig = create_distplot([df[c] for c in df.columns], df.columns)
>>> fig.show()
"""
if colors is None:
colors = []
if rug_text is None:
rug_text = []
validate_distplot(hist_data, curve_type)
utils.validate_equal_length(hist_data, group_labels)
if isinstance(bin_size, (float, int)):
bin_size = [bin_size] * len(hist_data)
data = []
if show_hist:
hist = _Distplot(
hist_data,
histnorm,
group_labels,
bin_size,
curve_type,
colors,
rug_text,
show_hist,
show_curve,
).make_hist()
data.append(hist)
if show_curve:
if curve_type == "normal":
curve = _Distplot(
hist_data,
histnorm,
group_labels,
bin_size,
curve_type,
colors,
rug_text,
show_hist,
show_curve,
).make_normal()
else:
curve = _Distplot(
hist_data,
histnorm,
group_labels,
bin_size,
curve_type,
colors,
rug_text,
show_hist,
show_curve,
).make_kde()
data.append(curve)
if show_rug:
rug = _Distplot(
hist_data,
histnorm,
group_labels,
bin_size,
curve_type,
colors,
rug_text,
show_hist,
show_curve,
).make_rug()
data.append(rug)
layout = graph_objs.Layout(
barmode="overlay",
hovermode="closest",
legend=dict(traceorder="reversed"),
xaxis1=dict(domain=[0.0, 1.0], anchor="y2", zeroline=False),
yaxis1=dict(domain=[0.35, 1], anchor="free", position=0.0),
yaxis2=dict(domain=[0, 0.25], anchor="x1", dtick=1, showticklabels=False),
)
else:
layout = graph_objs.Layout(
barmode="overlay",
hovermode="closest",
legend=dict(traceorder="reversed"),
xaxis1=dict(domain=[0.0, 1.0], anchor="y2", zeroline=False),
yaxis1=dict(domain=[0.0, 1], anchor="free", position=0.0),
)
data = sum(data, [])
return graph_objs.Figure(data=data, layout=layout)
| _distplot.create_distplot |
plotly.py | 8 | packages/python/plotly/plotly/figure_factory/_facet_grid.py | def create_facet_grid(
df,
x=None,
y=None,
facet_row=None,
facet_col=None,
color_name=None,
colormap=None,
color_is_cat=False,
facet_row_labels=None,
facet_col_labels=None,
height=None,
width=None,
trace_type="scatter",
scales="fixed",
dtick_x=None,
dtick_y=None,
show_boxes=True,
ggplot2=False,
binsize=1,
**kwargs,
):
"""
Returns figure for facet grid; **this function is deprecated**, since
plotly.express functions should be used instead, for example
>>> import plotly.express as px
>>> tips = px.data.tips()
>>> fig = px.scatter(tips,
... x='total_bill',
... y='tip',
... facet_row='sex',
... facet_col='smoker',
... color='size')
:param (pd.DataFrame) df: the dataframe of columns for the facet grid.
:param (str) x: the name of the dataframe column for the x axis data.
:param (str) y: the name of the dataframe column for the y axis data.
:param (str) facet_row: the name of the dataframe column that is used to
facet the grid into row panels.
:param (str) facet_col: the name of the dataframe column that is used to
facet the grid into column panels.
:param (str) color_name: the name of your dataframe column that will
function as the colormap variable.
:param (str|list|dict) colormap: the param that determines how the
color_name column colors the data. If the dataframe contains numeric
data, then a dictionary of colors will group the data categorically
while a Plotly Colorscale name or a custom colorscale will treat it
numerically. To learn more about colors and types of colormap, run
`help(plotly.colors)`.
:param (bool) color_is_cat: determines whether a numerical column for the
colormap will be treated as categorical (True) or sequential (False).
Default = False.
:param (str|dict) facet_row_labels: set to either 'name' or a dictionary
of all the unique values in the faceting row mapped to some text to
show up in the label annotations. If None, labeling works like usual.
:param (str|dict) facet_col_labels: set to either 'name' or a dictionary
of all the values in the faceting row mapped to some text to show up
in the label annotations. If None, labeling works like usual.
:param (int) height: the height of the facet grid figure.
:param (int) width: the width of the facet grid figure.
:param (str) trace_type: decides the type of plot to appear in the
facet grid. The options are 'scatter', 'scattergl', 'histogram',
'bar', and 'box'.
Default = 'scatter'.
:param (str) scales: determines if axes have fixed ranges or not. Valid
settings are 'fixed' (all axes fixed), 'free_x' (x axis free only),
'free_y' (y axis free only) or 'free' (both axes free).
:param (float) dtick_x: determines the distance between each tick on the
x-axis. Default is None which means dtick_x is set automatically.
:param (float) dtick_y: determines the distance between each tick on the
y-axis. Default is None which means dtick_y is set automatically.
:param (bool) show_boxes: draws grey boxes behind the facet titles.
:param (bool) ggplot2: draws the facet grid in the style of `ggplot2`. See
http://ggplot2.tidyverse.org/reference/facet_grid.html for reference.
Default = False
:param (int) binsize: groups all data into bins of a given length.
:param (dict) kwargs: a dictionary of scatterplot arguments.
Examples 1: One Way Faceting
>>> import plotly.figure_factory as ff
>>> import pandas as pd
>>> mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt')
>>> fig = ff.create_facet_grid(
... mpg,
... x='displ',
... y='cty',
... facet_col='cyl',
... )
>>> fig.show()
Example 2: Two Way Faceting
>>> import plotly.figure_factory as ff
>>> import pandas as pd
>>> mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt')
>>> fig = ff.create_facet_grid(
... mpg,
... x='displ',
... y='cty',
... facet_row='drv',
... facet_col='cyl',
... )
>>> fig.show()
Example 3: Categorical Coloring
>>> import plotly.figure_factory as ff
>>> import pandas as pd
>>> mtcars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv')
>>> mtcars.cyl = mtcars.cyl.astype(str)
>>> fig = ff.create_facet_grid(
... mtcars,
... x='mpg',
... y='wt',
... facet_col='cyl',
... color_name='cyl',
... color_is_cat=True,
... )
>>> fig.show()
"""
| /usr/src/app/target_test_cases/failed_tests__facet_grid.create_facet_grid.txt | def create_facet_grid(
df,
x=None,
y=None,
facet_row=None,
facet_col=None,
color_name=None,
colormap=None,
color_is_cat=False,
facet_row_labels=None,
facet_col_labels=None,
height=None,
width=None,
trace_type="scatter",
scales="fixed",
dtick_x=None,
dtick_y=None,
show_boxes=True,
ggplot2=False,
binsize=1,
**kwargs,
):
"""
Returns figure for facet grid; **this function is deprecated**, since
plotly.express functions should be used instead, for example
>>> import plotly.express as px
>>> tips = px.data.tips()
>>> fig = px.scatter(tips,
... x='total_bill',
... y='tip',
... facet_row='sex',
... facet_col='smoker',
... color='size')
:param (pd.DataFrame) df: the dataframe of columns for the facet grid.
:param (str) x: the name of the dataframe column for the x axis data.
:param (str) y: the name of the dataframe column for the y axis data.
:param (str) facet_row: the name of the dataframe column that is used to
facet the grid into row panels.
:param (str) facet_col: the name of the dataframe column that is used to
facet the grid into column panels.
:param (str) color_name: the name of your dataframe column that will
function as the colormap variable.
:param (str|list|dict) colormap: the param that determines how the
color_name column colors the data. If the dataframe contains numeric
data, then a dictionary of colors will group the data categorically
while a Plotly Colorscale name or a custom colorscale will treat it
numerically. To learn more about colors and types of colormap, run
`help(plotly.colors)`.
:param (bool) color_is_cat: determines whether a numerical column for the
colormap will be treated as categorical (True) or sequential (False).
Default = False.
:param (str|dict) facet_row_labels: set to either 'name' or a dictionary
of all the unique values in the faceting row mapped to some text to
show up in the label annotations. If None, labeling works like usual.
:param (str|dict) facet_col_labels: set to either 'name' or a dictionary
of all the values in the faceting row mapped to some text to show up
in the label annotations. If None, labeling works like usual.
:param (int) height: the height of the facet grid figure.
:param (int) width: the width of the facet grid figure.
:param (str) trace_type: decides the type of plot to appear in the
facet grid. The options are 'scatter', 'scattergl', 'histogram',
'bar', and 'box'.
Default = 'scatter'.
:param (str) scales: determines if axes have fixed ranges or not. Valid
settings are 'fixed' (all axes fixed), 'free_x' (x axis free only),
'free_y' (y axis free only) or 'free' (both axes free).
:param (float) dtick_x: determines the distance between each tick on the
x-axis. Default is None which means dtick_x is set automatically.
:param (float) dtick_y: determines the distance between each tick on the
y-axis. Default is None which means dtick_y is set automatically.
:param (bool) show_boxes: draws grey boxes behind the facet titles.
:param (bool) ggplot2: draws the facet grid in the style of `ggplot2`. See
http://ggplot2.tidyverse.org/reference/facet_grid.html for reference.
Default = False
:param (int) binsize: groups all data into bins of a given length.
:param (dict) kwargs: a dictionary of scatterplot arguments.
Examples 1: One Way Faceting
>>> import plotly.figure_factory as ff
>>> import pandas as pd
>>> mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt')
>>> fig = ff.create_facet_grid(
... mpg,
... x='displ',
... y='cty',
... facet_col='cyl',
... )
>>> fig.show()
Example 2: Two Way Faceting
>>> import plotly.figure_factory as ff
>>> import pandas as pd
>>> mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt')
>>> fig = ff.create_facet_grid(
... mpg,
... x='displ',
... y='cty',
... facet_row='drv',
... facet_col='cyl',
... )
>>> fig.show()
Example 3: Categorical Coloring
>>> import plotly.figure_factory as ff
>>> import pandas as pd
>>> mtcars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv')
>>> mtcars.cyl = mtcars.cyl.astype(str)
>>> fig = ff.create_facet_grid(
... mtcars,
... x='mpg',
... y='wt',
... facet_col='cyl',
... color_name='cyl',
... color_is_cat=True,
... )
>>> fig.show()
"""
if not pd:
raise ImportError("'pandas' must be installed for this figure_factory.")
if not isinstance(df, pd.DataFrame):
raise exceptions.PlotlyError("You must input a pandas DataFrame.")
# make sure all columns are of homogenous datatype
utils.validate_dataframe(df)
if trace_type in ["scatter", "scattergl"]:
if not x or not y:
raise exceptions.PlotlyError(
"You need to input 'x' and 'y' if you are you are using a "
"trace_type of 'scatter' or 'scattergl'."
)
for key in [x, y, facet_row, facet_col, color_name]:
if key is not None:
try:
df[key]
except KeyError:
raise exceptions.PlotlyError(
"x, y, facet_row, facet_col and color_name must be keys "
"in your dataframe."
)
# autoscale histogram bars
if trace_type not in ["scatter", "scattergl"]:
scales = "free"
# validate scales
if scales not in ["fixed", "free_x", "free_y", "free"]:
raise exceptions.PlotlyError(
"'scales' must be set to 'fixed', 'free_x', 'free_y' and 'free'."
)
if trace_type not in VALID_TRACE_TYPES:
raise exceptions.PlotlyError(
"'trace_type' must be in {}".format(VALID_TRACE_TYPES)
)
if trace_type == "histogram":
SUBPLOT_SPACING = 0.06
else:
SUBPLOT_SPACING = 0.015
# seperate kwargs for marker and else
if "marker" in kwargs:
kwargs_marker = kwargs["marker"]
else:
kwargs_marker = {}
marker_color = kwargs_marker.pop("color", None)
kwargs.pop("marker", None)
kwargs_trace = kwargs
if "size" not in kwargs_marker:
if ggplot2:
kwargs_marker["size"] = 5
else:
kwargs_marker["size"] = 8
if "opacity" not in kwargs_marker:
if not ggplot2:
kwargs_trace["opacity"] = 0.6
if "line" not in kwargs_marker:
if not ggplot2:
kwargs_marker["line"] = {"color": "darkgrey", "width": 1}
else:
kwargs_marker["line"] = {}
# default marker size
if not ggplot2:
if not marker_color:
marker_color = "rgb(31, 119, 180)"
else:
marker_color = "rgb(0, 0, 0)"
num_of_rows = 1
num_of_cols = 1
flipped_rows = False
flipped_cols = False
if facet_row:
num_of_rows = len(df[facet_row].unique())
flipped_rows = _is_flipped(num_of_rows)
if isinstance(facet_row_labels, dict):
for key in df[facet_row].unique():
if key not in facet_row_labels.keys():
unique_keys = df[facet_row].unique().tolist()
raise exceptions.PlotlyError(CUSTOM_LABEL_ERROR.format(unique_keys))
if facet_col:
num_of_cols = len(df[facet_col].unique())
flipped_cols = _is_flipped(num_of_cols)
if isinstance(facet_col_labels, dict):
for key in df[facet_col].unique():
if key not in facet_col_labels.keys():
unique_keys = df[facet_col].unique().tolist()
raise exceptions.PlotlyError(CUSTOM_LABEL_ERROR.format(unique_keys))
show_legend = False
if color_name:
if isinstance(df[color_name].iloc[0], str) or color_is_cat:
show_legend = True
if isinstance(colormap, dict):
clrs.validate_colors_dict(colormap, "rgb")
for val in df[color_name].unique():
if val not in colormap.keys():
raise exceptions.PlotlyError(
"If using 'colormap' as a dictionary, make sure "
"all the values of the colormap column are in "
"the keys of your dictionary."
)
else:
# use default plotly colors for dictionary
default_colors = clrs.DEFAULT_PLOTLY_COLORS
colormap = {}
j = 0
for val in df[color_name].unique():
if j >= len(default_colors):
j = 0
colormap[val] = default_colors[j]
j += 1
fig, annotations = _facet_grid_color_categorical(
df,
x,
y,
facet_row,
facet_col,
color_name,
colormap,
num_of_rows,
num_of_cols,
facet_row_labels,
facet_col_labels,
trace_type,
flipped_rows,
flipped_cols,
show_boxes,
SUBPLOT_SPACING,
marker_color,
kwargs_trace,
kwargs_marker,
)
elif isinstance(df[color_name].iloc[0], Number):
if isinstance(colormap, dict):
show_legend = True
clrs.validate_colors_dict(colormap, "rgb")
for val in df[color_name].unique():
if val not in colormap.keys():
raise exceptions.PlotlyError(
"If using 'colormap' as a dictionary, make sure "
"all the values of the colormap column are in "
"the keys of your dictionary."
)
fig, annotations = _facet_grid_color_categorical(
df,
x,
y,
facet_row,
facet_col,
color_name,
colormap,
num_of_rows,
num_of_cols,
facet_row_labels,
facet_col_labels,
trace_type,
flipped_rows,
flipped_cols,
show_boxes,
SUBPLOT_SPACING,
marker_color,
kwargs_trace,
kwargs_marker,
)
elif isinstance(colormap, list):
colorscale_list = colormap
clrs.validate_colorscale(colorscale_list)
fig, annotations = _facet_grid_color_numerical(
df,
x,
y,
facet_row,
facet_col,
color_name,
colorscale_list,
num_of_rows,
num_of_cols,
facet_row_labels,
facet_col_labels,
trace_type,
flipped_rows,
flipped_cols,
show_boxes,
SUBPLOT_SPACING,
marker_color,
kwargs_trace,
kwargs_marker,
)
elif isinstance(colormap, str):
if colormap in clrs.PLOTLY_SCALES.keys():
colorscale_list = clrs.PLOTLY_SCALES[colormap]
else:
raise exceptions.PlotlyError(
"If 'colormap' is a string, it must be the name "
"of a Plotly Colorscale. The available colorscale "
"names are {}".format(clrs.PLOTLY_SCALES.keys())
)
fig, annotations = _facet_grid_color_numerical(
df,
x,
y,
facet_row,
facet_col,
color_name,
colorscale_list,
num_of_rows,
num_of_cols,
facet_row_labels,
facet_col_labels,
trace_type,
flipped_rows,
flipped_cols,
show_boxes,
SUBPLOT_SPACING,
marker_color,
kwargs_trace,
kwargs_marker,
)
else:
colorscale_list = clrs.PLOTLY_SCALES["Reds"]
fig, annotations = _facet_grid_color_numerical(
df,
x,
y,
facet_row,
facet_col,
color_name,
colorscale_list,
num_of_rows,
num_of_cols,
facet_row_labels,
facet_col_labels,
trace_type,
flipped_rows,
flipped_cols,
show_boxes,
SUBPLOT_SPACING,
marker_color,
kwargs_trace,
kwargs_marker,
)
else:
fig, annotations = _facet_grid(
df,
x,
y,
facet_row,
facet_col,
num_of_rows,
num_of_cols,
facet_row_labels,
facet_col_labels,
trace_type,
flipped_rows,
flipped_cols,
show_boxes,
SUBPLOT_SPACING,
marker_color,
kwargs_trace,
kwargs_marker,
)
if not height:
height = max(600, 100 * num_of_rows)
if not width:
width = max(600, 100 * num_of_cols)
fig["layout"].update(
height=height, width=width, title="", paper_bgcolor="rgb(251, 251, 251)"
)
if ggplot2:
fig["layout"].update(
plot_bgcolor=PLOT_BGCOLOR,
paper_bgcolor="rgb(255, 255, 255)",
hovermode="closest",
)
# axis titles
x_title_annot = _axis_title_annotation(x, "x")
y_title_annot = _axis_title_annotation(y, "y")
# annotations
annotations.append(x_title_annot)
annotations.append(y_title_annot)
# legend
fig["layout"]["showlegend"] = show_legend
fig["layout"]["legend"]["bgcolor"] = LEGEND_COLOR
fig["layout"]["legend"]["borderwidth"] = LEGEND_BORDER_WIDTH
fig["layout"]["legend"]["x"] = 1.05
fig["layout"]["legend"]["y"] = 1
fig["layout"]["legend"]["yanchor"] = "top"
if show_legend:
fig["layout"]["showlegend"] = show_legend
if ggplot2:
if color_name:
legend_annot = _legend_annotation(color_name)
annotations.append(legend_annot)
fig["layout"]["margin"]["r"] = 150
# assign annotations to figure
fig["layout"]["annotations"] = annotations
# add shaded boxes behind axis titles
if show_boxes and ggplot2:
_add_shapes_to_fig(fig, ANNOT_RECT_COLOR, flipped_rows, flipped_cols)
# all xaxis and yaxis labels
axis_labels = {"x": [], "y": []}
for key in fig["layout"]:
if "xaxis" in key:
axis_labels["x"].append(key)
elif "yaxis" in key:
axis_labels["y"].append(key)
string_number_in_data = False
for var in [v for v in [x, y] if v]:
if isinstance(df[var].tolist()[0], str):
for item in df[var]:
try:
int(item)
string_number_in_data = True
except ValueError:
pass
if string_number_in_data:
for x_y in axis_labels.keys():
for axis_name in axis_labels[x_y]:
fig["layout"][axis_name]["type"] = "category"
if scales == "fixed":
fixed_axes = ["x", "y"]
elif scales == "free_x":
fixed_axes = ["y"]
elif scales == "free_y":
fixed_axes = ["x"]
elif scales == "free":
fixed_axes = []
# fixed ranges
for x_y in fixed_axes:
min_ranges = []
max_ranges = []
for trace in fig["data"]:
if trace[x_y] is not None and len(trace[x_y]) > 0:
min_ranges.append(min(trace[x_y]))
max_ranges.append(max(trace[x_y]))
while None in min_ranges:
min_ranges.remove(None)
while None in max_ranges:
max_ranges.remove(None)
min_range = min(min_ranges)
max_range = max(max_ranges)
range_are_numbers = isinstance(min_range, Number) and isinstance(
max_range, Number
)
if range_are_numbers:
min_range = math.floor(min_range)
max_range = math.ceil(max_range)
# extend widen frame by 5% on each side
min_range -= 0.05 * (max_range - min_range)
max_range += 0.05 * (max_range - min_range)
if x_y == "x":
if dtick_x:
dtick = dtick_x
else:
dtick = math.floor((max_range - min_range) / MAX_TICKS_PER_AXIS)
elif x_y == "y":
if dtick_y:
dtick = dtick_y
else:
dtick = math.floor((max_range - min_range) / MAX_TICKS_PER_AXIS)
else:
dtick = 1
for axis_title in axis_labels[x_y]:
fig["layout"][axis_title]["dtick"] = dtick
fig["layout"][axis_title]["ticklen"] = 0
fig["layout"][axis_title]["zeroline"] = False
if ggplot2:
fig["layout"][axis_title]["tickwidth"] = 1
fig["layout"][axis_title]["ticklen"] = 4
fig["layout"][axis_title]["gridwidth"] = GRID_WIDTH
fig["layout"][axis_title]["gridcolor"] = GRID_COLOR
fig["layout"][axis_title]["gridwidth"] = 2
fig["layout"][axis_title]["tickfont"] = {
"color": TICK_COLOR,
"size": 10,
}
# insert ranges into fig
if x_y in fixed_axes:
for key in fig["layout"]:
if "{}axis".format(x_y) in key and range_are_numbers:
fig["layout"][key]["range"] = [min_range, max_range]
return fig
| _facet_grid.create_facet_grid |
plotly.py | 9 | packages/python/plotly/plotly/graph_objs/_funnel.py | def __init__(
self,
arg=None,
alignmentgroup=None,
cliponaxis=None,
connector=None,
constraintext=None,
customdata=None,
customdatasrc=None,
dx=None,
dy=None,
hoverinfo=None,
hoverinfosrc=None,
hoverlabel=None,
hovertemplate=None,
hovertemplatesrc=None,
hovertext=None,
hovertextsrc=None,
ids=None,
idssrc=None,
insidetextanchor=None,
insidetextfont=None,
legend=None,
legendgroup=None,
legendgrouptitle=None,
legendrank=None,
legendwidth=None,
marker=None,
meta=None,
metasrc=None,
name=None,
offset=None,
offsetgroup=None,
opacity=None,
orientation=None,
outsidetextfont=None,
selectedpoints=None,
showlegend=None,
stream=None,
text=None,
textangle=None,
textfont=None,
textinfo=None,
textposition=None,
textpositionsrc=None,
textsrc=None,
texttemplate=None,
texttemplatesrc=None,
uid=None,
uirevision=None,
visible=None,
width=None,
x=None,
x0=None,
xaxis=None,
xhoverformat=None,
xperiod=None,
xperiod0=None,
xperiodalignment=None,
xsrc=None,
y=None,
y0=None,
yaxis=None,
yhoverformat=None,
yperiod=None,
yperiod0=None,
yperiodalignment=None,
ysrc=None,
zorder=None,
**kwargs,
):
"""
Construct a new Funnel object
Visualize stages in a process using length-encoded bars. This
trace can be used to show data in either a part-to-whole
representation wherein each item appears in a single stage, or
in a "drop-off" representation wherein each item appears in
each stage it traversed. See also the "funnelarea" trace type
for a different approach to visualizing funnel data.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.Funnel`
alignmentgroup
Set several traces linked to the same position axis or
matching axes to the same alignmentgroup. This controls
whether bars compute their positional range dependently
or independently.
cliponaxis
Determines whether the text nodes are clipped about the
subplot axes. To show the text nodes above axis lines
and tick labels, make sure to set `xaxis.layer` and
`yaxis.layer` to *below traces*.
connector
:class:`plotly.graph_objects.funnel.Connector` instance
or dict with compatible properties
constraintext
Constrain the size of text inside or outside a bar to
be no larger than the bar itself.
customdata
Assigns extra data each datum. This may be useful when
listening to hover, click and selection events. Note
that, "scatter" traces also appends customdata items in
the markers DOM elements
customdatasrc
Sets the source reference on Chart Studio Cloud for
`customdata`.
dx
Sets the x coordinate step. See `x0` for more info.
dy
Sets the y coordinate step. See `y0` for more info.
hoverinfo
Determines which trace information appear on hover. If
`none` or `skip` are set, no information is displayed
upon hovering. But, if `none` is set, click and hover
events are still fired.
hoverinfosrc
Sets the source reference on Chart Studio Cloud for
`hoverinfo`.
hoverlabel
:class:`plotly.graph_objects.funnel.Hoverlabel`
instance or dict with compatible properties
hovertemplate
Template string used for rendering the information that
appear on hover box. Note that this will override
`hoverinfo`. Variables are inserted using %{variable},
for example "y: %{y}" as well as %{xother}, {%_xother},
{%_xother_}, {%xother_}. When showing info for several
points, "xother" will be added to those with different
x positions from the first point. An underscore before
or after "(x|y)other" will add a space on that side,
only when this field is shown. Numbers are formatted
using d3-format's syntax %{variable:d3-format}, for
example "Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. The variables available in
`hovertemplate` are the ones emitted as event data
described at this link
https://plotly.com/javascript/plotlyjs-events/#event-
data. Additionally, every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Finally, the template string has access
to variables `percentInitial`, `percentPrevious` and
`percentTotal`. Anything contained in tag `<extra>` is
displayed in the secondary box, for example
"<extra>{fullData.name}</extra>". To hide the secondary
box completely, use an empty tag `<extra></extra>`.
hovertemplatesrc
Sets the source reference on Chart Studio Cloud for
`hovertemplate`.
hovertext
Sets hover text elements associated with each (x,y)
pair. If a single string, the same string appears over
all the data points. If an array of string, the items
are mapped in order to the this trace's (x,y)
coordinates. To be seen, trace `hoverinfo` must contain
a "text" flag.
hovertextsrc
Sets the source reference on Chart Studio Cloud for
`hovertext`.
ids
Assigns id labels to each datum. These ids for object
constancy of data points during animation. Should be an
array of strings, not numbers or any other type.
idssrc
Sets the source reference on Chart Studio Cloud for
`ids`.
insidetextanchor
Determines if texts are kept at center or start/end
points in `textposition` "inside" mode.
insidetextfont
Sets the font used for `text` lying inside the bar.
legend
Sets the reference to a legend to show this trace in.
References to these legends are "legend", "legend2",
"legend3", etc. Settings for these legends are set in
the layout, under `layout.legend`, `layout.legend2`,
etc.
legendgroup
Sets the legend group for this trace. Traces and shapes
part of the same legend group hide/show at the same
time when toggling legend items.
legendgrouptitle
:class:`plotly.graph_objects.funnel.Legendgrouptitle`
instance or dict with compatible properties
legendrank
Sets the legend rank for this trace. Items and groups
with smaller ranks are presented on top/left side while
with "reversed" `legend.traceorder` they are on
bottom/right side. The default legendrank is 1000, so
that you can use ranks less than 1000 to place certain
items before all unranked items, and ranks greater than
1000 to go after all unranked items. When having
unranked or equal rank items shapes would be displayed
after traces i.e. according to their order in data and
layout.
legendwidth
Sets the width (in px or fraction) of the legend for
this trace.
marker
:class:`plotly.graph_objects.funnel.Marker` instance or
dict with compatible properties
meta
Assigns extra meta information associated with this
trace that can be used in various text attributes.
Attributes such as trace `name`, graph, axis and
colorbar `title.text`, annotation `text`
`rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta`
values in an attribute in the same trace, simply use
`%{meta[i]}` where `i` is the index or key of the
`meta` item in question. To access trace `meta` in
layout attributes, use `%{data[n[.meta[i]}` where `i`
is the index or key of the `meta` and `n` is the trace
index.
metasrc
Sets the source reference on Chart Studio Cloud for
`meta`.
name
Sets the trace name. The trace name appears as the
legend item and on hover.
offset
Shifts the position where the bar is drawn (in position
axis units). In "group" barmode, traces that set
"offset" will be excluded and drawn in "overlay" mode
instead.
offsetgroup
Set several traces linked to the same position axis or
matching axes to the same offsetgroup where bars of the
same position coordinate will line up.
opacity
Sets the opacity of the trace.
orientation
Sets the orientation of the funnels. With "v" ("h"),
the value of the each bar spans along the vertical
(horizontal). By default funnels are tend to be
oriented horizontally; unless only "y" array is
presented or orientation is set to "v". Also regarding
graphs including only 'horizontal' funnels, "autorange"
on the "y-axis" are set to "reversed".
outsidetextfont
Sets the font used for `text` lying outside the bar.
selectedpoints
Array containing integer indices of selected points.
Has an effect only for traces that support selections.
Note that an empty array means an empty selection where
the `unselected` are turned on for all points, whereas,
any other non-array values means no selection all where
the `selected` and `unselected` styles have no effect.
showlegend
Determines whether or not an item corresponding to this
trace is shown in the legend.
stream
:class:`plotly.graph_objects.funnel.Stream` instance or
dict with compatible properties
text
Sets text elements associated with each (x,y) pair. If
a single string, the same string appears over all the
data points. If an array of string, the items are
mapped in order to the this trace's (x,y) coordinates.
If trace `hoverinfo` contains a "text" flag and
"hovertext" is not set, these elements will be seen in
the hover labels.
textangle
Sets the angle of the tick labels with respect to the
bar. For example, a `tickangle` of -90 draws the tick
labels vertically. With "auto" the texts may
automatically be rotated to fit with the maximum size
in bars.
textfont
Sets the font used for `text`.
textinfo
Determines which trace information appear on the graph.
In the case of having multiple funnels, percentages &
totals are computed separately (per trace).
textposition
Specifies the location of the `text`. "inside"
positions `text` inside, next to the bar end (rotated
and scaled if needed). "outside" positions `text`
outside, next to the bar end (scaled if needed), unless
there is another bar stacked on this one, then the text
gets pushed inside. "auto" tries to position `text`
inside the bar, but if the bar is too small and no bar
is stacked on this one the text is moved outside. If
"none", no text appears.
textpositionsrc
Sets the source reference on Chart Studio Cloud for
`textposition`.
textsrc
Sets the source reference on Chart Studio Cloud for
`text`.
texttemplate
Template string used for rendering the information text
that appear on points. Note that this will override
`textinfo`. Variables are inserted using %{variable},
for example "y: %{y}". Numbers are formatted using
d3-format's syntax %{variable:d3-format}, for example
"Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. Every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Finally, the template string has access
to variables `percentInitial`, `percentPrevious`,
`percentTotal`, `label` and `value`.
texttemplatesrc
Sets the source reference on Chart Studio Cloud for
`texttemplate`.
uid
Assign an id to this trace, Use this to provide object
constancy between traces during animations and
transitions.
uirevision
Controls persistence of some user-driven changes to the
trace: `constraintrange` in `parcoords` traces, as well
as some `editable: true` modifications such as `name`
and `colorbar.title`. Defaults to `layout.uirevision`.
Note that other user-driven trace attribute changes are
controlled by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
width
Sets the bar width (in position axis units).
x
Sets the x coordinates.
x0
Alternate to `x`. Builds a linear space of x
coordinates. Use with `dx` where `x0` is the starting
coordinate and `dx` the step.
xaxis
Sets a reference between this trace's x coordinates and
a 2D cartesian x axis. If "x" (the default value), the
x coordinates refer to `layout.xaxis`. If "x2", the x
coordinates refer to `layout.xaxis2`, and so on.
xhoverformat
Sets the hover text formatting rulefor `x` using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display *09~15~23.46*By default the values are
formatted using `xaxis.hoverformat`.
xperiod
Only relevant when the axis `type` is "date". Sets the
period positioning in milliseconds or "M<n>" on the x
axis. Special values in the form of "M<n>" could be
used to declare the number of months. In this case `n`
must be a positive integer.
xperiod0
Only relevant when the axis `type` is "date". Sets the
base for period positioning in milliseconds or date
string on the x0 axis. When `x0period` is round number
of weeks, the `x0period0` by default would be on a
Sunday i.e. 2000-01-02, otherwise it would be at
2000-01-01.
xperiodalignment
Only relevant when the axis `type` is "date". Sets the
alignment of data points on the x axis.
xsrc
Sets the source reference on Chart Studio Cloud for
`x`.
y
Sets the y coordinates.
y0
Alternate to `y`. Builds a linear space of y
coordinates. Use with `dy` where `y0` is the starting
coordinate and `dy` the step.
yaxis
Sets a reference between this trace's y coordinates and
a 2D cartesian y axis. If "y" (the default value), the
y coordinates refer to `layout.yaxis`. If "y2", the y
coordinates refer to `layout.yaxis2`, and so on.
yhoverformat
Sets the hover text formatting rulefor `y` using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display *09~15~23.46*By default the values are
formatted using `yaxis.hoverformat`.
yperiod
Only relevant when the axis `type` is "date". Sets the
period positioning in milliseconds or "M<n>" on the y
axis. Special values in the form of "M<n>" could be
used to declare the number of months. In this case `n`
must be a positive integer.
yperiod0
Only relevant when the axis `type` is "date". Sets the
base for period positioning in milliseconds or date
string on the y0 axis. When `y0period` is round number
of weeks, the `y0period0` by default would be on a
Sunday i.e. 2000-01-02, otherwise it would be at
2000-01-01.
yperiodalignment
Only relevant when the axis `type` is "date". Sets the
alignment of data points on the y axis.
ysrc
Sets the source reference on Chart Studio Cloud for
`y`.
zorder
Sets the layer on which this trace is displayed,
relative to other SVG traces on the same subplot. SVG
traces with higher `zorder` appear in front of those
with lower `zorder`.
Returns
-------
Funnel
"""
| /usr/src/app/target_test_cases/failed_tests__funnel.Funnel.__init__.txt | def __init__(
self,
arg=None,
alignmentgroup=None,
cliponaxis=None,
connector=None,
constraintext=None,
customdata=None,
customdatasrc=None,
dx=None,
dy=None,
hoverinfo=None,
hoverinfosrc=None,
hoverlabel=None,
hovertemplate=None,
hovertemplatesrc=None,
hovertext=None,
hovertextsrc=None,
ids=None,
idssrc=None,
insidetextanchor=None,
insidetextfont=None,
legend=None,
legendgroup=None,
legendgrouptitle=None,
legendrank=None,
legendwidth=None,
marker=None,
meta=None,
metasrc=None,
name=None,
offset=None,
offsetgroup=None,
opacity=None,
orientation=None,
outsidetextfont=None,
selectedpoints=None,
showlegend=None,
stream=None,
text=None,
textangle=None,
textfont=None,
textinfo=None,
textposition=None,
textpositionsrc=None,
textsrc=None,
texttemplate=None,
texttemplatesrc=None,
uid=None,
uirevision=None,
visible=None,
width=None,
x=None,
x0=None,
xaxis=None,
xhoverformat=None,
xperiod=None,
xperiod0=None,
xperiodalignment=None,
xsrc=None,
y=None,
y0=None,
yaxis=None,
yhoverformat=None,
yperiod=None,
yperiod0=None,
yperiodalignment=None,
ysrc=None,
zorder=None,
**kwargs,
):
"""
Construct a new Funnel object
Visualize stages in a process using length-encoded bars. This
trace can be used to show data in either a part-to-whole
representation wherein each item appears in a single stage, or
in a "drop-off" representation wherein each item appears in
each stage it traversed. See also the "funnelarea" trace type
for a different approach to visualizing funnel data.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.Funnel`
alignmentgroup
Set several traces linked to the same position axis or
matching axes to the same alignmentgroup. This controls
whether bars compute their positional range dependently
or independently.
cliponaxis
Determines whether the text nodes are clipped about the
subplot axes. To show the text nodes above axis lines
and tick labels, make sure to set `xaxis.layer` and
`yaxis.layer` to *below traces*.
connector
:class:`plotly.graph_objects.funnel.Connector` instance
or dict with compatible properties
constraintext
Constrain the size of text inside or outside a bar to
be no larger than the bar itself.
customdata
Assigns extra data each datum. This may be useful when
listening to hover, click and selection events. Note
that, "scatter" traces also appends customdata items in
the markers DOM elements
customdatasrc
Sets the source reference on Chart Studio Cloud for
`customdata`.
dx
Sets the x coordinate step. See `x0` for more info.
dy
Sets the y coordinate step. See `y0` for more info.
hoverinfo
Determines which trace information appear on hover. If
`none` or `skip` are set, no information is displayed
upon hovering. But, if `none` is set, click and hover
events are still fired.
hoverinfosrc
Sets the source reference on Chart Studio Cloud for
`hoverinfo`.
hoverlabel
:class:`plotly.graph_objects.funnel.Hoverlabel`
instance or dict with compatible properties
hovertemplate
Template string used for rendering the information that
appear on hover box. Note that this will override
`hoverinfo`. Variables are inserted using %{variable},
for example "y: %{y}" as well as %{xother}, {%_xother},
{%_xother_}, {%xother_}. When showing info for several
points, "xother" will be added to those with different
x positions from the first point. An underscore before
or after "(x|y)other" will add a space on that side,
only when this field is shown. Numbers are formatted
using d3-format's syntax %{variable:d3-format}, for
example "Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. The variables available in
`hovertemplate` are the ones emitted as event data
described at this link
https://plotly.com/javascript/plotlyjs-events/#event-
data. Additionally, every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Finally, the template string has access
to variables `percentInitial`, `percentPrevious` and
`percentTotal`. Anything contained in tag `<extra>` is
displayed in the secondary box, for example
"<extra>{fullData.name}</extra>". To hide the secondary
box completely, use an empty tag `<extra></extra>`.
hovertemplatesrc
Sets the source reference on Chart Studio Cloud for
`hovertemplate`.
hovertext
Sets hover text elements associated with each (x,y)
pair. If a single string, the same string appears over
all the data points. If an array of string, the items
are mapped in order to the this trace's (x,y)
coordinates. To be seen, trace `hoverinfo` must contain
a "text" flag.
hovertextsrc
Sets the source reference on Chart Studio Cloud for
`hovertext`.
ids
Assigns id labels to each datum. These ids for object
constancy of data points during animation. Should be an
array of strings, not numbers or any other type.
idssrc
Sets the source reference on Chart Studio Cloud for
`ids`.
insidetextanchor
Determines if texts are kept at center or start/end
points in `textposition` "inside" mode.
insidetextfont
Sets the font used for `text` lying inside the bar.
legend
Sets the reference to a legend to show this trace in.
References to these legends are "legend", "legend2",
"legend3", etc. Settings for these legends are set in
the layout, under `layout.legend`, `layout.legend2`,
etc.
legendgroup
Sets the legend group for this trace. Traces and shapes
part of the same legend group hide/show at the same
time when toggling legend items.
legendgrouptitle
:class:`plotly.graph_objects.funnel.Legendgrouptitle`
instance or dict with compatible properties
legendrank
Sets the legend rank for this trace. Items and groups
with smaller ranks are presented on top/left side while
with "reversed" `legend.traceorder` they are on
bottom/right side. The default legendrank is 1000, so
that you can use ranks less than 1000 to place certain
items before all unranked items, and ranks greater than
1000 to go after all unranked items. When having
unranked or equal rank items shapes would be displayed
after traces i.e. according to their order in data and
layout.
legendwidth
Sets the width (in px or fraction) of the legend for
this trace.
marker
:class:`plotly.graph_objects.funnel.Marker` instance or
dict with compatible properties
meta
Assigns extra meta information associated with this
trace that can be used in various text attributes.
Attributes such as trace `name`, graph, axis and
colorbar `title.text`, annotation `text`
`rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta`
values in an attribute in the same trace, simply use
`%{meta[i]}` where `i` is the index or key of the
`meta` item in question. To access trace `meta` in
layout attributes, use `%{data[n[.meta[i]}` where `i`
is the index or key of the `meta` and `n` is the trace
index.
metasrc
Sets the source reference on Chart Studio Cloud for
`meta`.
name
Sets the trace name. The trace name appears as the
legend item and on hover.
offset
Shifts the position where the bar is drawn (in position
axis units). In "group" barmode, traces that set
"offset" will be excluded and drawn in "overlay" mode
instead.
offsetgroup
Set several traces linked to the same position axis or
matching axes to the same offsetgroup where bars of the
same position coordinate will line up.
opacity
Sets the opacity of the trace.
orientation
Sets the orientation of the funnels. With "v" ("h"),
the value of the each bar spans along the vertical
(horizontal). By default funnels are tend to be
oriented horizontally; unless only "y" array is
presented or orientation is set to "v". Also regarding
graphs including only 'horizontal' funnels, "autorange"
on the "y-axis" are set to "reversed".
outsidetextfont
Sets the font used for `text` lying outside the bar.
selectedpoints
Array containing integer indices of selected points.
Has an effect only for traces that support selections.
Note that an empty array means an empty selection where
the `unselected` are turned on for all points, whereas,
any other non-array values means no selection all where
the `selected` and `unselected` styles have no effect.
showlegend
Determines whether or not an item corresponding to this
trace is shown in the legend.
stream
:class:`plotly.graph_objects.funnel.Stream` instance or
dict with compatible properties
text
Sets text elements associated with each (x,y) pair. If
a single string, the same string appears over all the
data points. If an array of string, the items are
mapped in order to the this trace's (x,y) coordinates.
If trace `hoverinfo` contains a "text" flag and
"hovertext" is not set, these elements will be seen in
the hover labels.
textangle
Sets the angle of the tick labels with respect to the
bar. For example, a `tickangle` of -90 draws the tick
labels vertically. With "auto" the texts may
automatically be rotated to fit with the maximum size
in bars.
textfont
Sets the font used for `text`.
textinfo
Determines which trace information appear on the graph.
In the case of having multiple funnels, percentages &
totals are computed separately (per trace).
textposition
Specifies the location of the `text`. "inside"
positions `text` inside, next to the bar end (rotated
and scaled if needed). "outside" positions `text`
outside, next to the bar end (scaled if needed), unless
there is another bar stacked on this one, then the text
gets pushed inside. "auto" tries to position `text`
inside the bar, but if the bar is too small and no bar
is stacked on this one the text is moved outside. If
"none", no text appears.
textpositionsrc
Sets the source reference on Chart Studio Cloud for
`textposition`.
textsrc
Sets the source reference on Chart Studio Cloud for
`text`.
texttemplate
Template string used for rendering the information text
that appear on points. Note that this will override
`textinfo`. Variables are inserted using %{variable},
for example "y: %{y}". Numbers are formatted using
d3-format's syntax %{variable:d3-format}, for example
"Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. Every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Finally, the template string has access
to variables `percentInitial`, `percentPrevious`,
`percentTotal`, `label` and `value`.
texttemplatesrc
Sets the source reference on Chart Studio Cloud for
`texttemplate`.
uid
Assign an id to this trace, Use this to provide object
constancy between traces during animations and
transitions.
uirevision
Controls persistence of some user-driven changes to the
trace: `constraintrange` in `parcoords` traces, as well
as some `editable: true` modifications such as `name`
and `colorbar.title`. Defaults to `layout.uirevision`.
Note that other user-driven trace attribute changes are
controlled by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
width
Sets the bar width (in position axis units).
x
Sets the x coordinates.
x0
Alternate to `x`. Builds a linear space of x
coordinates. Use with `dx` where `x0` is the starting
coordinate and `dx` the step.
xaxis
Sets a reference between this trace's x coordinates and
a 2D cartesian x axis. If "x" (the default value), the
x coordinates refer to `layout.xaxis`. If "x2", the x
coordinates refer to `layout.xaxis2`, and so on.
xhoverformat
Sets the hover text formatting rulefor `x` using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display *09~15~23.46*By default the values are
formatted using `xaxis.hoverformat`.
xperiod
Only relevant when the axis `type` is "date". Sets the
period positioning in milliseconds or "M<n>" on the x
axis. Special values in the form of "M<n>" could be
used to declare the number of months. In this case `n`
must be a positive integer.
xperiod0
Only relevant when the axis `type` is "date". Sets the
base for period positioning in milliseconds or date
string on the x0 axis. When `x0period` is round number
of weeks, the `x0period0` by default would be on a
Sunday i.e. 2000-01-02, otherwise it would be at
2000-01-01.
xperiodalignment
Only relevant when the axis `type` is "date". Sets the
alignment of data points on the x axis.
xsrc
Sets the source reference on Chart Studio Cloud for
`x`.
y
Sets the y coordinates.
y0
Alternate to `y`. Builds a linear space of y
coordinates. Use with `dy` where `y0` is the starting
coordinate and `dy` the step.
yaxis
Sets a reference between this trace's y coordinates and
a 2D cartesian y axis. If "y" (the default value), the
y coordinates refer to `layout.yaxis`. If "y2", the y
coordinates refer to `layout.yaxis2`, and so on.
yhoverformat
Sets the hover text formatting rulefor `y` using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display *09~15~23.46*By default the values are
formatted using `yaxis.hoverformat`.
yperiod
Only relevant when the axis `type` is "date". Sets the
period positioning in milliseconds or "M<n>" on the y
axis. Special values in the form of "M<n>" could be
used to declare the number of months. In this case `n`
must be a positive integer.
yperiod0
Only relevant when the axis `type` is "date". Sets the
base for period positioning in milliseconds or date
string on the y0 axis. When `y0period` is round number
of weeks, the `y0period0` by default would be on a
Sunday i.e. 2000-01-02, otherwise it would be at
2000-01-01.
yperiodalignment
Only relevant when the axis `type` is "date". Sets the
alignment of data points on the y axis.
ysrc
Sets the source reference on Chart Studio Cloud for
`y`.
zorder
Sets the layer on which this trace is displayed,
relative to other SVG traces on the same subplot. SVG
traces with higher `zorder` appear in front of those
with lower `zorder`.
Returns
-------
Funnel
"""
super(Funnel, self).__init__("funnel")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.Funnel
constructor must be a dict or
an instance of :class:`plotly.graph_objs.Funnel`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("alignmentgroup", None)
_v = alignmentgroup if alignmentgroup is not None else _v
if _v is not None:
self["alignmentgroup"] = _v
_v = arg.pop("cliponaxis", None)
_v = cliponaxis if cliponaxis is not None else _v
if _v is not None:
self["cliponaxis"] = _v
_v = arg.pop("connector", None)
_v = connector if connector is not None else _v
if _v is not None:
self["connector"] = _v
_v = arg.pop("constraintext", None)
_v = constraintext if constraintext is not None else _v
if _v is not None:
self["constraintext"] = _v
_v = arg.pop("customdata", None)
_v = customdata if customdata is not None else _v
if _v is not None:
self["customdata"] = _v
_v = arg.pop("customdatasrc", None)
_v = customdatasrc if customdatasrc is not None else _v
if _v is not None:
self["customdatasrc"] = _v
_v = arg.pop("dx", None)
_v = dx if dx is not None else _v
if _v is not None:
self["dx"] = _v
_v = arg.pop("dy", None)
_v = dy if dy is not None else _v
if _v is not None:
self["dy"] = _v
_v = arg.pop("hoverinfo", None)
_v = hoverinfo if hoverinfo is not None else _v
if _v is not None:
self["hoverinfo"] = _v
_v = arg.pop("hoverinfosrc", None)
_v = hoverinfosrc if hoverinfosrc is not None else _v
if _v is not None:
self["hoverinfosrc"] = _v
_v = arg.pop("hoverlabel", None)
_v = hoverlabel if hoverlabel is not None else _v
if _v is not None:
self["hoverlabel"] = _v
_v = arg.pop("hovertemplate", None)
_v = hovertemplate if hovertemplate is not None else _v
if _v is not None:
self["hovertemplate"] = _v
_v = arg.pop("hovertemplatesrc", None)
_v = hovertemplatesrc if hovertemplatesrc is not None else _v
if _v is not None:
self["hovertemplatesrc"] = _v
_v = arg.pop("hovertext", None)
_v = hovertext if hovertext is not None else _v
if _v is not None:
self["hovertext"] = _v
_v = arg.pop("hovertextsrc", None)
_v = hovertextsrc if hovertextsrc is not None else _v
if _v is not None:
self["hovertextsrc"] = _v
_v = arg.pop("ids", None)
_v = ids if ids is not None else _v
if _v is not None:
self["ids"] = _v
_v = arg.pop("idssrc", None)
_v = idssrc if idssrc is not None else _v
if _v is not None:
self["idssrc"] = _v
_v = arg.pop("insidetextanchor", None)
_v = insidetextanchor if insidetextanchor is not None else _v
if _v is not None:
self["insidetextanchor"] = _v
_v = arg.pop("insidetextfont", None)
_v = insidetextfont if insidetextfont is not None else _v
if _v is not None:
self["insidetextfont"] = _v
_v = arg.pop("legend", None)
_v = legend if legend is not None else _v
if _v is not None:
self["legend"] = _v
_v = arg.pop("legendgroup", None)
_v = legendgroup if legendgroup is not None else _v
if _v is not None:
self["legendgroup"] = _v
_v = arg.pop("legendgrouptitle", None)
_v = legendgrouptitle if legendgrouptitle is not None else _v
if _v is not None:
self["legendgrouptitle"] = _v
_v = arg.pop("legendrank", None)
_v = legendrank if legendrank is not None else _v
if _v is not None:
self["legendrank"] = _v
_v = arg.pop("legendwidth", None)
_v = legendwidth if legendwidth is not None else _v
if _v is not None:
self["legendwidth"] = _v
_v = arg.pop("marker", None)
_v = marker if marker is not None else _v
if _v is not None:
self["marker"] = _v
_v = arg.pop("meta", None)
_v = meta if meta is not None else _v
if _v is not None:
self["meta"] = _v
_v = arg.pop("metasrc", None)
_v = metasrc if metasrc is not None else _v
if _v is not None:
self["metasrc"] = _v
_v = arg.pop("name", None)
_v = name if name is not None else _v
if _v is not None:
self["name"] = _v
_v = arg.pop("offset", None)
_v = offset if offset is not None else _v
if _v is not None:
self["offset"] = _v
_v = arg.pop("offsetgroup", None)
_v = offsetgroup if offsetgroup is not None else _v
if _v is not None:
self["offsetgroup"] = _v
_v = arg.pop("opacity", None)
_v = opacity if opacity is not None else _v
if _v is not None:
self["opacity"] = _v
_v = arg.pop("orientation", None)
_v = orientation if orientation is not None else _v
if _v is not None:
self["orientation"] = _v
_v = arg.pop("outsidetextfont", None)
_v = outsidetextfont if outsidetextfont is not None else _v
if _v is not None:
self["outsidetextfont"] = _v
_v = arg.pop("selectedpoints", None)
_v = selectedpoints if selectedpoints is not None else _v
if _v is not None:
self["selectedpoints"] = _v
_v = arg.pop("showlegend", None)
_v = showlegend if showlegend is not None else _v
if _v is not None:
self["showlegend"] = _v
_v = arg.pop("stream", None)
_v = stream if stream is not None else _v
if _v is not None:
self["stream"] = _v
_v = arg.pop("text", None)
_v = text if text is not None else _v
if _v is not None:
self["text"] = _v
_v = arg.pop("textangle", None)
_v = textangle if textangle is not None else _v
if _v is not None:
self["textangle"] = _v
_v = arg.pop("textfont", None)
_v = textfont if textfont is not None else _v
if _v is not None:
self["textfont"] = _v
_v = arg.pop("textinfo", None)
_v = textinfo if textinfo is not None else _v
if _v is not None:
self["textinfo"] = _v
_v = arg.pop("textposition", None)
_v = textposition if textposition is not None else _v
if _v is not None:
self["textposition"] = _v
_v = arg.pop("textpositionsrc", None)
_v = textpositionsrc if textpositionsrc is not None else _v
if _v is not None:
self["textpositionsrc"] = _v
_v = arg.pop("textsrc", None)
_v = textsrc if textsrc is not None else _v
if _v is not None:
self["textsrc"] = _v
_v = arg.pop("texttemplate", None)
_v = texttemplate if texttemplate is not None else _v
if _v is not None:
self["texttemplate"] = _v
_v = arg.pop("texttemplatesrc", None)
_v = texttemplatesrc if texttemplatesrc is not None else _v
if _v is not None:
self["texttemplatesrc"] = _v
_v = arg.pop("uid", None)
_v = uid if uid is not None else _v
if _v is not None:
self["uid"] = _v
_v = arg.pop("uirevision", None)
_v = uirevision if uirevision is not None else _v
if _v is not None:
self["uirevision"] = _v
_v = arg.pop("visible", None)
_v = visible if visible is not None else _v
if _v is not None:
self["visible"] = _v
_v = arg.pop("width", None)
_v = width if width is not None else _v
if _v is not None:
self["width"] = _v
_v = arg.pop("x", None)
_v = x if x is not None else _v
if _v is not None:
self["x"] = _v
_v = arg.pop("x0", None)
_v = x0 if x0 is not None else _v
if _v is not None:
self["x0"] = _v
_v = arg.pop("xaxis", None)
_v = xaxis if xaxis is not None else _v
if _v is not None:
self["xaxis"] = _v
_v = arg.pop("xhoverformat", None)
_v = xhoverformat if xhoverformat is not None else _v
if _v is not None:
self["xhoverformat"] = _v
_v = arg.pop("xperiod", None)
_v = xperiod if xperiod is not None else _v
if _v is not None:
self["xperiod"] = _v
_v = arg.pop("xperiod0", None)
_v = xperiod0 if xperiod0 is not None else _v
if _v is not None:
self["xperiod0"] = _v
_v = arg.pop("xperiodalignment", None)
_v = xperiodalignment if xperiodalignment is not None else _v
if _v is not None:
self["xperiodalignment"] = _v
_v = arg.pop("xsrc", None)
_v = xsrc if xsrc is not None else _v
if _v is not None:
self["xsrc"] = _v
_v = arg.pop("y", None)
_v = y if y is not None else _v
if _v is not None:
self["y"] = _v
_v = arg.pop("y0", None)
_v = y0 if y0 is not None else _v
if _v is not None:
self["y0"] = _v
_v = arg.pop("yaxis", None)
_v = yaxis if yaxis is not None else _v
if _v is not None:
self["yaxis"] = _v
_v = arg.pop("yhoverformat", None)
_v = yhoverformat if yhoverformat is not None else _v
if _v is not None:
self["yhoverformat"] = _v
_v = arg.pop("yperiod", None)
_v = yperiod if yperiod is not None else _v
if _v is not None:
self["yperiod"] = _v
_v = arg.pop("yperiod0", None)
_v = yperiod0 if yperiod0 is not None else _v
if _v is not None:
self["yperiod0"] = _v
_v = arg.pop("yperiodalignment", None)
_v = yperiodalignment if yperiodalignment is not None else _v
if _v is not None:
self["yperiodalignment"] = _v
_v = arg.pop("ysrc", None)
_v = ysrc if ysrc is not None else _v
if _v is not None:
self["ysrc"] = _v
_v = arg.pop("zorder", None)
_v = zorder if zorder is not None else _v
if _v is not None:
self["zorder"] = _v
# Read-only literals
# ------------------
self._props["type"] = "funnel"
arg.pop("type", None)
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| _funnel.Funnel.__init__ |
plotly.py | 10 | packages/python/plotly/plotly/graph_objs/_funnel.py | def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.funnel.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Supported dict properties:
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.colorscale`. Has an
effect only if in `marker.color` is set to a
numerical array. In case `colorscale` is
unspecified or `autocolorscale` is true, the
default palette will be chosen according to
whether numbers in the `color` array are all
positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `marker.color`) or the bounds set in
`marker.cmin` and `marker.cmax` Has an effect
only if in `marker.color` is set to a numerical
array. Defaults to `false` when `marker.cmin`
and `marker.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `marker.cmin` and/or `marker.cmax` to
be equidistant to this point. Has an effect
only if in `marker.color` is set to a numerical
array. Value should have the same units as in
`marker.color`. Has no effect when
`marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmax` must be set as well.
color
Sets the marker color. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`marker.cmin` and `marker.cmax` if set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.funnel.marker.Colo
rBar` instance or dict with compatible
properties
colorscale
Sets the colorscale. Has an effect only if in
`marker.color` is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `marker.cmin` and
`marker.cmax`. Alternatively, `colorscale` may
be a palette name string of the following list:
Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud
for `color`.
line
:class:`plotly.graph_objects.funnel.marker.Line
` instance or dict with compatible properties
opacity
Sets the opacity of the bars.
opacitysrc
Sets the source reference on Chart Studio Cloud
for `opacity`.
reversescale
Reverses the color mapping if true. Has an
effect only if in `marker.color` is set to a
numerical array. If true, `marker.cmin` will
correspond to the last color in the array and
`marker.cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
in `marker.color` is set to a numerical array.
Returns
-------
plotly.graph_objs.funnel.Marker
"""
| /usr/src/app/target_test_cases/failed_tests__funnel.marker.txt | def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.funnel.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Supported dict properties:
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.colorscale`. Has an
effect only if in `marker.color` is set to a
numerical array. In case `colorscale` is
unspecified or `autocolorscale` is true, the
default palette will be chosen according to
whether numbers in the `color` array are all
positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `marker.color`) or the bounds set in
`marker.cmin` and `marker.cmax` Has an effect
only if in `marker.color` is set to a numerical
array. Defaults to `false` when `marker.cmin`
and `marker.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `marker.cmin` and/or `marker.cmax` to
be equidistant to this point. Has an effect
only if in `marker.color` is set to a numerical
array. Value should have the same units as in
`marker.color`. Has no effect when
`marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmax` must be set as well.
color
Sets the marker color. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`marker.cmin` and `marker.cmax` if set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.funnel.marker.Colo
rBar` instance or dict with compatible
properties
colorscale
Sets the colorscale. Has an effect only if in
`marker.color` is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `marker.cmin` and
`marker.cmax`. Alternatively, `colorscale` may
be a palette name string of the following list:
Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud
for `color`.
line
:class:`plotly.graph_objects.funnel.marker.Line
` instance or dict with compatible properties
opacity
Sets the opacity of the bars.
opacitysrc
Sets the source reference on Chart Studio Cloud
for `opacity`.
reversescale
Reverses the color mapping if true. Has an
effect only if in `marker.color` is set to a
numerical array. If true, `marker.cmin` will
correspond to the last color in the array and
`marker.cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
in `marker.color` is set to a numerical array.
Returns
-------
plotly.graph_objs.funnel.Marker
"""
return self["marker"]
| _funnel.marker |
plotly.py | 11 | packages/python/plotly/plotly/graph_objs/_funnelarea.py | def __init__(
self,
arg=None,
aspectratio=None,
baseratio=None,
customdata=None,
customdatasrc=None,
dlabel=None,
domain=None,
hoverinfo=None,
hoverinfosrc=None,
hoverlabel=None,
hovertemplate=None,
hovertemplatesrc=None,
hovertext=None,
hovertextsrc=None,
ids=None,
idssrc=None,
insidetextfont=None,
label0=None,
labels=None,
labelssrc=None,
legend=None,
legendgroup=None,
legendgrouptitle=None,
legendrank=None,
legendwidth=None,
marker=None,
meta=None,
metasrc=None,
name=None,
opacity=None,
scalegroup=None,
showlegend=None,
stream=None,
text=None,
textfont=None,
textinfo=None,
textposition=None,
textpositionsrc=None,
textsrc=None,
texttemplate=None,
texttemplatesrc=None,
title=None,
uid=None,
uirevision=None,
values=None,
valuessrc=None,
visible=None,
**kwargs,
):
"""
Construct a new Funnelarea object
Visualize stages in a process using area-encoded trapezoids.
This trace can be used to show data in a part-to-whole
representation similar to a "pie" trace, wherein each item
appears in a single stage. See also the "funnel" trace type for
a different approach to visualizing funnel data.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.Funnelarea`
aspectratio
Sets the ratio between height and width
baseratio
Sets the ratio between bottom length and maximum top
length.
customdata
Assigns extra data each datum. This may be useful when
listening to hover, click and selection events. Note
that, "scatter" traces also appends customdata items in
the markers DOM elements
customdatasrc
Sets the source reference on Chart Studio Cloud for
`customdata`.
dlabel
Sets the label step. See `label0` for more info.
domain
:class:`plotly.graph_objects.funnelarea.Domain`
instance or dict with compatible properties
hoverinfo
Determines which trace information appear on hover. If
`none` or `skip` are set, no information is displayed
upon hovering. But, if `none` is set, click and hover
events are still fired.
hoverinfosrc
Sets the source reference on Chart Studio Cloud for
`hoverinfo`.
hoverlabel
:class:`plotly.graph_objects.funnelarea.Hoverlabel`
instance or dict with compatible properties
hovertemplate
Template string used for rendering the information that
appear on hover box. Note that this will override
`hoverinfo`. Variables are inserted using %{variable},
for example "y: %{y}" as well as %{xother}, {%_xother},
{%_xother_}, {%xother_}. When showing info for several
points, "xother" will be added to those with different
x positions from the first point. An underscore before
or after "(x|y)other" will add a space on that side,
only when this field is shown. Numbers are formatted
using d3-format's syntax %{variable:d3-format}, for
example "Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. The variables available in
`hovertemplate` are the ones emitted as event data
described at this link
https://plotly.com/javascript/plotlyjs-events/#event-
data. Additionally, every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Finally, the template string has access
to variables `label`, `color`, `value`, `text` and
`percent`. Anything contained in tag `<extra>` is
displayed in the secondary box, for example
"<extra>{fullData.name}</extra>". To hide the secondary
box completely, use an empty tag `<extra></extra>`.
hovertemplatesrc
Sets the source reference on Chart Studio Cloud for
`hovertemplate`.
hovertext
Sets hover text elements associated with each sector.
If a single string, the same string appears for all
data points. If an array of string, the items are
mapped in order of this trace's sectors. To be seen,
trace `hoverinfo` must contain a "text" flag.
hovertextsrc
Sets the source reference on Chart Studio Cloud for
`hovertext`.
ids
Assigns id labels to each datum. These ids for object
constancy of data points during animation. Should be an
array of strings, not numbers or any other type.
idssrc
Sets the source reference on Chart Studio Cloud for
`ids`.
insidetextfont
Sets the font used for `textinfo` lying inside the
sector.
label0
Alternate to `labels`. Builds a numeric set of labels.
Use with `dlabel` where `label0` is the starting label
and `dlabel` the step.
labels
Sets the sector labels. If `labels` entries are
duplicated, we sum associated `values` or simply count
occurrences if `values` is not provided. For other
array attributes (including color) we use the first
non-empty entry among all occurrences of the label.
labelssrc
Sets the source reference on Chart Studio Cloud for
`labels`.
legend
Sets the reference to a legend to show this trace in.
References to these legends are "legend", "legend2",
"legend3", etc. Settings for these legends are set in
the layout, under `layout.legend`, `layout.legend2`,
etc.
legendgroup
Sets the legend group for this trace. Traces and shapes
part of the same legend group hide/show at the same
time when toggling legend items.
legendgrouptitle
:class:`plotly.graph_objects.funnelarea.Legendgrouptitl
e` instance or dict with compatible properties
legendrank
Sets the legend rank for this trace. Items and groups
with smaller ranks are presented on top/left side while
with "reversed" `legend.traceorder` they are on
bottom/right side. The default legendrank is 1000, so
that you can use ranks less than 1000 to place certain
items before all unranked items, and ranks greater than
1000 to go after all unranked items. When having
unranked or equal rank items shapes would be displayed
after traces i.e. according to their order in data and
layout.
legendwidth
Sets the width (in px or fraction) of the legend for
this trace.
marker
:class:`plotly.graph_objects.funnelarea.Marker`
instance or dict with compatible properties
meta
Assigns extra meta information associated with this
trace that can be used in various text attributes.
Attributes such as trace `name`, graph, axis and
colorbar `title.text`, annotation `text`
`rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta`
values in an attribute in the same trace, simply use
`%{meta[i]}` where `i` is the index or key of the
`meta` item in question. To access trace `meta` in
layout attributes, use `%{data[n[.meta[i]}` where `i`
is the index or key of the `meta` and `n` is the trace
index.
metasrc
Sets the source reference on Chart Studio Cloud for
`meta`.
name
Sets the trace name. The trace name appears as the
legend item and on hover.
opacity
Sets the opacity of the trace.
scalegroup
If there are multiple funnelareas that should be sized
according to their totals, link them by providing a
non-empty group id here shared by every trace in the
same group.
showlegend
Determines whether or not an item corresponding to this
trace is shown in the legend.
stream
:class:`plotly.graph_objects.funnelarea.Stream`
instance or dict with compatible properties
text
Sets text elements associated with each sector. If
trace `textinfo` contains a "text" flag, these elements
will be seen on the chart. If trace `hoverinfo`
contains a "text" flag and "hovertext" is not set,
these elements will be seen in the hover labels.
textfont
Sets the font used for `textinfo`.
textinfo
Determines which trace information appear on the graph.
textposition
Specifies the location of the `textinfo`.
textpositionsrc
Sets the source reference on Chart Studio Cloud for
`textposition`.
textsrc
Sets the source reference on Chart Studio Cloud for
`text`.
texttemplate
Template string used for rendering the information text
that appear on points. Note that this will override
`textinfo`. Variables are inserted using %{variable},
for example "y: %{y}". Numbers are formatted using
d3-format's syntax %{variable:d3-format}, for example
"Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. Every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Finally, the template string has access
to variables `label`, `color`, `value`, `text` and
`percent`.
texttemplatesrc
Sets the source reference on Chart Studio Cloud for
`texttemplate`.
title
:class:`plotly.graph_objects.funnelarea.Title` instance
or dict with compatible properties
uid
Assign an id to this trace, Use this to provide object
constancy between traces during animations and
transitions.
uirevision
Controls persistence of some user-driven changes to the
trace: `constraintrange` in `parcoords` traces, as well
as some `editable: true` modifications such as `name`
and `colorbar.title`. Defaults to `layout.uirevision`.
Note that other user-driven trace attribute changes are
controlled by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
values
Sets the values of the sectors. If omitted, we count
occurrences of each label.
valuessrc
Sets the source reference on Chart Studio Cloud for
`values`.
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
Returns
-------
Funnelarea
"""
| /usr/src/app/target_test_cases/failed_tests__funnelarea.Funnelarea.__init__.txt | def __init__(
self,
arg=None,
aspectratio=None,
baseratio=None,
customdata=None,
customdatasrc=None,
dlabel=None,
domain=None,
hoverinfo=None,
hoverinfosrc=None,
hoverlabel=None,
hovertemplate=None,
hovertemplatesrc=None,
hovertext=None,
hovertextsrc=None,
ids=None,
idssrc=None,
insidetextfont=None,
label0=None,
labels=None,
labelssrc=None,
legend=None,
legendgroup=None,
legendgrouptitle=None,
legendrank=None,
legendwidth=None,
marker=None,
meta=None,
metasrc=None,
name=None,
opacity=None,
scalegroup=None,
showlegend=None,
stream=None,
text=None,
textfont=None,
textinfo=None,
textposition=None,
textpositionsrc=None,
textsrc=None,
texttemplate=None,
texttemplatesrc=None,
title=None,
uid=None,
uirevision=None,
values=None,
valuessrc=None,
visible=None,
**kwargs,
):
"""
Construct a new Funnelarea object
Visualize stages in a process using area-encoded trapezoids.
This trace can be used to show data in a part-to-whole
representation similar to a "pie" trace, wherein each item
appears in a single stage. See also the "funnel" trace type for
a different approach to visualizing funnel data.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.Funnelarea`
aspectratio
Sets the ratio between height and width
baseratio
Sets the ratio between bottom length and maximum top
length.
customdata
Assigns extra data each datum. This may be useful when
listening to hover, click and selection events. Note
that, "scatter" traces also appends customdata items in
the markers DOM elements
customdatasrc
Sets the source reference on Chart Studio Cloud for
`customdata`.
dlabel
Sets the label step. See `label0` for more info.
domain
:class:`plotly.graph_objects.funnelarea.Domain`
instance or dict with compatible properties
hoverinfo
Determines which trace information appear on hover. If
`none` or `skip` are set, no information is displayed
upon hovering. But, if `none` is set, click and hover
events are still fired.
hoverinfosrc
Sets the source reference on Chart Studio Cloud for
`hoverinfo`.
hoverlabel
:class:`plotly.graph_objects.funnelarea.Hoverlabel`
instance or dict with compatible properties
hovertemplate
Template string used for rendering the information that
appear on hover box. Note that this will override
`hoverinfo`. Variables are inserted using %{variable},
for example "y: %{y}" as well as %{xother}, {%_xother},
{%_xother_}, {%xother_}. When showing info for several
points, "xother" will be added to those with different
x positions from the first point. An underscore before
or after "(x|y)other" will add a space on that side,
only when this field is shown. Numbers are formatted
using d3-format's syntax %{variable:d3-format}, for
example "Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. The variables available in
`hovertemplate` are the ones emitted as event data
described at this link
https://plotly.com/javascript/plotlyjs-events/#event-
data. Additionally, every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Finally, the template string has access
to variables `label`, `color`, `value`, `text` and
`percent`. Anything contained in tag `<extra>` is
displayed in the secondary box, for example
"<extra>{fullData.name}</extra>". To hide the secondary
box completely, use an empty tag `<extra></extra>`.
hovertemplatesrc
Sets the source reference on Chart Studio Cloud for
`hovertemplate`.
hovertext
Sets hover text elements associated with each sector.
If a single string, the same string appears for all
data points. If an array of string, the items are
mapped in order of this trace's sectors. To be seen,
trace `hoverinfo` must contain a "text" flag.
hovertextsrc
Sets the source reference on Chart Studio Cloud for
`hovertext`.
ids
Assigns id labels to each datum. These ids for object
constancy of data points during animation. Should be an
array of strings, not numbers or any other type.
idssrc
Sets the source reference on Chart Studio Cloud for
`ids`.
insidetextfont
Sets the font used for `textinfo` lying inside the
sector.
label0
Alternate to `labels`. Builds a numeric set of labels.
Use with `dlabel` where `label0` is the starting label
and `dlabel` the step.
labels
Sets the sector labels. If `labels` entries are
duplicated, we sum associated `values` or simply count
occurrences if `values` is not provided. For other
array attributes (including color) we use the first
non-empty entry among all occurrences of the label.
labelssrc
Sets the source reference on Chart Studio Cloud for
`labels`.
legend
Sets the reference to a legend to show this trace in.
References to these legends are "legend", "legend2",
"legend3", etc. Settings for these legends are set in
the layout, under `layout.legend`, `layout.legend2`,
etc.
legendgroup
Sets the legend group for this trace. Traces and shapes
part of the same legend group hide/show at the same
time when toggling legend items.
legendgrouptitle
:class:`plotly.graph_objects.funnelarea.Legendgrouptitl
e` instance or dict with compatible properties
legendrank
Sets the legend rank for this trace. Items and groups
with smaller ranks are presented on top/left side while
with "reversed" `legend.traceorder` they are on
bottom/right side. The default legendrank is 1000, so
that you can use ranks less than 1000 to place certain
items before all unranked items, and ranks greater than
1000 to go after all unranked items. When having
unranked or equal rank items shapes would be displayed
after traces i.e. according to their order in data and
layout.
legendwidth
Sets the width (in px or fraction) of the legend for
this trace.
marker
:class:`plotly.graph_objects.funnelarea.Marker`
instance or dict with compatible properties
meta
Assigns extra meta information associated with this
trace that can be used in various text attributes.
Attributes such as trace `name`, graph, axis and
colorbar `title.text`, annotation `text`
`rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta`
values in an attribute in the same trace, simply use
`%{meta[i]}` where `i` is the index or key of the
`meta` item in question. To access trace `meta` in
layout attributes, use `%{data[n[.meta[i]}` where `i`
is the index or key of the `meta` and `n` is the trace
index.
metasrc
Sets the source reference on Chart Studio Cloud for
`meta`.
name
Sets the trace name. The trace name appears as the
legend item and on hover.
opacity
Sets the opacity of the trace.
scalegroup
If there are multiple funnelareas that should be sized
according to their totals, link them by providing a
non-empty group id here shared by every trace in the
same group.
showlegend
Determines whether or not an item corresponding to this
trace is shown in the legend.
stream
:class:`plotly.graph_objects.funnelarea.Stream`
instance or dict with compatible properties
text
Sets text elements associated with each sector. If
trace `textinfo` contains a "text" flag, these elements
will be seen on the chart. If trace `hoverinfo`
contains a "text" flag and "hovertext" is not set,
these elements will be seen in the hover labels.
textfont
Sets the font used for `textinfo`.
textinfo
Determines which trace information appear on the graph.
textposition
Specifies the location of the `textinfo`.
textpositionsrc
Sets the source reference on Chart Studio Cloud for
`textposition`.
textsrc
Sets the source reference on Chart Studio Cloud for
`text`.
texttemplate
Template string used for rendering the information text
that appear on points. Note that this will override
`textinfo`. Variables are inserted using %{variable},
for example "y: %{y}". Numbers are formatted using
d3-format's syntax %{variable:d3-format}, for example
"Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. Every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Finally, the template string has access
to variables `label`, `color`, `value`, `text` and
`percent`.
texttemplatesrc
Sets the source reference on Chart Studio Cloud for
`texttemplate`.
title
:class:`plotly.graph_objects.funnelarea.Title` instance
or dict with compatible properties
uid
Assign an id to this trace, Use this to provide object
constancy between traces during animations and
transitions.
uirevision
Controls persistence of some user-driven changes to the
trace: `constraintrange` in `parcoords` traces, as well
as some `editable: true` modifications such as `name`
and `colorbar.title`. Defaults to `layout.uirevision`.
Note that other user-driven trace attribute changes are
controlled by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
values
Sets the values of the sectors. If omitted, we count
occurrences of each label.
valuessrc
Sets the source reference on Chart Studio Cloud for
`values`.
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
Returns
-------
Funnelarea
"""
super(Funnelarea, self).__init__("funnelarea")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.Funnelarea
constructor must be a dict or
an instance of :class:`plotly.graph_objs.Funnelarea`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("aspectratio", None)
_v = aspectratio if aspectratio is not None else _v
if _v is not None:
self["aspectratio"] = _v
_v = arg.pop("baseratio", None)
_v = baseratio if baseratio is not None else _v
if _v is not None:
self["baseratio"] = _v
_v = arg.pop("customdata", None)
_v = customdata if customdata is not None else _v
if _v is not None:
self["customdata"] = _v
_v = arg.pop("customdatasrc", None)
_v = customdatasrc if customdatasrc is not None else _v
if _v is not None:
self["customdatasrc"] = _v
_v = arg.pop("dlabel", None)
_v = dlabel if dlabel is not None else _v
if _v is not None:
self["dlabel"] = _v
_v = arg.pop("domain", None)
_v = domain if domain is not None else _v
if _v is not None:
self["domain"] = _v
_v = arg.pop("hoverinfo", None)
_v = hoverinfo if hoverinfo is not None else _v
if _v is not None:
self["hoverinfo"] = _v
_v = arg.pop("hoverinfosrc", None)
_v = hoverinfosrc if hoverinfosrc is not None else _v
if _v is not None:
self["hoverinfosrc"] = _v
_v = arg.pop("hoverlabel", None)
_v = hoverlabel if hoverlabel is not None else _v
if _v is not None:
self["hoverlabel"] = _v
_v = arg.pop("hovertemplate", None)
_v = hovertemplate if hovertemplate is not None else _v
if _v is not None:
self["hovertemplate"] = _v
_v = arg.pop("hovertemplatesrc", None)
_v = hovertemplatesrc if hovertemplatesrc is not None else _v
if _v is not None:
self["hovertemplatesrc"] = _v
_v = arg.pop("hovertext", None)
_v = hovertext if hovertext is not None else _v
if _v is not None:
self["hovertext"] = _v
_v = arg.pop("hovertextsrc", None)
_v = hovertextsrc if hovertextsrc is not None else _v
if _v is not None:
self["hovertextsrc"] = _v
_v = arg.pop("ids", None)
_v = ids if ids is not None else _v
if _v is not None:
self["ids"] = _v
_v = arg.pop("idssrc", None)
_v = idssrc if idssrc is not None else _v
if _v is not None:
self["idssrc"] = _v
_v = arg.pop("insidetextfont", None)
_v = insidetextfont if insidetextfont is not None else _v
if _v is not None:
self["insidetextfont"] = _v
_v = arg.pop("label0", None)
_v = label0 if label0 is not None else _v
if _v is not None:
self["label0"] = _v
_v = arg.pop("labels", None)
_v = labels if labels is not None else _v
if _v is not None:
self["labels"] = _v
_v = arg.pop("labelssrc", None)
_v = labelssrc if labelssrc is not None else _v
if _v is not None:
self["labelssrc"] = _v
_v = arg.pop("legend", None)
_v = legend if legend is not None else _v
if _v is not None:
self["legend"] = _v
_v = arg.pop("legendgroup", None)
_v = legendgroup if legendgroup is not None else _v
if _v is not None:
self["legendgroup"] = _v
_v = arg.pop("legendgrouptitle", None)
_v = legendgrouptitle if legendgrouptitle is not None else _v
if _v is not None:
self["legendgrouptitle"] = _v
_v = arg.pop("legendrank", None)
_v = legendrank if legendrank is not None else _v
if _v is not None:
self["legendrank"] = _v
_v = arg.pop("legendwidth", None)
_v = legendwidth if legendwidth is not None else _v
if _v is not None:
self["legendwidth"] = _v
_v = arg.pop("marker", None)
_v = marker if marker is not None else _v
if _v is not None:
self["marker"] = _v
_v = arg.pop("meta", None)
_v = meta if meta is not None else _v
if _v is not None:
self["meta"] = _v
_v = arg.pop("metasrc", None)
_v = metasrc if metasrc is not None else _v
if _v is not None:
self["metasrc"] = _v
_v = arg.pop("name", None)
_v = name if name is not None else _v
if _v is not None:
self["name"] = _v
_v = arg.pop("opacity", None)
_v = opacity if opacity is not None else _v
if _v is not None:
self["opacity"] = _v
_v = arg.pop("scalegroup", None)
_v = scalegroup if scalegroup is not None else _v
if _v is not None:
self["scalegroup"] = _v
_v = arg.pop("showlegend", None)
_v = showlegend if showlegend is not None else _v
if _v is not None:
self["showlegend"] = _v
_v = arg.pop("stream", None)
_v = stream if stream is not None else _v
if _v is not None:
self["stream"] = _v
_v = arg.pop("text", None)
_v = text if text is not None else _v
if _v is not None:
self["text"] = _v
_v = arg.pop("textfont", None)
_v = textfont if textfont is not None else _v
if _v is not None:
self["textfont"] = _v
_v = arg.pop("textinfo", None)
_v = textinfo if textinfo is not None else _v
if _v is not None:
self["textinfo"] = _v
_v = arg.pop("textposition", None)
_v = textposition if textposition is not None else _v
if _v is not None:
self["textposition"] = _v
_v = arg.pop("textpositionsrc", None)
_v = textpositionsrc if textpositionsrc is not None else _v
if _v is not None:
self["textpositionsrc"] = _v
_v = arg.pop("textsrc", None)
_v = textsrc if textsrc is not None else _v
if _v is not None:
self["textsrc"] = _v
_v = arg.pop("texttemplate", None)
_v = texttemplate if texttemplate is not None else _v
if _v is not None:
self["texttemplate"] = _v
_v = arg.pop("texttemplatesrc", None)
_v = texttemplatesrc if texttemplatesrc is not None else _v
if _v is not None:
self["texttemplatesrc"] = _v
_v = arg.pop("title", None)
_v = title if title is not None else _v
if _v is not None:
self["title"] = _v
_v = arg.pop("uid", None)
_v = uid if uid is not None else _v
if _v is not None:
self["uid"] = _v
_v = arg.pop("uirevision", None)
_v = uirevision if uirevision is not None else _v
if _v is not None:
self["uirevision"] = _v
_v = arg.pop("values", None)
_v = values if values is not None else _v
if _v is not None:
self["values"] = _v
_v = arg.pop("valuessrc", None)
_v = valuessrc if valuessrc is not None else _v
if _v is not None:
self["valuessrc"] = _v
_v = arg.pop("visible", None)
_v = visible if visible is not None else _v
if _v is not None:
self["visible"] = _v
# Read-only literals
# ------------------
self._props["type"] = "funnelarea"
arg.pop("type", None)
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| _funnelarea.Funnelarea.__init__ |
plotly.py | 12 | packages/python/plotly/plotly/figure_factory/_gantt.py | def create_gantt(
df,
colors=None,
index_col=None,
show_colorbar=False,
reverse_colors=False,
title="Gantt Chart",
bar_width=0.2,
showgrid_x=False,
showgrid_y=False,
height=600,
width=None,
tasks=None,
task_names=None,
data=None,
group_tasks=False,
show_hover_fill=True,
):
"""
**deprecated**, use instead
:func:`plotly.express.timeline`.
Returns figure for a gantt chart
:param (array|list) df: input data for gantt chart. Must be either a
a dataframe or a list. If dataframe, the columns must include
'Task', 'Start' and 'Finish'. Other columns can be included and
used for indexing. If a list, its elements must be dictionaries
with the same required column headers: 'Task', 'Start' and
'Finish'.
:param (str|list|dict|tuple) colors: either a plotly scale name, an
rgb or hex color, a color tuple or a list of colors. An rgb color
is of the form 'rgb(x, y, z)' where x, y, z belong to the interval
[0, 255] and a color tuple is a tuple of the form (a, b, c) where
a, b and c belong to [0, 1]. If colors is a list, it must
contain the valid color types aforementioned as its members.
If a dictionary, all values of the indexing column must be keys in
colors.
:param (str|float) index_col: the column header (if df is a data
frame) that will function as the indexing column. If df is a list,
index_col must be one of the keys in all the items of df.
:param (bool) show_colorbar: determines if colorbar will be visible.
Only applies if values in the index column are numeric.
:param (bool) show_hover_fill: enables/disables the hovertext for the
filled area of the chart.
:param (bool) reverse_colors: reverses the order of selected colors
:param (str) title: the title of the chart
:param (float) bar_width: the width of the horizontal bars in the plot
:param (bool) showgrid_x: show/hide the x-axis grid
:param (bool) showgrid_y: show/hide the y-axis grid
:param (float) height: the height of the chart
:param (float) width: the width of the chart
Example 1: Simple Gantt Chart
>>> from plotly.figure_factory import create_gantt
>>> # Make data for chart
>>> df = [dict(Task="Job A", Start='2009-01-01', Finish='2009-02-30'),
... dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15'),
... dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30')]
>>> # Create a figure
>>> fig = create_gantt(df)
>>> fig.show()
Example 2: Index by Column with Numerical Entries
>>> from plotly.figure_factory import create_gantt
>>> # Make data for chart
>>> df = [dict(Task="Job A", Start='2009-01-01',
... Finish='2009-02-30', Complete=10),
... dict(Task="Job B", Start='2009-03-05',
... Finish='2009-04-15', Complete=60),
... dict(Task="Job C", Start='2009-02-20',
... Finish='2009-05-30', Complete=95)]
>>> # Create a figure with Plotly colorscale
>>> fig = create_gantt(df, colors='Blues', index_col='Complete',
... show_colorbar=True, bar_width=0.5,
... showgrid_x=True, showgrid_y=True)
>>> fig.show()
Example 3: Index by Column with String Entries
>>> from plotly.figure_factory import create_gantt
>>> # Make data for chart
>>> df = [dict(Task="Job A", Start='2009-01-01',
... Finish='2009-02-30', Resource='Apple'),
... dict(Task="Job B", Start='2009-03-05',
... Finish='2009-04-15', Resource='Grape'),
... dict(Task="Job C", Start='2009-02-20',
... Finish='2009-05-30', Resource='Banana')]
>>> # Create a figure with Plotly colorscale
>>> fig = create_gantt(df, colors=['rgb(200, 50, 25)', (1, 0, 1), '#6c4774'],
... index_col='Resource', reverse_colors=True,
... show_colorbar=True)
>>> fig.show()
Example 4: Use a dictionary for colors
>>> from plotly.figure_factory import create_gantt
>>> # Make data for chart
>>> df = [dict(Task="Job A", Start='2009-01-01',
... Finish='2009-02-30', Resource='Apple'),
... dict(Task="Job B", Start='2009-03-05',
... Finish='2009-04-15', Resource='Grape'),
... dict(Task="Job C", Start='2009-02-20',
... Finish='2009-05-30', Resource='Banana')]
>>> # Make a dictionary of colors
>>> colors = {'Apple': 'rgb(255, 0, 0)',
... 'Grape': 'rgb(170, 14, 200)',
... 'Banana': (1, 1, 0.2)}
>>> # Create a figure with Plotly colorscale
>>> fig = create_gantt(df, colors=colors, index_col='Resource',
... show_colorbar=True)
>>> fig.show()
Example 5: Use a pandas dataframe
>>> from plotly.figure_factory import create_gantt
>>> import pandas as pd
>>> # Make data as a dataframe
>>> df = pd.DataFrame([['Run', '2010-01-01', '2011-02-02', 10],
... ['Fast', '2011-01-01', '2012-06-05', 55],
... ['Eat', '2012-01-05', '2013-07-05', 94]],
... columns=['Task', 'Start', 'Finish', 'Complete'])
>>> # Create a figure with Plotly colorscale
>>> fig = create_gantt(df, colors='Blues', index_col='Complete',
... show_colorbar=True, bar_width=0.5,
... showgrid_x=True, showgrid_y=True)
>>> fig.show()
"""
| /usr/src/app/target_test_cases/failed_tests__gantt.create_gantt.txt | def create_gantt(
df,
colors=None,
index_col=None,
show_colorbar=False,
reverse_colors=False,
title="Gantt Chart",
bar_width=0.2,
showgrid_x=False,
showgrid_y=False,
height=600,
width=None,
tasks=None,
task_names=None,
data=None,
group_tasks=False,
show_hover_fill=True,
):
"""
**deprecated**, use instead
:func:`plotly.express.timeline`.
Returns figure for a gantt chart
:param (array|list) df: input data for gantt chart. Must be either a
a dataframe or a list. If dataframe, the columns must include
'Task', 'Start' and 'Finish'. Other columns can be included and
used for indexing. If a list, its elements must be dictionaries
with the same required column headers: 'Task', 'Start' and
'Finish'.
:param (str|list|dict|tuple) colors: either a plotly scale name, an
rgb or hex color, a color tuple or a list of colors. An rgb color
is of the form 'rgb(x, y, z)' where x, y, z belong to the interval
[0, 255] and a color tuple is a tuple of the form (a, b, c) where
a, b and c belong to [0, 1]. If colors is a list, it must
contain the valid color types aforementioned as its members.
If a dictionary, all values of the indexing column must be keys in
colors.
:param (str|float) index_col: the column header (if df is a data
frame) that will function as the indexing column. If df is a list,
index_col must be one of the keys in all the items of df.
:param (bool) show_colorbar: determines if colorbar will be visible.
Only applies if values in the index column are numeric.
:param (bool) show_hover_fill: enables/disables the hovertext for the
filled area of the chart.
:param (bool) reverse_colors: reverses the order of selected colors
:param (str) title: the title of the chart
:param (float) bar_width: the width of the horizontal bars in the plot
:param (bool) showgrid_x: show/hide the x-axis grid
:param (bool) showgrid_y: show/hide the y-axis grid
:param (float) height: the height of the chart
:param (float) width: the width of the chart
Example 1: Simple Gantt Chart
>>> from plotly.figure_factory import create_gantt
>>> # Make data for chart
>>> df = [dict(Task="Job A", Start='2009-01-01', Finish='2009-02-30'),
... dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15'),
... dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30')]
>>> # Create a figure
>>> fig = create_gantt(df)
>>> fig.show()
Example 2: Index by Column with Numerical Entries
>>> from plotly.figure_factory import create_gantt
>>> # Make data for chart
>>> df = [dict(Task="Job A", Start='2009-01-01',
... Finish='2009-02-30', Complete=10),
... dict(Task="Job B", Start='2009-03-05',
... Finish='2009-04-15', Complete=60),
... dict(Task="Job C", Start='2009-02-20',
... Finish='2009-05-30', Complete=95)]
>>> # Create a figure with Plotly colorscale
>>> fig = create_gantt(df, colors='Blues', index_col='Complete',
... show_colorbar=True, bar_width=0.5,
... showgrid_x=True, showgrid_y=True)
>>> fig.show()
Example 3: Index by Column with String Entries
>>> from plotly.figure_factory import create_gantt
>>> # Make data for chart
>>> df = [dict(Task="Job A", Start='2009-01-01',
... Finish='2009-02-30', Resource='Apple'),
... dict(Task="Job B", Start='2009-03-05',
... Finish='2009-04-15', Resource='Grape'),
... dict(Task="Job C", Start='2009-02-20',
... Finish='2009-05-30', Resource='Banana')]
>>> # Create a figure with Plotly colorscale
>>> fig = create_gantt(df, colors=['rgb(200, 50, 25)', (1, 0, 1), '#6c4774'],
... index_col='Resource', reverse_colors=True,
... show_colorbar=True)
>>> fig.show()
Example 4: Use a dictionary for colors
>>> from plotly.figure_factory import create_gantt
>>> # Make data for chart
>>> df = [dict(Task="Job A", Start='2009-01-01',
... Finish='2009-02-30', Resource='Apple'),
... dict(Task="Job B", Start='2009-03-05',
... Finish='2009-04-15', Resource='Grape'),
... dict(Task="Job C", Start='2009-02-20',
... Finish='2009-05-30', Resource='Banana')]
>>> # Make a dictionary of colors
>>> colors = {'Apple': 'rgb(255, 0, 0)',
... 'Grape': 'rgb(170, 14, 200)',
... 'Banana': (1, 1, 0.2)}
>>> # Create a figure with Plotly colorscale
>>> fig = create_gantt(df, colors=colors, index_col='Resource',
... show_colorbar=True)
>>> fig.show()
Example 5: Use a pandas dataframe
>>> from plotly.figure_factory import create_gantt
>>> import pandas as pd
>>> # Make data as a dataframe
>>> df = pd.DataFrame([['Run', '2010-01-01', '2011-02-02', 10],
... ['Fast', '2011-01-01', '2012-06-05', 55],
... ['Eat', '2012-01-05', '2013-07-05', 94]],
... columns=['Task', 'Start', 'Finish', 'Complete'])
>>> # Create a figure with Plotly colorscale
>>> fig = create_gantt(df, colors='Blues', index_col='Complete',
... show_colorbar=True, bar_width=0.5,
... showgrid_x=True, showgrid_y=True)
>>> fig.show()
"""
# validate gantt input data
chart = validate_gantt(df)
if index_col:
if index_col not in chart[0]:
raise exceptions.PlotlyError(
"In order to use an indexing column and assign colors to "
"the values of the index, you must choose an actual "
"column name in the dataframe or key if a list of "
"dictionaries is being used."
)
# validate gantt index column
index_list = []
for dictionary in chart:
index_list.append(dictionary[index_col])
utils.validate_index(index_list)
# Validate colors
if isinstance(colors, dict):
colors = clrs.validate_colors_dict(colors, "rgb")
else:
colors = clrs.validate_colors(colors, "rgb")
if reverse_colors is True:
colors.reverse()
if not index_col:
if isinstance(colors, dict):
raise exceptions.PlotlyError(
"Error. You have set colors to a dictionary but have not "
"picked an index. An index is required if you are "
"assigning colors to particular values in a dictionary."
)
fig = gantt(
chart,
colors,
title,
bar_width,
showgrid_x,
showgrid_y,
height,
width,
tasks=None,
task_names=None,
data=None,
group_tasks=group_tasks,
show_hover_fill=show_hover_fill,
show_colorbar=show_colorbar,
)
return fig
else:
if not isinstance(colors, dict):
fig = gantt_colorscale(
chart,
colors,
title,
index_col,
show_colorbar,
bar_width,
showgrid_x,
showgrid_y,
height,
width,
tasks=None,
task_names=None,
data=None,
group_tasks=group_tasks,
show_hover_fill=show_hover_fill,
)
return fig
else:
fig = gantt_dict(
chart,
colors,
title,
index_col,
show_colorbar,
bar_width,
showgrid_x,
showgrid_y,
height,
width,
tasks=None,
task_names=None,
data=None,
group_tasks=group_tasks,
show_hover_fill=show_hover_fill,
)
return fig
| _gantt.create_gantt |
plotly.py | 13 | packages/python/plotly/plotly/graph_objs/layout/_grid.py | def __init__(
self,
arg=None,
columns=None,
domain=None,
pattern=None,
roworder=None,
rows=None,
subplots=None,
xaxes=None,
xgap=None,
xside=None,
yaxes=None,
ygap=None,
yside=None,
**kwargs,
):
"""
Construct a new Grid object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.layout.Grid`
columns
The number of columns in the grid. If you provide a 2D
`subplots` array, the length of its longest row is used
as the default. If you give an `xaxes` array, its
length is used as the default. But it's also possible
to have a different length, if you want to leave a row
at the end for non-cartesian subplots.
domain
:class:`plotly.graph_objects.layout.grid.Domain`
instance or dict with compatible properties
pattern
If no `subplots`, `xaxes`, or `yaxes` are given but we
do have `rows` and `columns`, we can generate defaults
using consecutive axis IDs, in two ways: "coupled"
gives one x axis per column and one y axis per row.
"independent" uses a new xy pair for each cell, left-
to-right across each row then iterating rows according
to `roworder`.
roworder
Is the first row the top or the bottom? Note that
columns are always enumerated from left to right.
rows
The number of rows in the grid. If you provide a 2D
`subplots` array or a `yaxes` array, its length is used
as the default. But it's also possible to have a
different length, if you want to leave a row at the end
for non-cartesian subplots.
subplots
Used for freeform grids, where some axes may be shared
across subplots but others are not. Each entry should
be a cartesian subplot id, like "xy" or "x3y2", or ""
to leave that cell empty. You may reuse x axes within
the same column, and y axes within the same row. Non-
cartesian subplots and traces that support `domain` can
place themselves in this grid separately using the
`gridcell` attribute.
xaxes
Used with `yaxes` when the x and y axes are shared
across columns and rows. Each entry should be an x axis
id like "x", "x2", etc., or "" to not put an x axis in
that column. Entries other than "" must be unique.
Ignored if `subplots` is present. If missing but
`yaxes` is present, will generate consecutive IDs.
xgap
Horizontal space between grid cells, expressed as a
fraction of the total width available to one cell.
Defaults to 0.1 for coupled-axes grids and 0.2 for
independent grids.
xside
Sets where the x axis labels and titles go. "bottom"
means the very bottom of the grid. "bottom plot" is the
lowest plot that each x axis is used in. "top" and "top
plot" are similar.
yaxes
Used with `yaxes` when the x and y axes are shared
across columns and rows. Each entry should be an y axis
id like "y", "y2", etc., or "" to not put a y axis in
that row. Entries other than "" must be unique. Ignored
if `subplots` is present. If missing but `xaxes` is
present, will generate consecutive IDs.
ygap
Vertical space between grid cells, expressed as a
fraction of the total height available to one cell.
Defaults to 0.1 for coupled-axes grids and 0.3 for
independent grids.
yside
Sets where the y axis labels and titles go. "left"
means the very left edge of the grid. *left plot* is
the leftmost plot that each y axis is used in. "right"
and *right plot* are similar.
Returns
-------
Grid
"""
| /usr/src/app/target_test_cases/failed_tests__grid.Grid.__init__.txt | def __init__(
self,
arg=None,
columns=None,
domain=None,
pattern=None,
roworder=None,
rows=None,
subplots=None,
xaxes=None,
xgap=None,
xside=None,
yaxes=None,
ygap=None,
yside=None,
**kwargs,
):
"""
Construct a new Grid object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.layout.Grid`
columns
The number of columns in the grid. If you provide a 2D
`subplots` array, the length of its longest row is used
as the default. If you give an `xaxes` array, its
length is used as the default. But it's also possible
to have a different length, if you want to leave a row
at the end for non-cartesian subplots.
domain
:class:`plotly.graph_objects.layout.grid.Domain`
instance or dict with compatible properties
pattern
If no `subplots`, `xaxes`, or `yaxes` are given but we
do have `rows` and `columns`, we can generate defaults
using consecutive axis IDs, in two ways: "coupled"
gives one x axis per column and one y axis per row.
"independent" uses a new xy pair for each cell, left-
to-right across each row then iterating rows according
to `roworder`.
roworder
Is the first row the top or the bottom? Note that
columns are always enumerated from left to right.
rows
The number of rows in the grid. If you provide a 2D
`subplots` array or a `yaxes` array, its length is used
as the default. But it's also possible to have a
different length, if you want to leave a row at the end
for non-cartesian subplots.
subplots
Used for freeform grids, where some axes may be shared
across subplots but others are not. Each entry should
be a cartesian subplot id, like "xy" or "x3y2", or ""
to leave that cell empty. You may reuse x axes within
the same column, and y axes within the same row. Non-
cartesian subplots and traces that support `domain` can
place themselves in this grid separately using the
`gridcell` attribute.
xaxes
Used with `yaxes` when the x and y axes are shared
across columns and rows. Each entry should be an x axis
id like "x", "x2", etc., or "" to not put an x axis in
that column. Entries other than "" must be unique.
Ignored if `subplots` is present. If missing but
`yaxes` is present, will generate consecutive IDs.
xgap
Horizontal space between grid cells, expressed as a
fraction of the total width available to one cell.
Defaults to 0.1 for coupled-axes grids and 0.2 for
independent grids.
xside
Sets where the x axis labels and titles go. "bottom"
means the very bottom of the grid. "bottom plot" is the
lowest plot that each x axis is used in. "top" and "top
plot" are similar.
yaxes
Used with `yaxes` when the x and y axes are shared
across columns and rows. Each entry should be an y axis
id like "y", "y2", etc., or "" to not put a y axis in
that row. Entries other than "" must be unique. Ignored
if `subplots` is present. If missing but `xaxes` is
present, will generate consecutive IDs.
ygap
Vertical space between grid cells, expressed as a
fraction of the total height available to one cell.
Defaults to 0.1 for coupled-axes grids and 0.3 for
independent grids.
yside
Sets where the y axis labels and titles go. "left"
means the very left edge of the grid. *left plot* is
the leftmost plot that each y axis is used in. "right"
and *right plot* are similar.
Returns
-------
Grid
"""
super(Grid, self).__init__("grid")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.layout.Grid
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.Grid`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("columns", None)
_v = columns if columns is not None else _v
if _v is not None:
self["columns"] = _v
_v = arg.pop("domain", None)
_v = domain if domain is not None else _v
if _v is not None:
self["domain"] = _v
_v = arg.pop("pattern", None)
_v = pattern if pattern is not None else _v
if _v is not None:
self["pattern"] = _v
_v = arg.pop("roworder", None)
_v = roworder if roworder is not None else _v
if _v is not None:
self["roworder"] = _v
_v = arg.pop("rows", None)
_v = rows if rows is not None else _v
if _v is not None:
self["rows"] = _v
_v = arg.pop("subplots", None)
_v = subplots if subplots is not None else _v
if _v is not None:
self["subplots"] = _v
_v = arg.pop("xaxes", None)
_v = xaxes if xaxes is not None else _v
if _v is not None:
self["xaxes"] = _v
_v = arg.pop("xgap", None)
_v = xgap if xgap is not None else _v
if _v is not None:
self["xgap"] = _v
_v = arg.pop("xside", None)
_v = xside if xside is not None else _v
if _v is not None:
self["xside"] = _v
_v = arg.pop("yaxes", None)
_v = yaxes if yaxes is not None else _v
if _v is not None:
self["yaxes"] = _v
_v = arg.pop("ygap", None)
_v = ygap if ygap is not None else _v
if _v is not None:
self["ygap"] = _v
_v = arg.pop("yside", None)
_v = yside if yside is not None else _v
if _v is not None:
self["yside"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| _grid.Grid.__init__ |
plotly.py | 14 | packages/python/plotly/plotly/graph_objs/_histogram.py | def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.histogram.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Supported dict properties:
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.colorscale`. Has an
effect only if in `marker.color` is set to a
numerical array. In case `colorscale` is
unspecified or `autocolorscale` is true, the
default palette will be chosen according to
whether numbers in the `color` array are all
positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `marker.color`) or the bounds set in
`marker.cmin` and `marker.cmax` Has an effect
only if in `marker.color` is set to a numerical
array. Defaults to `false` when `marker.cmin`
and `marker.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `marker.cmin` and/or `marker.cmax` to
be equidistant to this point. Has an effect
only if in `marker.color` is set to a numerical
array. Value should have the same units as in
`marker.color`. Has no effect when
`marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmax` must be set as well.
color
Sets the marker color. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`marker.cmin` and `marker.cmax` if set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.histogram.marker.C
olorBar` instance or dict with compatible
properties
colorscale
Sets the colorscale. Has an effect only if in
`marker.color` is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `marker.cmin` and
`marker.cmax`. Alternatively, `colorscale` may
be a palette name string of the following list:
Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud
for `color`.
cornerradius
Sets the rounding of corners. May be an integer
number of pixels, or a percentage of bar width
(as a string ending in %). Defaults to
`layout.barcornerradius`. In stack or relative
barmode, the first trace to set cornerradius is
used for the whole stack.
line
:class:`plotly.graph_objects.histogram.marker.L
ine` instance or dict with compatible
properties
opacity
Sets the opacity of the bars.
opacitysrc
Sets the source reference on Chart Studio Cloud
for `opacity`.
pattern
Sets the pattern within the marker.
reversescale
Reverses the color mapping if true. Has an
effect only if in `marker.color` is set to a
numerical array. If true, `marker.cmin` will
correspond to the last color in the array and
`marker.cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
in `marker.color` is set to a numerical array.
Returns
-------
plotly.graph_objs.histogram.Marker
"""
| /usr/src/app/target_test_cases/failed_tests__histogram.marker.txt | def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.histogram.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Supported dict properties:
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.colorscale`. Has an
effect only if in `marker.color` is set to a
numerical array. In case `colorscale` is
unspecified or `autocolorscale` is true, the
default palette will be chosen according to
whether numbers in the `color` array are all
positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `marker.color`) or the bounds set in
`marker.cmin` and `marker.cmax` Has an effect
only if in `marker.color` is set to a numerical
array. Defaults to `false` when `marker.cmin`
and `marker.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `marker.cmin` and/or `marker.cmax` to
be equidistant to this point. Has an effect
only if in `marker.color` is set to a numerical
array. Value should have the same units as in
`marker.color`. Has no effect when
`marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmax` must be set as well.
color
Sets the marker color. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`marker.cmin` and `marker.cmax` if set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.histogram.marker.C
olorBar` instance or dict with compatible
properties
colorscale
Sets the colorscale. Has an effect only if in
`marker.color` is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `marker.cmin` and
`marker.cmax`. Alternatively, `colorscale` may
be a palette name string of the following list:
Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud
for `color`.
cornerradius
Sets the rounding of corners. May be an integer
number of pixels, or a percentage of bar width
(as a string ending in %). Defaults to
`layout.barcornerradius`. In stack or relative
barmode, the first trace to set cornerradius is
used for the whole stack.
line
:class:`plotly.graph_objects.histogram.marker.L
ine` instance or dict with compatible
properties
opacity
Sets the opacity of the bars.
opacitysrc
Sets the source reference on Chart Studio Cloud
for `opacity`.
pattern
Sets the pattern within the marker.
reversescale
Reverses the color mapping if true. Has an
effect only if in `marker.color` is set to a
numerical array. If true, `marker.cmin` will
correspond to the last color in the array and
`marker.cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
in `marker.color` is set to a numerical array.
Returns
-------
plotly.graph_objs.histogram.Marker
"""
return self["marker"]
| _histogram.marker |
plotly.py | 15 | packages/python/plotly/plotly/io/_html.py | def to_html(
fig,
config=None,
auto_play=True,
include_plotlyjs=True,
include_mathjax=False,
post_script=None,
full_html=True,
animation_opts=None,
default_width="100%",
default_height="100%",
validate=True,
div_id=None,
):
"""
Convert a figure to an HTML string representation.
Parameters
----------
fig:
Figure object or dict representing a figure
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. The url used is versioned to match the bundled plotly.js.
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, 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
-------
str
Representation of figure as an HTML div string
"""
| /usr/src/app/target_test_cases/failed_tests__html.to_html.txt | def to_html(
fig,
config=None,
auto_play=True,
include_plotlyjs=True,
include_mathjax=False,
post_script=None,
full_html=True,
animation_opts=None,
default_width="100%",
default_height="100%",
validate=True,
div_id=None,
):
"""
Convert a figure to an HTML string representation.
Parameters
----------
fig:
Figure object or dict representing a figure
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. The url used is versioned to match the bundled plotly.js.
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, 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
-------
str
Representation of figure as an HTML div string
"""
from plotly.io.json import to_json_plotly
# ## Validate figure ##
fig_dict = validate_coerce_fig_to_dict(fig, validate)
# ## Generate div id ##
plotdivid = div_id or str(uuid.uuid4())
# ## Serialize figure ##
jdata = to_json_plotly(fig_dict.get("data", []))
jlayout = to_json_plotly(fig_dict.get("layout", {}))
if fig_dict.get("frames", None):
jframes = to_json_plotly(fig_dict.get("frames", []))
else:
jframes = None
# ## Serialize figure config ##
config = _get_jconfig(config)
# Set responsive
config.setdefault("responsive", True)
# Get div width/height
layout_dict = fig_dict.get("layout", {})
template_dict = fig_dict.get("layout", {}).get("template", {}).get("layout", {})
div_width = layout_dict.get("width", template_dict.get("width", default_width))
div_height = layout_dict.get("height", template_dict.get("height", default_height))
# Add 'px' suffix to numeric widths
try:
float(div_width)
except (ValueError, TypeError):
pass
else:
div_width = str(div_width) + "px"
try:
float(div_height)
except (ValueError, TypeError):
pass
else:
div_height = str(div_height) + "px"
# ## Get platform URL ##
if config.get("showLink", False) or config.get("showSendToCloud", False):
# Figure is going to include a Chart Studio link or send-to-cloud button,
# So we need to configure the PLOTLYENV.BASE_URL property
base_url_line = """
window.PLOTLYENV.BASE_URL='{plotly_platform_url}';\
""".format(
plotly_platform_url=config.get("plotlyServerURL", "https://plot.ly")
)
else:
# Figure is not going to include a Chart Studio link or send-to-cloud button,
# In this case we don't want https://plot.ly to show up anywhere in the HTML
# output
config.pop("plotlyServerURL", None)
config.pop("linkText", None)
config.pop("showLink", None)
base_url_line = ""
# ## Build script body ##
# This is the part that actually calls Plotly.js
# build post script snippet(s)
then_post_script = ""
if post_script:
if not isinstance(post_script, (list, tuple)):
post_script = [post_script]
for ps in post_script:
then_post_script += """.then(function(){{
{post_script}
}})""".format(
post_script=ps.replace("{plot_id}", plotdivid)
)
then_addframes = ""
then_animate = ""
if jframes:
then_addframes = """.then(function(){{
Plotly.addFrames('{id}', {frames});
}})""".format(
id=plotdivid, frames=jframes
)
if auto_play:
if animation_opts:
animation_opts_arg = ", " + _json.dumps(animation_opts)
else:
animation_opts_arg = ""
then_animate = """.then(function(){{
Plotly.animate('{id}', null{animation_opts});
}})""".format(
id=plotdivid, animation_opts=animation_opts_arg
)
# Serialize config dict to JSON
jconfig = _json.dumps(config)
script = """\
if (document.getElementById("{id}")) {{\
Plotly.newPlot(\
"{id}",\
{data},\
{layout},\
{config}\
){then_addframes}{then_animate}{then_post_script}\
}}""".format(
id=plotdivid,
data=jdata,
layout=jlayout,
config=jconfig,
then_addframes=then_addframes,
then_animate=then_animate,
then_post_script=then_post_script,
)
# ## Handle loading/initializing plotly.js ##
include_plotlyjs_orig = include_plotlyjs
if isinstance(include_plotlyjs, str):
include_plotlyjs = include_plotlyjs.lower()
# Start/end of requirejs block (if any)
require_start = ""
require_end = ""
# Init and load
load_plotlyjs = ""
# Init plotlyjs. This block needs to run before plotly.js is loaded in
# order for MathJax configuration to work properly
if include_plotlyjs == "require":
require_start = 'require(["plotly"], function(Plotly) {'
require_end = "});"
elif include_plotlyjs == "cdn":
load_plotlyjs = """\
{win_config}
<script charset="utf-8" src="{cdn_url}"></script>\
""".format(
win_config=_window_plotly_config, cdn_url=plotly_cdn_url()
)
elif include_plotlyjs == "directory":
load_plotlyjs = """\
{win_config}
<script charset="utf-8" src="plotly.min.js"></script>\
""".format(
win_config=_window_plotly_config
)
elif isinstance(include_plotlyjs, str) and include_plotlyjs.endswith(".js"):
load_plotlyjs = """\
{win_config}
<script charset="utf-8" src="{url}"></script>\
""".format(
win_config=_window_plotly_config, url=include_plotlyjs_orig
)
elif include_plotlyjs:
load_plotlyjs = """\
{win_config}
<script type="text/javascript">{plotlyjs}</script>\
""".format(
win_config=_window_plotly_config, plotlyjs=get_plotlyjs()
)
# ## Handle loading/initializing MathJax ##
include_mathjax_orig = include_mathjax
if isinstance(include_mathjax, str):
include_mathjax = include_mathjax.lower()
mathjax_template = """\
<script src="{url}?config=TeX-AMS-MML_SVG"></script>"""
if include_mathjax == "cdn":
mathjax_script = (
mathjax_template.format(
url=(
"https://cdnjs.cloudflare.com" "/ajax/libs/mathjax/2.7.5/MathJax.js"
)
)
+ _mathjax_config
)
elif isinstance(include_mathjax, str) and include_mathjax.endswith(".js"):
mathjax_script = (
mathjax_template.format(url=include_mathjax_orig) + _mathjax_config
)
elif not include_mathjax:
mathjax_script = ""
else:
raise ValueError(
"""\
Invalid value of type {typ} received as the include_mathjax argument
Received value: {val}
include_mathjax may be specified as False, 'cdn', or a string ending with '.js'
""".format(
typ=type(include_mathjax), val=repr(include_mathjax)
)
)
plotly_html_div = """\
<div>\
{mathjax_script}\
{load_plotlyjs}\
<div id="{id}" class="plotly-graph-div" \
style="height:{height}; width:{width};"></div>\
<script type="text/javascript">\
{require_start}\
window.PLOTLYENV=window.PLOTLYENV || {{}};{base_url_line}\
{script};\
{require_end}\
</script>\
</div>""".format(
mathjax_script=mathjax_script,
load_plotlyjs=load_plotlyjs,
id=plotdivid,
width=div_width,
height=div_height,
base_url_line=base_url_line,
require_start=require_start,
script=script,
require_end=require_end,
).strip()
if full_html:
return """\
<html>
<head><meta charset="utf-8" /></head>
<body>
{div}
</body>
</html>""".format(
div=plotly_html_div
)
else:
return plotly_html_div
| _html.to_html |
plotly.py | 16 | packages/python/plotly/plotly/io/_html.py | def write_html(
fig,
file,
config=None,
auto_play=True,
include_plotlyjs=True,
include_mathjax=False,
post_script=None,
full_html=True,
animation_opts=None,
validate=True,
default_width="100%",
default_height="100%",
auto_open=False,
div_id=None,
):
"""
Write a figure to an HTML file representation
Parameters
----------
fig:
Figure object or dict representing a figure
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. The url used is versioned to match the bundled plotly.js.
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 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, 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
-------
str
Representation of figure as an HTML div string
"""
| /usr/src/app/target_test_cases/failed_tests__html.write_html.txt | def write_html(
fig,
file,
config=None,
auto_play=True,
include_plotlyjs=True,
include_mathjax=False,
post_script=None,
full_html=True,
animation_opts=None,
validate=True,
default_width="100%",
default_height="100%",
auto_open=False,
div_id=None,
):
"""
Write a figure to an HTML file representation
Parameters
----------
fig:
Figure object or dict representing a figure
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. The url used is versioned to match the bundled plotly.js.
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 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, 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
-------
str
Representation of figure as an HTML div string
"""
# Build HTML string
html_str = to_html(
fig,
config=config,
auto_play=auto_play,
include_plotlyjs=include_plotlyjs,
include_mathjax=include_mathjax,
post_script=post_script,
full_html=full_html,
animation_opts=animation_opts,
default_width=default_width,
default_height=default_height,
validate=validate,
div_id=div_id,
)
# Check if file is a string
if isinstance(file, str):
# Use the standard pathlib constructor to make a pathlib object.
path = Path(file)
elif isinstance(file, Path): # PurePath is the most general pathlib object.
# `file` is already a pathlib object.
path = file
else:
# We could not make a pathlib object out of file. Either `file` is an open file
# descriptor with a `write()` method or it's an invalid object.
path = None
# Write HTML string
if path is not None:
# To use a different file encoding, pass a file descriptor
path.write_text(html_str, "utf-8")
else:
file.write(html_str)
# Check if we should copy plotly.min.js to output directory
if path is not None and full_html and include_plotlyjs == "directory":
bundle_path = path.parent / "plotly.min.js"
if not bundle_path.exists():
bundle_path.write_text(get_plotlyjs(), encoding="utf-8")
# Handle auto_open
if path is not None and full_html and auto_open:
url = path.absolute().as_uri()
webbrowser.open(url)
| _html.write_html |
plotly.py | 17 | packages/python/plotly/plotly/express/_imshow.py | def imshow(
img,
zmin=None,
zmax=None,
origin=None,
labels={},
x=None,
y=None,
animation_frame=None,
facet_col=None,
facet_col_wrap=None,
facet_col_spacing=None,
facet_row_spacing=None,
color_continuous_scale=None,
color_continuous_midpoint=None,
range_color=None,
title=None,
template=None,
width=None,
height=None,
aspect=None,
contrast_rescaling=None,
binary_string=None,
binary_backend="auto",
binary_compression_level=4,
binary_format="png",
text_auto=False,
) -> go.Figure:
"""
Display an image, i.e. data on a 2D regular raster.
Parameters
----------
img: array-like image, or xarray
The image data. Supported array shapes are
- (M, N): an image with scalar data. The data is visualized
using a colormap.
- (M, N, 3): an image with RGB values.
- (M, N, 4): an image with RGBA values, i.e. including transparency.
zmin, zmax : scalar or iterable, optional
zmin and zmax define the scalar range that the colormap covers. By default,
zmin and zmax correspond to the min and max values of the datatype for integer
datatypes (ie [0-255] for uint8 images, [0, 65535] for uint16 images, etc.). For
a multichannel image of floats, the max of the image is computed and zmax is the
smallest power of 256 (1, 255, 65535) greater than this max value,
with a 5% tolerance. For a single-channel image, the max of the image is used.
Overridden by range_color.
origin : str, 'upper' or 'lower' (default 'upper')
position of the [0, 0] pixel of the image array, in the upper left or lower left
corner. The convention 'upper' is typically used for matrices and images.
labels : dict with str keys and str values (default `{}`)
Sets names used in the figure for axis titles (keys ``x`` and ``y``),
colorbar title and hoverlabel (key ``color``). The values should correspond
to the desired label to be displayed. If ``img`` is an xarray, dimension
names are used for axis titles, and long name for the colorbar title
(unless overridden in ``labels``). Possible keys are: x, y, and color.
x, y: list-like, optional
x and y are used to label the axes of single-channel heatmap visualizations and
their lengths must match the lengths of the second and first dimensions of the
img argument. They are auto-populated if the input is an xarray.
animation_frame: int or str, optional (default None)
axis number along which the image array is sliced to create an animation plot.
If `img` is an xarray, `animation_frame` can be the name of one the dimensions.
facet_col: int or str, optional (default None)
axis number along which the image array is sliced to create a facetted plot.
If `img` is an xarray, `facet_col` can be the name of one the dimensions.
facet_col_wrap: int
Maximum number of facet columns. Wraps the column variable at this width,
so that the column facets span multiple rows.
Ignored if `facet_col` is None.
facet_col_spacing: float between 0 and 1
Spacing between facet columns, in paper units. Default is 0.02.
facet_row_spacing: float between 0 and 1
Spacing between facet rows created when ``facet_col_wrap`` is used, in
paper units. Default is 0.0.7.
color_continuous_scale : str or list of str
colormap used to map scalar data to colors (for a 2D image). This parameter is
not used for RGB or RGBA images. If a string is provided, it should be the name
of a known color scale, and if a list is provided, it should be a list of CSS-
compatible colors.
color_continuous_midpoint : number
If set, computes the bounds of the continuous color scale to have the desired
midpoint. Overridden by range_color or zmin and zmax.
range_color : list of two numbers
If provided, overrides auto-scaling on the continuous color scale, including
overriding `color_continuous_midpoint`. Also overrides zmin and zmax. Used only
for single-channel images.
title : str
The figure title.
template : str or dict or plotly.graph_objects.layout.Template instance
The figure template name or definition.
width : number
The figure width in pixels.
height: number
The figure height in pixels.
aspect: 'equal', 'auto', or None
- 'equal': Ensures an aspect ratio of 1 or pixels (square pixels)
- 'auto': The axes is kept fixed and the aspect ratio of pixels is
adjusted so that the data fit in the axes. In general, this will
result in non-square pixels.
- if None, 'equal' is used for numpy arrays and 'auto' for xarrays
(which have typically heterogeneous coordinates)
contrast_rescaling: 'minmax', 'infer', or None
how to determine data values corresponding to the bounds of the color
range, when zmin or zmax are not passed. If `minmax`, the min and max
values of the image are used. If `infer`, a heuristic based on the image
data type is used.
binary_string: bool, default None
if True, the image data are first rescaled and encoded as uint8 and
then passed to plotly.js as a b64 PNG string. If False, data are passed
unchanged as a numerical array. Setting to True may lead to performance
gains, at the cost of a loss of precision depending on the original data
type. If None, use_binary_string is set to True for multichannel (eg) RGB
arrays, and to False for single-channel (2D) arrays. 2D arrays are
represented as grayscale and with no colorbar if use_binary_string is
True.
binary_backend: str, 'auto' (default), 'pil' or 'pypng'
Third-party package for the transformation of numpy arrays to
png b64 strings. If 'auto', Pillow is used if installed, otherwise
pypng.
binary_compression_level: int, between 0 and 9 (default 4)
png compression level to be passed to the backend when transforming an
array to a png b64 string. Increasing `binary_compression` decreases the
size of the png string, but the compression step takes more time. For most
images it is not worth using levels greater than 5, but it's possible to
test `len(fig.data[0].source)` and to time the execution of `imshow` to
tune the level of compression. 0 means no compression (not recommended).
binary_format: str, 'png' (default) or 'jpg'
compression format used to generate b64 string. 'png' is recommended
since it uses lossless compression, but 'jpg' (lossy) compression can
result if smaller binary strings for natural images.
text_auto: bool or str (default `False`)
If `True` or a string, single-channel `img` values will be displayed as text.
A string like `'.2f'` will be interpreted as a `texttemplate` numeric formatting directive.
Returns
-------
fig : graph_objects.Figure containing the displayed image
See also
--------
plotly.graph_objects.Image : image trace
plotly.graph_objects.Heatmap : heatmap trace
Notes
-----
In order to update and customize the returned figure, use
`go.Figure.update_traces` or `go.Figure.update_layout`.
If an xarray is passed, dimensions names and coordinates are used for
axes labels and ticks.
"""
| /usr/src/app/target_test_cases/failed_tests__imshow.imshow.txt | def imshow(
img,
zmin=None,
zmax=None,
origin=None,
labels={},
x=None,
y=None,
animation_frame=None,
facet_col=None,
facet_col_wrap=None,
facet_col_spacing=None,
facet_row_spacing=None,
color_continuous_scale=None,
color_continuous_midpoint=None,
range_color=None,
title=None,
template=None,
width=None,
height=None,
aspect=None,
contrast_rescaling=None,
binary_string=None,
binary_backend="auto",
binary_compression_level=4,
binary_format="png",
text_auto=False,
) -> go.Figure:
"""
Display an image, i.e. data on a 2D regular raster.
Parameters
----------
img: array-like image, or xarray
The image data. Supported array shapes are
- (M, N): an image with scalar data. The data is visualized
using a colormap.
- (M, N, 3): an image with RGB values.
- (M, N, 4): an image with RGBA values, i.e. including transparency.
zmin, zmax : scalar or iterable, optional
zmin and zmax define the scalar range that the colormap covers. By default,
zmin and zmax correspond to the min and max values of the datatype for integer
datatypes (ie [0-255] for uint8 images, [0, 65535] for uint16 images, etc.). For
a multichannel image of floats, the max of the image is computed and zmax is the
smallest power of 256 (1, 255, 65535) greater than this max value,
with a 5% tolerance. For a single-channel image, the max of the image is used.
Overridden by range_color.
origin : str, 'upper' or 'lower' (default 'upper')
position of the [0, 0] pixel of the image array, in the upper left or lower left
corner. The convention 'upper' is typically used for matrices and images.
labels : dict with str keys and str values (default `{}`)
Sets names used in the figure for axis titles (keys ``x`` and ``y``),
colorbar title and hoverlabel (key ``color``). The values should correspond
to the desired label to be displayed. If ``img`` is an xarray, dimension
names are used for axis titles, and long name for the colorbar title
(unless overridden in ``labels``). Possible keys are: x, y, and color.
x, y: list-like, optional
x and y are used to label the axes of single-channel heatmap visualizations and
their lengths must match the lengths of the second and first dimensions of the
img argument. They are auto-populated if the input is an xarray.
animation_frame: int or str, optional (default None)
axis number along which the image array is sliced to create an animation plot.
If `img` is an xarray, `animation_frame` can be the name of one the dimensions.
facet_col: int or str, optional (default None)
axis number along which the image array is sliced to create a facetted plot.
If `img` is an xarray, `facet_col` can be the name of one the dimensions.
facet_col_wrap: int
Maximum number of facet columns. Wraps the column variable at this width,
so that the column facets span multiple rows.
Ignored if `facet_col` is None.
facet_col_spacing: float between 0 and 1
Spacing between facet columns, in paper units. Default is 0.02.
facet_row_spacing: float between 0 and 1
Spacing between facet rows created when ``facet_col_wrap`` is used, in
paper units. Default is 0.0.7.
color_continuous_scale : str or list of str
colormap used to map scalar data to colors (for a 2D image). This parameter is
not used for RGB or RGBA images. If a string is provided, it should be the name
of a known color scale, and if a list is provided, it should be a list of CSS-
compatible colors.
color_continuous_midpoint : number
If set, computes the bounds of the continuous color scale to have the desired
midpoint. Overridden by range_color or zmin and zmax.
range_color : list of two numbers
If provided, overrides auto-scaling on the continuous color scale, including
overriding `color_continuous_midpoint`. Also overrides zmin and zmax. Used only
for single-channel images.
title : str
The figure title.
template : str or dict or plotly.graph_objects.layout.Template instance
The figure template name or definition.
width : number
The figure width in pixels.
height: number
The figure height in pixels.
aspect: 'equal', 'auto', or None
- 'equal': Ensures an aspect ratio of 1 or pixels (square pixels)
- 'auto': The axes is kept fixed and the aspect ratio of pixels is
adjusted so that the data fit in the axes. In general, this will
result in non-square pixels.
- if None, 'equal' is used for numpy arrays and 'auto' for xarrays
(which have typically heterogeneous coordinates)
contrast_rescaling: 'minmax', 'infer', or None
how to determine data values corresponding to the bounds of the color
range, when zmin or zmax are not passed. If `minmax`, the min and max
values of the image are used. If `infer`, a heuristic based on the image
data type is used.
binary_string: bool, default None
if True, the image data are first rescaled and encoded as uint8 and
then passed to plotly.js as a b64 PNG string. If False, data are passed
unchanged as a numerical array. Setting to True may lead to performance
gains, at the cost of a loss of precision depending on the original data
type. If None, use_binary_string is set to True for multichannel (eg) RGB
arrays, and to False for single-channel (2D) arrays. 2D arrays are
represented as grayscale and with no colorbar if use_binary_string is
True.
binary_backend: str, 'auto' (default), 'pil' or 'pypng'
Third-party package for the transformation of numpy arrays to
png b64 strings. If 'auto', Pillow is used if installed, otherwise
pypng.
binary_compression_level: int, between 0 and 9 (default 4)
png compression level to be passed to the backend when transforming an
array to a png b64 string. Increasing `binary_compression` decreases the
size of the png string, but the compression step takes more time. For most
images it is not worth using levels greater than 5, but it's possible to
test `len(fig.data[0].source)` and to time the execution of `imshow` to
tune the level of compression. 0 means no compression (not recommended).
binary_format: str, 'png' (default) or 'jpg'
compression format used to generate b64 string. 'png' is recommended
since it uses lossless compression, but 'jpg' (lossy) compression can
result if smaller binary strings for natural images.
text_auto: bool or str (default `False`)
If `True` or a string, single-channel `img` values will be displayed as text.
A string like `'.2f'` will be interpreted as a `texttemplate` numeric formatting directive.
Returns
-------
fig : graph_objects.Figure containing the displayed image
See also
--------
plotly.graph_objects.Image : image trace
plotly.graph_objects.Heatmap : heatmap trace
Notes
-----
In order to update and customize the returned figure, use
`go.Figure.update_traces` or `go.Figure.update_layout`.
If an xarray is passed, dimensions names and coordinates are used for
axes labels and ticks.
"""
args = locals()
apply_default_cascade(args)
labels = labels.copy()
nslices_facet = 1
if facet_col is not None:
if isinstance(facet_col, str):
facet_col = img.dims.index(facet_col)
nslices_facet = img.shape[facet_col]
facet_slices = range(nslices_facet)
ncols = int(facet_col_wrap) if facet_col_wrap is not None else nslices_facet
nrows = (
nslices_facet // ncols + 1
if nslices_facet % ncols
else nslices_facet // ncols
)
else:
nrows = 1
ncols = 1
if animation_frame is not None:
if isinstance(animation_frame, str):
animation_frame = img.dims.index(animation_frame)
nslices_animation = img.shape[animation_frame]
animation_slices = range(nslices_animation)
slice_dimensions = (facet_col is not None) + (
animation_frame is not None
) # 0, 1, or 2
facet_label = None
animation_label = None
img_is_xarray = False
# ----- Define x and y, set labels if img is an xarray -------------------
if xarray_imported and isinstance(img, xarray.DataArray):
dims = list(img.dims)
img_is_xarray = True
pop_indexes = []
if facet_col is not None:
facet_slices = img.coords[img.dims[facet_col]].values
pop_indexes.append(facet_col)
facet_label = img.dims[facet_col]
if animation_frame is not None:
animation_slices = img.coords[img.dims[animation_frame]].values
pop_indexes.append(animation_frame)
animation_label = img.dims[animation_frame]
# Remove indices in sorted order.
for index in sorted(pop_indexes, reverse=True):
_ = dims.pop(index)
y_label, x_label = dims[0], dims[1]
# np.datetime64 is not handled correctly by go.Heatmap
for ax in [x_label, y_label]:
if np.issubdtype(img.coords[ax].dtype, np.datetime64):
img.coords[ax] = img.coords[ax].astype(str)
if x is None:
x = img.coords[x_label].values
if y is None:
y = img.coords[y_label].values
if aspect is None:
aspect = "auto"
if labels.get("x", None) is None:
labels["x"] = x_label
if labels.get("y", None) is None:
labels["y"] = y_label
if labels.get("animation_frame", None) is None:
labels["animation_frame"] = animation_label
if labels.get("facet_col", None) is None:
labels["facet_col"] = facet_label
if labels.get("color", None) is None:
labels["color"] = xarray.plot.utils.label_from_attrs(img)
labels["color"] = labels["color"].replace("\n", "<br>")
else:
if hasattr(img, "columns") and hasattr(img.columns, "__len__"):
if x is None:
x = img.columns
if labels.get("x", None) is None and hasattr(img.columns, "name"):
labels["x"] = img.columns.name or ""
if hasattr(img, "index") and hasattr(img.index, "__len__"):
if y is None:
y = img.index
if labels.get("y", None) is None and hasattr(img.index, "name"):
labels["y"] = img.index.name or ""
if labels.get("x", None) is None:
labels["x"] = ""
if labels.get("y", None) is None:
labels["y"] = ""
if labels.get("color", None) is None:
labels["color"] = ""
if aspect is None:
aspect = "equal"
# --- Set the value of binary_string (forbidden for pandas)
if isinstance(img, pd.DataFrame):
if binary_string:
raise ValueError("Binary strings cannot be used with pandas arrays")
is_dataframe = True
else:
is_dataframe = False
# --------------- Starting from here img is always a numpy array --------
img = np.asanyarray(img)
# Reshape array so that animation dimension comes first, then facets, then images
if facet_col is not None:
img = np.moveaxis(img, facet_col, 0)
if animation_frame is not None and animation_frame < facet_col:
animation_frame += 1
facet_col = True
if animation_frame is not None:
img = np.moveaxis(img, animation_frame, 0)
animation_frame = True
args["animation_frame"] = (
"animation_frame"
if labels.get("animation_frame") is None
else labels["animation_frame"]
)
iterables = ()
if animation_frame is not None:
iterables += (range(nslices_animation),)
if facet_col is not None:
iterables += (range(nslices_facet),)
# Default behaviour of binary_string: True for RGB images, False for 2D
if binary_string is None:
binary_string = img.ndim >= (3 + slice_dimensions) and not is_dataframe
# Cast bools to uint8 (also one byte)
if img.dtype == bool:
img = 255 * img.astype(np.uint8)
if range_color is not None:
zmin = range_color[0]
zmax = range_color[1]
# -------- Contrast rescaling: either minmax or infer ------------------
if contrast_rescaling is None:
contrast_rescaling = "minmax" if img.ndim == (2 + slice_dimensions) else "infer"
# We try to set zmin and zmax only if necessary, because traces have good defaults
if contrast_rescaling == "minmax":
# When using binary_string and minmax we need to set zmin and zmax to rescale the image
if (zmin is not None or binary_string) and zmax is None:
zmax = img.max()
if (zmax is not None or binary_string) and zmin is None:
zmin = img.min()
else:
# For uint8 data and infer we let zmin and zmax to be None if passed as None
if zmax is None and img.dtype != np.uint8:
zmax = _infer_zmax_from_type(img)
if zmin is None and zmax is not None:
zmin = 0
# For 2d data, use Heatmap trace, unless binary_string is True
if img.ndim == 2 + slice_dimensions and not binary_string:
y_index = slice_dimensions
if y is not None and img.shape[y_index] != len(y):
raise ValueError(
"The length of the y vector must match the length of the first "
+ "dimension of the img matrix."
)
x_index = slice_dimensions + 1
if x is not None and img.shape[x_index] != len(x):
raise ValueError(
"The length of the x vector must match the length of the second "
+ "dimension of the img matrix."
)
texttemplate = None
if text_auto is True:
texttemplate = "%{z}"
elif text_auto is not False:
texttemplate = "%{z:" + text_auto + "}"
traces = [
go.Heatmap(
x=x,
y=y,
z=img[index_tup],
coloraxis="coloraxis1",
name=str(i),
texttemplate=texttemplate,
)
for i, index_tup in enumerate(itertools.product(*iterables))
]
autorange = True if origin == "lower" else "reversed"
layout = dict(yaxis=dict(autorange=autorange))
if aspect == "equal":
layout["xaxis"] = dict(scaleanchor="y", constrain="domain")
layout["yaxis"]["constrain"] = "domain"
colorscale_validator = ColorscaleValidator("colorscale", "imshow")
layout["coloraxis1"] = dict(
colorscale=colorscale_validator.validate_coerce(
args["color_continuous_scale"]
),
cmid=color_continuous_midpoint,
cmin=zmin,
cmax=zmax,
)
if labels["color"]:
layout["coloraxis1"]["colorbar"] = dict(title_text=labels["color"])
# For 2D+RGB data, use Image trace
elif (
img.ndim >= 3
and (img.shape[-1] in [3, 4] or slice_dimensions and binary_string)
) or (img.ndim == 2 and binary_string):
rescale_image = True # to check whether image has been modified
if zmin is not None and zmax is not None:
zmin, zmax = (
_vectorize_zvalue(zmin, mode="min"),
_vectorize_zvalue(zmax, mode="max"),
)
x0, y0, dx, dy = (None,) * 4
error_msg_xarray = (
"Non-numerical coordinates were passed with xarray `img`, but "
"the Image trace cannot handle it. Please use `binary_string=False` "
"for 2D data or pass instead the numpy array `img.values` to `px.imshow`."
)
if x is not None:
x = np.asanyarray(x)
if np.issubdtype(x.dtype, np.number):
x0 = x[0]
dx = x[1] - x[0]
else:
error_msg = (
error_msg_xarray
if img_is_xarray
else (
"Only numerical values are accepted for the `x` parameter "
"when an Image trace is used."
)
)
raise ValueError(error_msg)
if y is not None:
y = np.asanyarray(y)
if np.issubdtype(y.dtype, np.number):
y0 = y[0]
dy = y[1] - y[0]
else:
error_msg = (
error_msg_xarray
if img_is_xarray
else (
"Only numerical values are accepted for the `y` parameter "
"when an Image trace is used."
)
)
raise ValueError(error_msg)
if binary_string:
if zmin is None and zmax is None: # no rescaling, faster
img_rescaled = img
rescale_image = False
elif img.ndim == 2 + slice_dimensions: # single-channel image
img_rescaled = rescale_intensity(
img, in_range=(zmin[0], zmax[0]), out_range=np.uint8
)
else:
img_rescaled = np.stack(
[
rescale_intensity(
img[..., ch],
in_range=(zmin[ch], zmax[ch]),
out_range=np.uint8,
)
for ch in range(img.shape[-1])
],
axis=-1,
)
img_str = [
image_array_to_data_uri(
img_rescaled[index_tup],
backend=binary_backend,
compression=binary_compression_level,
ext=binary_format,
)
for index_tup in itertools.product(*iterables)
]
traces = [
go.Image(source=img_str_slice, name=str(i), x0=x0, y0=y0, dx=dx, dy=dy)
for i, img_str_slice in enumerate(img_str)
]
else:
colormodel = "rgb" if img.shape[-1] == 3 else "rgba256"
traces = [
go.Image(
z=img[index_tup],
zmin=zmin,
zmax=zmax,
colormodel=colormodel,
x0=x0,
y0=y0,
dx=dx,
dy=dy,
)
for index_tup in itertools.product(*iterables)
]
layout = {}
if origin == "lower" or (dy is not None and dy < 0):
layout["yaxis"] = dict(autorange=True)
if dx is not None and dx < 0:
layout["xaxis"] = dict(autorange="reversed")
else:
raise ValueError(
"px.imshow only accepts 2D single-channel, RGB or RGBA images. "
"An image of shape %s was provided. "
"Alternatively, 3- or 4-D single or multichannel datasets can be "
"visualized using the `facet_col` or/and `animation_frame` arguments."
% str(img.shape)
)
# Now build figure
col_labels = []
if facet_col is not None:
slice_label = (
"facet_col" if labels.get("facet_col") is None else labels["facet_col"]
)
col_labels = [f"{slice_label}={i}" for i in facet_slices]
fig = init_figure(args, "xy", [], nrows, ncols, col_labels, [])
for attr_name in ["height", "width"]:
if args[attr_name]:
layout[attr_name] = args[attr_name]
if args["title"]:
layout["title_text"] = args["title"]
elif args["template"].layout.margin.t is None:
layout["margin"] = {"t": 60}
frame_list = []
for index, trace in enumerate(traces):
if (facet_col and index < nrows * ncols) or index == 0:
fig.add_trace(trace, row=nrows - index // ncols, col=index % ncols + 1)
if animation_frame is not None:
for i, index in zip(range(nslices_animation), animation_slices):
frame_list.append(
dict(
data=traces[nslices_facet * i : nslices_facet * (i + 1)],
layout=layout,
name=str(index),
)
)
if animation_frame:
fig.frames = frame_list
fig.update_layout(layout)
# Hover name, z or color
if binary_string and rescale_image and not np.all(img == img_rescaled):
# we rescaled the image, hence z is not displayed in hover since it does
# not correspond to img values
hovertemplate = "%s: %%{x}<br>%s: %%{y}<extra></extra>" % (
labels["x"] or "x",
labels["y"] or "y",
)
else:
if trace["type"] == "heatmap":
hover_name = "%{z}"
elif img.ndim == 2:
hover_name = "%{z[0]}"
elif img.ndim == 3 and img.shape[-1] == 3:
hover_name = "[%{z[0]}, %{z[1]}, %{z[2]}]"
else:
hover_name = "%{z}"
hovertemplate = "%s: %%{x}<br>%s: %%{y}<br>%s: %s<extra></extra>" % (
labels["x"] or "x",
labels["y"] or "y",
labels["color"] or "color",
hover_name,
)
fig.update_traces(hovertemplate=hovertemplate)
if labels["x"]:
fig.update_xaxes(title_text=labels["x"], row=1)
if labels["y"]:
fig.update_yaxes(title_text=labels["y"], col=1)
configure_animation_controls(args, go.Image, fig)
fig.update_layout(template=args["template"], overwrite=True)
return fig
| _imshow.imshow |
plotly.py | 18 | packages/python/plotly/plotly/graph_objs/_layout.py | def annotations(self):
"""
The 'annotations' property is a tuple of instances of
Annotation that may be specified as:
- A list or tuple of instances of plotly.graph_objs.layout.Annotation
- A list or tuple of dicts of string/value properties that
will be passed to the Annotation constructor
Supported dict properties:
align
Sets the horizontal alignment of the `text`
within the box. Has an effect only if `text`
spans two or more lines (i.e. `text` contains
one or more <br> HTML tags) or if an explicit
width is set to override the text width.
arrowcolor
Sets the color of the annotation arrow.
arrowhead
Sets the end annotation arrow head style.
arrowside
Sets the annotation arrow head position.
arrowsize
Sets the size of the end annotation arrow head,
relative to `arrowwidth`. A value of 1
(default) gives a head about 3x as wide as the
line.
arrowwidth
Sets the width (in px) of annotation arrow
line.
ax
Sets the x component of the arrow tail about
the arrow head. If `axref` is `pixel`, a
positive (negative) component corresponds to an
arrow pointing from right to left (left to
right). If `axref` is not `pixel` and is
exactly the same as `xref`, this is an absolute
value on that axis, like `x`, specified in the
same coordinates as `xref`.
axref
Indicates in what coordinates the tail of the
annotation (ax,ay) is specified. If set to a x
axis id (e.g. "x" or "x2"), the `x` position
refers to a x coordinate. If set to "paper",
the `x` position refers to the distance from
the left of the plotting area in normalized
coordinates where 0 (1) corresponds to the left
(right). If set to a x axis ID followed by
"domain" (separated by a space), the position
behaves like for "paper", but refers to the
distance in fractions of the domain length from
the left of the domain of that axis: e.g., *x2
domain* refers to the domain of the second x
axis and a x position of 0.5 refers to the
point between the left and the right of the
domain of the second x axis. In order for
absolute positioning of the arrow to work,
"axref" must be exactly the same as "xref",
otherwise "axref" will revert to "pixel"
(explained next). For relative positioning,
"axref" can be set to "pixel", in which case
the "ax" value is specified in pixels relative
to "x". Absolute positioning is useful for
trendline annotations which should continue to
indicate the correct trend when zoomed.
Relative positioning is useful for specifying
the text offset for an annotated point.
ay
Sets the y component of the arrow tail about
the arrow head. If `ayref` is `pixel`, a
positive (negative) component corresponds to an
arrow pointing from bottom to top (top to
bottom). If `ayref` is not `pixel` and is
exactly the same as `yref`, this is an absolute
value on that axis, like `y`, specified in the
same coordinates as `yref`.
ayref
Indicates in what coordinates the tail of the
annotation (ax,ay) is specified. If set to a y
axis id (e.g. "y" or "y2"), the `y` position
refers to a y coordinate. If set to "paper",
the `y` position refers to the distance from
the bottom of the plotting area in normalized
coordinates where 0 (1) corresponds to the
bottom (top). If set to a y axis ID followed by
"domain" (separated by a space), the position
behaves like for "paper", but refers to the
distance in fractions of the domain length from
the bottom of the domain of that axis: e.g.,
*y2 domain* refers to the domain of the second
y axis and a y position of 0.5 refers to the
point between the bottom and the top of the
domain of the second y axis. In order for
absolute positioning of the arrow to work,
"ayref" must be exactly the same as "yref",
otherwise "ayref" will revert to "pixel"
(explained next). For relative positioning,
"ayref" can be set to "pixel", in which case
the "ay" value is specified in pixels relative
to "y". Absolute positioning is useful for
trendline annotations which should continue to
indicate the correct trend when zoomed.
Relative positioning is useful for specifying
the text offset for an annotated point.
bgcolor
Sets the background color of the annotation.
bordercolor
Sets the color of the border enclosing the
annotation `text`.
borderpad
Sets the padding (in px) between the `text` and
the enclosing border.
borderwidth
Sets the width (in px) of the border enclosing
the annotation `text`.
captureevents
Determines whether the annotation text box
captures mouse move and click events, or allows
those events to pass through to data points in
the plot that may be behind the annotation. By
default `captureevents` is False unless
`hovertext` is provided. If you use the event
`plotly_clickannotation` without `hovertext`
you must explicitly enable `captureevents`.
clicktoshow
Makes this annotation respond to clicks on the
plot. If you click a data point that exactly
matches the `x` and `y` values of this
annotation, and it is hidden (visible: false),
it will appear. In "onoff" mode, you must click
the same point again to make it disappear, so
if you click multiple points, you can show
multiple annotations. In "onout" mode, a click
anywhere else in the plot (on another data
point or not) will hide this annotation. If you
need to show/hide this annotation in response
to different `x` or `y` values, you can set
`xclick` and/or `yclick`. This is useful for
example to label the side of a bar. To label
markers though, `standoff` is preferred over
`xclick` and `yclick`.
font
Sets the annotation text font.
height
Sets an explicit height for the text box. null
(default) lets the text set the box height.
Taller text will be clipped.
hoverlabel
:class:`plotly.graph_objects.layout.annotation.
Hoverlabel` instance or dict with compatible
properties
hovertext
Sets text to appear when hovering over this
annotation. If omitted or blank, no hover label
will appear.
name
When used in a template, named items are
created in the output figure in addition to any
items the figure already has in this array. You
can modify these items in the output figure by
making your own item with `templateitemname`
matching this `name` alongside your
modifications (including `visible: false` or
`enabled: false` to hide it). Has no effect
outside of a template.
opacity
Sets the opacity of the annotation (text +
arrow).
showarrow
Determines whether or not the annotation is
drawn with an arrow. If True, `text` is placed
near the arrow's tail. If False, `text` lines
up with the `x` and `y` provided.
standoff
Sets a distance, in pixels, to move the end
arrowhead away from the position it is pointing
at, for example to point at the edge of a
marker independent of zoom. Note that this
shortens the arrow from the `ax` / `ay` vector,
in contrast to `xshift` / `yshift` which moves
everything by this amount.
startarrowhead
Sets the start annotation arrow head style.
startarrowsize
Sets the size of the start annotation arrow
head, relative to `arrowwidth`. A value of 1
(default) gives a head about 3x as wide as the
line.
startstandoff
Sets a distance, in pixels, to move the start
arrowhead away from the position it is pointing
at, for example to point at the edge of a
marker independent of zoom. Note that this
shortens the arrow from the `ax` / `ay` vector,
in contrast to `xshift` / `yshift` which moves
everything by this amount.
templateitemname
Used to refer to a named item in this array in
the template. Named items from the template
will be created even without a matching item in
the input figure, but you can modify one by
making an item with `templateitemname` matching
its `name`, alongside your modifications
(including `visible: false` or `enabled: false`
to hide it). If there is no template or no
matching item, this item will be hidden unless
you explicitly show it with `visible: true`.
text
Sets the text associated with this annotation.
Plotly uses a subset of HTML tags to do things
like newline (<br>), bold (<b></b>), italics
(<i></i>), hyperlinks (<a href='...'></a>).
Tags <em>, <sup>, <sub>, <s>, <u> <span> are
also supported.
textangle
Sets the angle at which the `text` is drawn
with respect to the horizontal.
valign
Sets the vertical alignment of the `text`
within the box. Has an effect only if an
explicit height is set to override the text
height.
visible
Determines whether or not this annotation is
visible.
width
Sets an explicit width for the text box. null
(default) lets the text set the box width.
Wider text will be clipped. There is no
automatic wrapping; use <br> to start a new
line.
x
Sets the annotation's x position. If the axis
`type` is "log", then you must take the log of
your desired range. If the axis `type` is
"date", it should be date strings, like date
data, though Date objects and unix milliseconds
will be accepted and converted to strings. If
the axis `type` is "category", it should be
numbers, using the scale where each category is
assigned a serial number from zero in the order
it appears.
xanchor
Sets the text box's horizontal position anchor
This anchor binds the `x` position to the
"left", "center" or "right" of the annotation.
For example, if `x` is set to 1, `xref` to
"paper" and `xanchor` to "right" then the
right-most portion of the annotation lines up
with the right-most edge of the plotting area.
If "auto", the anchor is equivalent to "center"
for data-referenced annotations or if there is
an arrow, whereas for paper-referenced with no
arrow, the anchor picked corresponds to the
closest side.
xclick
Toggle this annotation when clicking a data
point whose `x` value is `xclick` rather than
the annotation's `x` value.
xref
Sets the annotation's x coordinate axis. If set
to a x axis id (e.g. "x" or "x2"), the `x`
position refers to a x coordinate. If set to
"paper", the `x` position refers to the
distance from the left of the plotting area in
normalized coordinates where 0 (1) corresponds
to the left (right). If set to a x axis ID
followed by "domain" (separated by a space),
the position behaves like for "paper", but
refers to the distance in fractions of the
domain length from the left of the domain of
that axis: e.g., *x2 domain* refers to the
domain of the second x axis and a x position
of 0.5 refers to the point between the left and
the right of the domain of the second x axis.
xshift
Shifts the position of the whole annotation and
arrow to the right (positive) or left
(negative) by this many pixels.
y
Sets the annotation's y position. If the axis
`type` is "log", then you must take the log of
your desired range. If the axis `type` is
"date", it should be date strings, like date
data, though Date objects and unix milliseconds
will be accepted and converted to strings. If
the axis `type` is "category", it should be
numbers, using the scale where each category is
assigned a serial number from zero in the order
it appears.
yanchor
Sets the text box's vertical position anchor
This anchor binds the `y` position to the
"top", "middle" or "bottom" of the annotation.
For example, if `y` is set to 1, `yref` to
"paper" and `yanchor` to "top" then the top-
most portion of the annotation lines up with
the top-most edge of the plotting area. If
"auto", the anchor is equivalent to "middle"
for data-referenced annotations or if there is
an arrow, whereas for paper-referenced with no
arrow, the anchor picked corresponds to the
closest side.
yclick
Toggle this annotation when clicking a data
point whose `y` value is `yclick` rather than
the annotation's `y` value.
yref
Sets the annotation's y coordinate axis. If set
to a y axis id (e.g. "y" or "y2"), the `y`
position refers to a y coordinate. If set to
"paper", the `y` position refers to the
distance from the bottom of the plotting area
in normalized coordinates where 0 (1)
corresponds to the bottom (top). If set to a y
axis ID followed by "domain" (separated by a
space), the position behaves like for "paper",
but refers to the distance in fractions of the
domain length from the bottom of the domain of
that axis: e.g., *y2 domain* refers to the
domain of the second y axis and a y position
of 0.5 refers to the point between the bottom
and the top of the domain of the second y axis.
yshift
Shifts the position of the whole annotation and
arrow up (positive) or down (negative) by this
many pixels.
Returns
-------
tuple[plotly.graph_objs.layout.Annotation]
"""
| /usr/src/app/target_test_cases/failed_tests__layout.annotations.txt | def annotations(self):
"""
The 'annotations' property is a tuple of instances of
Annotation that may be specified as:
- A list or tuple of instances of plotly.graph_objs.layout.Annotation
- A list or tuple of dicts of string/value properties that
will be passed to the Annotation constructor
Supported dict properties:
align
Sets the horizontal alignment of the `text`
within the box. Has an effect only if `text`
spans two or more lines (i.e. `text` contains
one or more <br> HTML tags) or if an explicit
width is set to override the text width.
arrowcolor
Sets the color of the annotation arrow.
arrowhead
Sets the end annotation arrow head style.
arrowside
Sets the annotation arrow head position.
arrowsize
Sets the size of the end annotation arrow head,
relative to `arrowwidth`. A value of 1
(default) gives a head about 3x as wide as the
line.
arrowwidth
Sets the width (in px) of annotation arrow
line.
ax
Sets the x component of the arrow tail about
the arrow head. If `axref` is `pixel`, a
positive (negative) component corresponds to an
arrow pointing from right to left (left to
right). If `axref` is not `pixel` and is
exactly the same as `xref`, this is an absolute
value on that axis, like `x`, specified in the
same coordinates as `xref`.
axref
Indicates in what coordinates the tail of the
annotation (ax,ay) is specified. If set to a x
axis id (e.g. "x" or "x2"), the `x` position
refers to a x coordinate. If set to "paper",
the `x` position refers to the distance from
the left of the plotting area in normalized
coordinates where 0 (1) corresponds to the left
(right). If set to a x axis ID followed by
"domain" (separated by a space), the position
behaves like for "paper", but refers to the
distance in fractions of the domain length from
the left of the domain of that axis: e.g., *x2
domain* refers to the domain of the second x
axis and a x position of 0.5 refers to the
point between the left and the right of the
domain of the second x axis. In order for
absolute positioning of the arrow to work,
"axref" must be exactly the same as "xref",
otherwise "axref" will revert to "pixel"
(explained next). For relative positioning,
"axref" can be set to "pixel", in which case
the "ax" value is specified in pixels relative
to "x". Absolute positioning is useful for
trendline annotations which should continue to
indicate the correct trend when zoomed.
Relative positioning is useful for specifying
the text offset for an annotated point.
ay
Sets the y component of the arrow tail about
the arrow head. If `ayref` is `pixel`, a
positive (negative) component corresponds to an
arrow pointing from bottom to top (top to
bottom). If `ayref` is not `pixel` and is
exactly the same as `yref`, this is an absolute
value on that axis, like `y`, specified in the
same coordinates as `yref`.
ayref
Indicates in what coordinates the tail of the
annotation (ax,ay) is specified. If set to a y
axis id (e.g. "y" or "y2"), the `y` position
refers to a y coordinate. If set to "paper",
the `y` position refers to the distance from
the bottom of the plotting area in normalized
coordinates where 0 (1) corresponds to the
bottom (top). If set to a y axis ID followed by
"domain" (separated by a space), the position
behaves like for "paper", but refers to the
distance in fractions of the domain length from
the bottom of the domain of that axis: e.g.,
*y2 domain* refers to the domain of the second
y axis and a y position of 0.5 refers to the
point between the bottom and the top of the
domain of the second y axis. In order for
absolute positioning of the arrow to work,
"ayref" must be exactly the same as "yref",
otherwise "ayref" will revert to "pixel"
(explained next). For relative positioning,
"ayref" can be set to "pixel", in which case
the "ay" value is specified in pixels relative
to "y". Absolute positioning is useful for
trendline annotations which should continue to
indicate the correct trend when zoomed.
Relative positioning is useful for specifying
the text offset for an annotated point.
bgcolor
Sets the background color of the annotation.
bordercolor
Sets the color of the border enclosing the
annotation `text`.
borderpad
Sets the padding (in px) between the `text` and
the enclosing border.
borderwidth
Sets the width (in px) of the border enclosing
the annotation `text`.
captureevents
Determines whether the annotation text box
captures mouse move and click events, or allows
those events to pass through to data points in
the plot that may be behind the annotation. By
default `captureevents` is False unless
`hovertext` is provided. If you use the event
`plotly_clickannotation` without `hovertext`
you must explicitly enable `captureevents`.
clicktoshow
Makes this annotation respond to clicks on the
plot. If you click a data point that exactly
matches the `x` and `y` values of this
annotation, and it is hidden (visible: false),
it will appear. In "onoff" mode, you must click
the same point again to make it disappear, so
if you click multiple points, you can show
multiple annotations. In "onout" mode, a click
anywhere else in the plot (on another data
point or not) will hide this annotation. If you
need to show/hide this annotation in response
to different `x` or `y` values, you can set
`xclick` and/or `yclick`. This is useful for
example to label the side of a bar. To label
markers though, `standoff` is preferred over
`xclick` and `yclick`.
font
Sets the annotation text font.
height
Sets an explicit height for the text box. null
(default) lets the text set the box height.
Taller text will be clipped.
hoverlabel
:class:`plotly.graph_objects.layout.annotation.
Hoverlabel` instance or dict with compatible
properties
hovertext
Sets text to appear when hovering over this
annotation. If omitted or blank, no hover label
will appear.
name
When used in a template, named items are
created in the output figure in addition to any
items the figure already has in this array. You
can modify these items in the output figure by
making your own item with `templateitemname`
matching this `name` alongside your
modifications (including `visible: false` or
`enabled: false` to hide it). Has no effect
outside of a template.
opacity
Sets the opacity of the annotation (text +
arrow).
showarrow
Determines whether or not the annotation is
drawn with an arrow. If True, `text` is placed
near the arrow's tail. If False, `text` lines
up with the `x` and `y` provided.
standoff
Sets a distance, in pixels, to move the end
arrowhead away from the position it is pointing
at, for example to point at the edge of a
marker independent of zoom. Note that this
shortens the arrow from the `ax` / `ay` vector,
in contrast to `xshift` / `yshift` which moves
everything by this amount.
startarrowhead
Sets the start annotation arrow head style.
startarrowsize
Sets the size of the start annotation arrow
head, relative to `arrowwidth`. A value of 1
(default) gives a head about 3x as wide as the
line.
startstandoff
Sets a distance, in pixels, to move the start
arrowhead away from the position it is pointing
at, for example to point at the edge of a
marker independent of zoom. Note that this
shortens the arrow from the `ax` / `ay` vector,
in contrast to `xshift` / `yshift` which moves
everything by this amount.
templateitemname
Used to refer to a named item in this array in
the template. Named items from the template
will be created even without a matching item in
the input figure, but you can modify one by
making an item with `templateitemname` matching
its `name`, alongside your modifications
(including `visible: false` or `enabled: false`
to hide it). If there is no template or no
matching item, this item will be hidden unless
you explicitly show it with `visible: true`.
text
Sets the text associated with this annotation.
Plotly uses a subset of HTML tags to do things
like newline (<br>), bold (<b></b>), italics
(<i></i>), hyperlinks (<a href='...'></a>).
Tags <em>, <sup>, <sub>, <s>, <u> <span> are
also supported.
textangle
Sets the angle at which the `text` is drawn
with respect to the horizontal.
valign
Sets the vertical alignment of the `text`
within the box. Has an effect only if an
explicit height is set to override the text
height.
visible
Determines whether or not this annotation is
visible.
width
Sets an explicit width for the text box. null
(default) lets the text set the box width.
Wider text will be clipped. There is no
automatic wrapping; use <br> to start a new
line.
x
Sets the annotation's x position. If the axis
`type` is "log", then you must take the log of
your desired range. If the axis `type` is
"date", it should be date strings, like date
data, though Date objects and unix milliseconds
will be accepted and converted to strings. If
the axis `type` is "category", it should be
numbers, using the scale where each category is
assigned a serial number from zero in the order
it appears.
xanchor
Sets the text box's horizontal position anchor
This anchor binds the `x` position to the
"left", "center" or "right" of the annotation.
For example, if `x` is set to 1, `xref` to
"paper" and `xanchor` to "right" then the
right-most portion of the annotation lines up
with the right-most edge of the plotting area.
If "auto", the anchor is equivalent to "center"
for data-referenced annotations or if there is
an arrow, whereas for paper-referenced with no
arrow, the anchor picked corresponds to the
closest side.
xclick
Toggle this annotation when clicking a data
point whose `x` value is `xclick` rather than
the annotation's `x` value.
xref
Sets the annotation's x coordinate axis. If set
to a x axis id (e.g. "x" or "x2"), the `x`
position refers to a x coordinate. If set to
"paper", the `x` position refers to the
distance from the left of the plotting area in
normalized coordinates where 0 (1) corresponds
to the left (right). If set to a x axis ID
followed by "domain" (separated by a space),
the position behaves like for "paper", but
refers to the distance in fractions of the
domain length from the left of the domain of
that axis: e.g., *x2 domain* refers to the
domain of the second x axis and a x position
of 0.5 refers to the point between the left and
the right of the domain of the second x axis.
xshift
Shifts the position of the whole annotation and
arrow to the right (positive) or left
(negative) by this many pixels.
y
Sets the annotation's y position. If the axis
`type` is "log", then you must take the log of
your desired range. If the axis `type` is
"date", it should be date strings, like date
data, though Date objects and unix milliseconds
will be accepted and converted to strings. If
the axis `type` is "category", it should be
numbers, using the scale where each category is
assigned a serial number from zero in the order
it appears.
yanchor
Sets the text box's vertical position anchor
This anchor binds the `y` position to the
"top", "middle" or "bottom" of the annotation.
For example, if `y` is set to 1, `yref` to
"paper" and `yanchor` to "top" then the top-
most portion of the annotation lines up with
the top-most edge of the plotting area. If
"auto", the anchor is equivalent to "middle"
for data-referenced annotations or if there is
an arrow, whereas for paper-referenced with no
arrow, the anchor picked corresponds to the
closest side.
yclick
Toggle this annotation when clicking a data
point whose `y` value is `yclick` rather than
the annotation's `y` value.
yref
Sets the annotation's y coordinate axis. If set
to a y axis id (e.g. "y" or "y2"), the `y`
position refers to a y coordinate. If set to
"paper", the `y` position refers to the
distance from the bottom of the plotting area
in normalized coordinates where 0 (1)
corresponds to the bottom (top). If set to a y
axis ID followed by "domain" (separated by a
space), the position behaves like for "paper",
but refers to the distance in fractions of the
domain length from the bottom of the domain of
that axis: e.g., *y2 domain* refers to the
domain of the second y axis and a y position
of 0.5 refers to the point between the bottom
and the top of the domain of the second y axis.
yshift
Shifts the position of the whole annotation and
arrow up (positive) or down (negative) by this
many pixels.
Returns
-------
tuple[plotly.graph_objs.layout.Annotation]
"""
return self["annotations"]
| _layout.annotations |
plotly.py | 19 | packages/python/plotly/plotly/graph_objs/_layout.py | def coloraxis(self):
"""
The 'coloraxis' property is an instance of Coloraxis
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.Coloraxis`
- A dict of string/value properties that will be passed
to the Coloraxis constructor
Supported dict properties:
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `colorscale`. In case
`colorscale` is unspecified or `autocolorscale`
is true, the default palette will be chosen
according to whether numbers in the `color`
array are all positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
corresponding trace color array(s)) or the
bounds set in `cmin` and `cmax` Defaults to
`false` when `cmin` and `cmax` are set by the
user.
cmax
Sets the upper bound of the color domain. Value
should have the same units as corresponding
trace color array(s) and if set, `cmin` must be
set as well.
cmid
Sets the mid-point of the color domain by
scaling `cmin` and/or `cmax` to be equidistant
to this point. Value should have the same units
as corresponding trace color array(s). Has no
effect when `cauto` is `false`.
cmin
Sets the lower bound of the color domain. Value
should have the same units as corresponding
trace color array(s) and if set, `cmax` must be
set as well.
colorbar
:class:`plotly.graph_objects.layout.coloraxis.C
olorBar` instance or dict with compatible
properties
colorscale
Sets the colorscale. The colorscale must be an
array containing arrays mapping a normalized
value to an rgb, rgba, hex, hsl, hsv, or named
color string. At minimum, a mapping for the
lowest (0) and highest (1) values are required.
For example, `[[0, 'rgb(0,0,255)'], [1,
'rgb(255,0,0)']]`. To control the bounds of the
colorscale in color space, use `cmin` and
`cmax`. Alternatively, `colorscale` may be a
palette name string of the following list: Blac
kbody,Bluered,Blues,Cividis,Earth,Electric,Gree
ns,Greys,Hot,Jet,Picnic,Portland,Rainbow,RdBu,R
eds,Viridis,YlGnBu,YlOrRd.
reversescale
Reverses the color mapping if true. If true,
`cmin` will correspond to the last color in the
array and `cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace.
Returns
-------
plotly.graph_objs.layout.Coloraxis
"""
| /usr/src/app/target_test_cases/failed_tests__layout.coloraxis.txt | def coloraxis(self):
"""
The 'coloraxis' property is an instance of Coloraxis
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.Coloraxis`
- A dict of string/value properties that will be passed
to the Coloraxis constructor
Supported dict properties:
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `colorscale`. In case
`colorscale` is unspecified or `autocolorscale`
is true, the default palette will be chosen
according to whether numbers in the `color`
array are all positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
corresponding trace color array(s)) or the
bounds set in `cmin` and `cmax` Defaults to
`false` when `cmin` and `cmax` are set by the
user.
cmax
Sets the upper bound of the color domain. Value
should have the same units as corresponding
trace color array(s) and if set, `cmin` must be
set as well.
cmid
Sets the mid-point of the color domain by
scaling `cmin` and/or `cmax` to be equidistant
to this point. Value should have the same units
as corresponding trace color array(s). Has no
effect when `cauto` is `false`.
cmin
Sets the lower bound of the color domain. Value
should have the same units as corresponding
trace color array(s) and if set, `cmax` must be
set as well.
colorbar
:class:`plotly.graph_objects.layout.coloraxis.C
olorBar` instance or dict with compatible
properties
colorscale
Sets the colorscale. The colorscale must be an
array containing arrays mapping a normalized
value to an rgb, rgba, hex, hsl, hsv, or named
color string. At minimum, a mapping for the
lowest (0) and highest (1) values are required.
For example, `[[0, 'rgb(0,0,255)'], [1,
'rgb(255,0,0)']]`. To control the bounds of the
colorscale in color space, use `cmin` and
`cmax`. Alternatively, `colorscale` may be a
palette name string of the following list: Blac
kbody,Bluered,Blues,Cividis,Earth,Electric,Gree
ns,Greys,Hot,Jet,Picnic,Portland,Rainbow,RdBu,R
eds,Viridis,YlGnBu,YlOrRd.
reversescale
Reverses the color mapping if true. If true,
`cmin` will correspond to the last color in the
array and `cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace.
Returns
-------
plotly.graph_objs.layout.Coloraxis
"""
return self["coloraxis"]
| _layout.coloraxis |
plotly.py | 20 | packages/python/plotly/plotly/graph_objs/_layout.py | def geo(self):
"""
The 'geo' property is an instance of Geo
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.Geo`
- A dict of string/value properties that will be passed
to the Geo constructor
Supported dict properties:
bgcolor
Set the background color of the map
center
:class:`plotly.graph_objects.layout.geo.Center`
instance or dict with compatible properties
coastlinecolor
Sets the coastline color.
coastlinewidth
Sets the coastline stroke width (in px).
countrycolor
Sets line color of the country boundaries.
countrywidth
Sets line width (in px) of the country
boundaries.
domain
:class:`plotly.graph_objects.layout.geo.Domain`
instance or dict with compatible properties
fitbounds
Determines if this subplot's view settings are
auto-computed to fit trace data. On scoped
maps, setting `fitbounds` leads to `center.lon`
and `center.lat` getting auto-filled. On maps
with a non-clipped projection, setting
`fitbounds` leads to `center.lon`,
`center.lat`, and `projection.rotation.lon`
getting auto-filled. On maps with a clipped
projection, setting `fitbounds` leads to
`center.lon`, `center.lat`,
`projection.rotation.lon`,
`projection.rotation.lat`, `lonaxis.range` and
`lonaxis.range` getting auto-filled. If
"locations", only the trace's visible locations
are considered in the `fitbounds` computations.
If "geojson", the entire trace input `geojson`
(if provided) is considered in the `fitbounds`
computations, Defaults to False.
framecolor
Sets the color the frame.
framewidth
Sets the stroke width (in px) of the frame.
lakecolor
Sets the color of the lakes.
landcolor
Sets the land mass color.
lataxis
:class:`plotly.graph_objects.layout.geo.Lataxis
` instance or dict with compatible properties
lonaxis
:class:`plotly.graph_objects.layout.geo.Lonaxis
` instance or dict with compatible properties
oceancolor
Sets the ocean color
projection
:class:`plotly.graph_objects.layout.geo.Project
ion` instance or dict with compatible
properties
resolution
Sets the resolution of the base layers. The
values have units of km/mm e.g. 110 corresponds
to a scale ratio of 1:110,000,000.
rivercolor
Sets color of the rivers.
riverwidth
Sets the stroke width (in px) of the rivers.
scope
Set the scope of the map.
showcoastlines
Sets whether or not the coastlines are drawn.
showcountries
Sets whether or not country boundaries are
drawn.
showframe
Sets whether or not a frame is drawn around the
map.
showlakes
Sets whether or not lakes are drawn.
showland
Sets whether or not land masses are filled in
color.
showocean
Sets whether or not oceans are filled in color.
showrivers
Sets whether or not rivers are drawn.
showsubunits
Sets whether or not boundaries of subunits
within countries (e.g. states, provinces) are
drawn.
subunitcolor
Sets the color of the subunits boundaries.
subunitwidth
Sets the stroke width (in px) of the subunits
boundaries.
uirevision
Controls persistence of user-driven changes in
the view (projection and center). Defaults to
`layout.uirevision`.
visible
Sets the default visibility of the base layers.
Returns
-------
plotly.graph_objs.layout.Geo
"""
| /usr/src/app/target_test_cases/failed_tests__layout.geo.txt | def geo(self):
"""
The 'geo' property is an instance of Geo
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.Geo`
- A dict of string/value properties that will be passed
to the Geo constructor
Supported dict properties:
bgcolor
Set the background color of the map
center
:class:`plotly.graph_objects.layout.geo.Center`
instance or dict with compatible properties
coastlinecolor
Sets the coastline color.
coastlinewidth
Sets the coastline stroke width (in px).
countrycolor
Sets line color of the country boundaries.
countrywidth
Sets line width (in px) of the country
boundaries.
domain
:class:`plotly.graph_objects.layout.geo.Domain`
instance or dict with compatible properties
fitbounds
Determines if this subplot's view settings are
auto-computed to fit trace data. On scoped
maps, setting `fitbounds` leads to `center.lon`
and `center.lat` getting auto-filled. On maps
with a non-clipped projection, setting
`fitbounds` leads to `center.lon`,
`center.lat`, and `projection.rotation.lon`
getting auto-filled. On maps with a clipped
projection, setting `fitbounds` leads to
`center.lon`, `center.lat`,
`projection.rotation.lon`,
`projection.rotation.lat`, `lonaxis.range` and
`lonaxis.range` getting auto-filled. If
"locations", only the trace's visible locations
are considered in the `fitbounds` computations.
If "geojson", the entire trace input `geojson`
(if provided) is considered in the `fitbounds`
computations, Defaults to False.
framecolor
Sets the color the frame.
framewidth
Sets the stroke width (in px) of the frame.
lakecolor
Sets the color of the lakes.
landcolor
Sets the land mass color.
lataxis
:class:`plotly.graph_objects.layout.geo.Lataxis
` instance or dict with compatible properties
lonaxis
:class:`plotly.graph_objects.layout.geo.Lonaxis
` instance or dict with compatible properties
oceancolor
Sets the ocean color
projection
:class:`plotly.graph_objects.layout.geo.Project
ion` instance or dict with compatible
properties
resolution
Sets the resolution of the base layers. The
values have units of km/mm e.g. 110 corresponds
to a scale ratio of 1:110,000,000.
rivercolor
Sets color of the rivers.
riverwidth
Sets the stroke width (in px) of the rivers.
scope
Set the scope of the map.
showcoastlines
Sets whether or not the coastlines are drawn.
showcountries
Sets whether or not country boundaries are
drawn.
showframe
Sets whether or not a frame is drawn around the
map.
showlakes
Sets whether or not lakes are drawn.
showland
Sets whether or not land masses are filled in
color.
showocean
Sets whether or not oceans are filled in color.
showrivers
Sets whether or not rivers are drawn.
showsubunits
Sets whether or not boundaries of subunits
within countries (e.g. states, provinces) are
drawn.
subunitcolor
Sets the color of the subunits boundaries.
subunitwidth
Sets the stroke width (in px) of the subunits
boundaries.
uirevision
Controls persistence of user-driven changes in
the view (projection and center). Defaults to
`layout.uirevision`.
visible
Sets the default visibility of the base layers.
Returns
-------
plotly.graph_objs.layout.Geo
"""
return self["geo"]
| _layout.geo |
plotly.py | 21 | packages/python/plotly/plotly/graph_objs/_layout.py | def grid(self):
"""
The 'grid' property is an instance of Grid
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.Grid`
- A dict of string/value properties that will be passed
to the Grid constructor
Supported dict properties:
columns
The number of columns in the grid. If you
provide a 2D `subplots` array, the length of
its longest row is used as the default. If you
give an `xaxes` array, its length is used as
the default. But it's also possible to have a
different length, if you want to leave a row at
the end for non-cartesian subplots.
domain
:class:`plotly.graph_objects.layout.grid.Domain
` instance or dict with compatible properties
pattern
If no `subplots`, `xaxes`, or `yaxes` are given
but we do have `rows` and `columns`, we can
generate defaults using consecutive axis IDs,
in two ways: "coupled" gives one x axis per
column and one y axis per row. "independent"
uses a new xy pair for each cell, left-to-right
across each row then iterating rows according
to `roworder`.
roworder
Is the first row the top or the bottom? Note
that columns are always enumerated from left to
right.
rows
The number of rows in the grid. If you provide
a 2D `subplots` array or a `yaxes` array, its
length is used as the default. But it's also
possible to have a different length, if you
want to leave a row at the end for non-
cartesian subplots.
subplots
Used for freeform grids, where some axes may be
shared across subplots but others are not. Each
entry should be a cartesian subplot id, like
"xy" or "x3y2", or "" to leave that cell empty.
You may reuse x axes within the same column,
and y axes within the same row. Non-cartesian
subplots and traces that support `domain` can
place themselves in this grid separately using
the `gridcell` attribute.
xaxes
Used with `yaxes` when the x and y axes are
shared across columns and rows. Each entry
should be an x axis id like "x", "x2", etc., or
"" to not put an x axis in that column. Entries
other than "" must be unique. Ignored if
`subplots` is present. If missing but `yaxes`
is present, will generate consecutive IDs.
xgap
Horizontal space between grid cells, expressed
as a fraction of the total width available to
one cell. Defaults to 0.1 for coupled-axes
grids and 0.2 for independent grids.
xside
Sets where the x axis labels and titles go.
"bottom" means the very bottom of the grid.
"bottom plot" is the lowest plot that each x
axis is used in. "top" and "top plot" are
similar.
yaxes
Used with `yaxes` when the x and y axes are
shared across columns and rows. Each entry
should be an y axis id like "y", "y2", etc., or
"" to not put a y axis in that row. Entries
other than "" must be unique. Ignored if
`subplots` is present. If missing but `xaxes`
is present, will generate consecutive IDs.
ygap
Vertical space between grid cells, expressed as
a fraction of the total height available to one
cell. Defaults to 0.1 for coupled-axes grids
and 0.3 for independent grids.
yside
Sets where the y axis labels and titles go.
"left" means the very left edge of the grid.
*left plot* is the leftmost plot that each y
axis is used in. "right" and *right plot* are
similar.
Returns
-------
plotly.graph_objs.layout.Grid
"""
| /usr/src/app/target_test_cases/failed_tests__layout.grid.txt | def grid(self):
"""
The 'grid' property is an instance of Grid
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.Grid`
- A dict of string/value properties that will be passed
to the Grid constructor
Supported dict properties:
columns
The number of columns in the grid. If you
provide a 2D `subplots` array, the length of
its longest row is used as the default. If you
give an `xaxes` array, its length is used as
the default. But it's also possible to have a
different length, if you want to leave a row at
the end for non-cartesian subplots.
domain
:class:`plotly.graph_objects.layout.grid.Domain
` instance or dict with compatible properties
pattern
If no `subplots`, `xaxes`, or `yaxes` are given
but we do have `rows` and `columns`, we can
generate defaults using consecutive axis IDs,
in two ways: "coupled" gives one x axis per
column and one y axis per row. "independent"
uses a new xy pair for each cell, left-to-right
across each row then iterating rows according
to `roworder`.
roworder
Is the first row the top or the bottom? Note
that columns are always enumerated from left to
right.
rows
The number of rows in the grid. If you provide
a 2D `subplots` array or a `yaxes` array, its
length is used as the default. But it's also
possible to have a different length, if you
want to leave a row at the end for non-
cartesian subplots.
subplots
Used for freeform grids, where some axes may be
shared across subplots but others are not. Each
entry should be a cartesian subplot id, like
"xy" or "x3y2", or "" to leave that cell empty.
You may reuse x axes within the same column,
and y axes within the same row. Non-cartesian
subplots and traces that support `domain` can
place themselves in this grid separately using
the `gridcell` attribute.
xaxes
Used with `yaxes` when the x and y axes are
shared across columns and rows. Each entry
should be an x axis id like "x", "x2", etc., or
"" to not put an x axis in that column. Entries
other than "" must be unique. Ignored if
`subplots` is present. If missing but `yaxes`
is present, will generate consecutive IDs.
xgap
Horizontal space between grid cells, expressed
as a fraction of the total width available to
one cell. Defaults to 0.1 for coupled-axes
grids and 0.2 for independent grids.
xside
Sets where the x axis labels and titles go.
"bottom" means the very bottom of the grid.
"bottom plot" is the lowest plot that each x
axis is used in. "top" and "top plot" are
similar.
yaxes
Used with `yaxes` when the x and y axes are
shared across columns and rows. Each entry
should be an y axis id like "y", "y2", etc., or
"" to not put a y axis in that row. Entries
other than "" must be unique. Ignored if
`subplots` is present. If missing but `xaxes`
is present, will generate consecutive IDs.
ygap
Vertical space between grid cells, expressed as
a fraction of the total height available to one
cell. Defaults to 0.1 for coupled-axes grids
and 0.3 for independent grids.
yside
Sets where the y axis labels and titles go.
"left" means the very left edge of the grid.
*left plot* is the leftmost plot that each y
axis is used in. "right" and *right plot* are
similar.
Returns
-------
plotly.graph_objs.layout.Grid
"""
return self["grid"]
| _layout.grid |
plotly.py | 22 | packages/python/plotly/plotly/graph_objs/_layout.py | def images(self):
"""
The 'images' property is a tuple of instances of
Image that may be specified as:
- A list or tuple of instances of plotly.graph_objs.layout.Image
- A list or tuple of dicts of string/value properties that
will be passed to the Image constructor
Supported dict properties:
layer
Specifies whether images are drawn below or
above traces. When `xref` and `yref` are both
set to `paper`, image is drawn below the entire
plot area.
name
When used in a template, named items are
created in the output figure in addition to any
items the figure already has in this array. You
can modify these items in the output figure by
making your own item with `templateitemname`
matching this `name` alongside your
modifications (including `visible: false` or
`enabled: false` to hide it). Has no effect
outside of a template.
opacity
Sets the opacity of the image.
sizex
Sets the image container size horizontally. The
image will be sized based on the `position`
value. When `xref` is set to `paper`, units are
sized relative to the plot width. When `xref`
ends with ` domain`, units are sized relative
to the axis width.
sizey
Sets the image container size vertically. The
image will be sized based on the `position`
value. When `yref` is set to `paper`, units are
sized relative to the plot height. When `yref`
ends with ` domain`, units are sized relative
to the axis height.
sizing
Specifies which dimension of the image to
constrain.
source
Specifies the URL of the image to be used. The
URL must be accessible from the domain where
the plot code is run, and can be either
relative or absolute.
templateitemname
Used to refer to a named item in this array in
the template. Named items from the template
will be created even without a matching item in
the input figure, but you can modify one by
making an item with `templateitemname` matching
its `name`, alongside your modifications
(including `visible: false` or `enabled: false`
to hide it). If there is no template or no
matching item, this item will be hidden unless
you explicitly show it with `visible: true`.
visible
Determines whether or not this image is
visible.
x
Sets the image's x position. When `xref` is set
to `paper`, units are sized relative to the
plot height. See `xref` for more info
xanchor
Sets the anchor for the x position
xref
Sets the images's x coordinate axis. If set to
a x axis id (e.g. "x" or "x2"), the `x`
position refers to a x coordinate. If set to
"paper", the `x` position refers to the
distance from the left of the plotting area in
normalized coordinates where 0 (1) corresponds
to the left (right). If set to a x axis ID
followed by "domain" (separated by a space),
the position behaves like for "paper", but
refers to the distance in fractions of the
domain length from the left of the domain of
that axis: e.g., *x2 domain* refers to the
domain of the second x axis and a x position
of 0.5 refers to the point between the left and
the right of the domain of the second x axis.
y
Sets the image's y position. When `yref` is set
to `paper`, units are sized relative to the
plot height. See `yref` for more info
yanchor
Sets the anchor for the y position.
yref
Sets the images's y coordinate axis. If set to
a y axis id (e.g. "y" or "y2"), the `y`
position refers to a y coordinate. If set to
"paper", the `y` position refers to the
distance from the bottom of the plotting area
in normalized coordinates where 0 (1)
corresponds to the bottom (top). If set to a y
axis ID followed by "domain" (separated by a
space), the position behaves like for "paper",
but refers to the distance in fractions of the
domain length from the bottom of the domain of
that axis: e.g., *y2 domain* refers to the
domain of the second y axis and a y position
of 0.5 refers to the point between the bottom
and the top of the domain of the second y axis.
Returns
-------
tuple[plotly.graph_objs.layout.Image]
"""
| /usr/src/app/target_test_cases/failed_tests__layout.images.txt | def images(self):
"""
The 'images' property is a tuple of instances of
Image that may be specified as:
- A list or tuple of instances of plotly.graph_objs.layout.Image
- A list or tuple of dicts of string/value properties that
will be passed to the Image constructor
Supported dict properties:
layer
Specifies whether images are drawn below or
above traces. When `xref` and `yref` are both
set to `paper`, image is drawn below the entire
plot area.
name
When used in a template, named items are
created in the output figure in addition to any
items the figure already has in this array. You
can modify these items in the output figure by
making your own item with `templateitemname`
matching this `name` alongside your
modifications (including `visible: false` or
`enabled: false` to hide it). Has no effect
outside of a template.
opacity
Sets the opacity of the image.
sizex
Sets the image container size horizontally. The
image will be sized based on the `position`
value. When `xref` is set to `paper`, units are
sized relative to the plot width. When `xref`
ends with ` domain`, units are sized relative
to the axis width.
sizey
Sets the image container size vertically. The
image will be sized based on the `position`
value. When `yref` is set to `paper`, units are
sized relative to the plot height. When `yref`
ends with ` domain`, units are sized relative
to the axis height.
sizing
Specifies which dimension of the image to
constrain.
source
Specifies the URL of the image to be used. The
URL must be accessible from the domain where
the plot code is run, and can be either
relative or absolute.
templateitemname
Used to refer to a named item in this array in
the template. Named items from the template
will be created even without a matching item in
the input figure, but you can modify one by
making an item with `templateitemname` matching
its `name`, alongside your modifications
(including `visible: false` or `enabled: false`
to hide it). If there is no template or no
matching item, this item will be hidden unless
you explicitly show it with `visible: true`.
visible
Determines whether or not this image is
visible.
x
Sets the image's x position. When `xref` is set
to `paper`, units are sized relative to the
plot height. See `xref` for more info
xanchor
Sets the anchor for the x position
xref
Sets the images's x coordinate axis. If set to
a x axis id (e.g. "x" or "x2"), the `x`
position refers to a x coordinate. If set to
"paper", the `x` position refers to the
distance from the left of the plotting area in
normalized coordinates where 0 (1) corresponds
to the left (right). If set to a x axis ID
followed by "domain" (separated by a space),
the position behaves like for "paper", but
refers to the distance in fractions of the
domain length from the left of the domain of
that axis: e.g., *x2 domain* refers to the
domain of the second x axis and a x position
of 0.5 refers to the point between the left and
the right of the domain of the second x axis.
y
Sets the image's y position. When `yref` is set
to `paper`, units are sized relative to the
plot height. See `yref` for more info
yanchor
Sets the anchor for the y position.
yref
Sets the images's y coordinate axis. If set to
a y axis id (e.g. "y" or "y2"), the `y`
position refers to a y coordinate. If set to
"paper", the `y` position refers to the
distance from the bottom of the plotting area
in normalized coordinates where 0 (1)
corresponds to the bottom (top). If set to a y
axis ID followed by "domain" (separated by a
space), the position behaves like for "paper",
but refers to the distance in fractions of the
domain length from the bottom of the domain of
that axis: e.g., *y2 domain* refers to the
domain of the second y axis and a y position
of 0.5 refers to the point between the bottom
and the top of the domain of the second y axis.
Returns
-------
tuple[plotly.graph_objs.layout.Image]
"""
return self["images"]
| _layout.images |
plotly.py | 23 | packages/python/plotly/plotly/graph_objs/_layout.py | def legend(self):
"""
The 'legend' property is an instance of Legend
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.Legend`
- A dict of string/value properties that will be passed
to the Legend constructor
Supported dict properties:
bgcolor
Sets the legend background color. Defaults to
`layout.paper_bgcolor`.
bordercolor
Sets the color of the border enclosing the
legend.
borderwidth
Sets the width (in px) of the border enclosing
the legend.
entrywidth
Sets the width (in px or fraction) of the
legend. Use 0 to size the entry based on the
text width, when `entrywidthmode` is set to
"pixels".
entrywidthmode
Determines what entrywidth means.
font
Sets the font used to text the legend items.
groupclick
Determines the behavior on legend group item
click. "toggleitem" toggles the visibility of
the individual item clicked on the graph.
"togglegroup" toggles the visibility of all
items in the same legendgroup as the item
clicked on the graph.
grouptitlefont
Sets the font for group titles in legend.
Defaults to `legend.font` with its size
increased about 10%.
indentation
Sets the indentation (in px) of the legend
entries.
itemclick
Determines the behavior on legend item click.
"toggle" toggles the visibility of the item
clicked on the graph. "toggleothers" makes the
clicked item the sole visible item on the
graph. False disables legend item click
interactions.
itemdoubleclick
Determines the behavior on legend item double-
click. "toggle" toggles the visibility of the
item clicked on the graph. "toggleothers" makes
the clicked item the sole visible item on the
graph. False disables legend item double-click
interactions.
itemsizing
Determines if the legend items symbols scale
with their corresponding "trace" attributes or
remain "constant" independent of the symbol
size on the graph.
itemwidth
Sets the width (in px) of the legend item
symbols (the part other than the title.text).
orientation
Sets the orientation of the legend.
title
:class:`plotly.graph_objects.layout.legend.Titl
e` instance or dict with compatible properties
tracegroupgap
Sets the amount of vertical space (in px)
between legend groups.
traceorder
Determines the order at which the legend items
are displayed. If "normal", the items are
displayed top-to-bottom in the same order as
the input data. If "reversed", the items are
displayed in the opposite order as "normal". If
"grouped", the items are displayed in groups
(when a trace `legendgroup` is provided). if
"grouped+reversed", the items are displayed in
the opposite order as "grouped".
uirevision
Controls persistence of legend-driven changes
in trace and pie label visibility. Defaults to
`layout.uirevision`.
valign
Sets the vertical alignment of the symbols with
respect to their associated text.
visible
Determines whether or not this legend is
visible.
x
Sets the x position with respect to `xref` (in
normalized coordinates) of the legend. When
`xref` is "paper", defaults to 1.02 for
vertical legends and defaults to 0 for
horizontal legends. When `xref` is "container",
defaults to 1 for vertical legends and defaults
to 0 for horizontal legends. Must be between 0
and 1 if `xref` is "container". and between
"-2" and 3 if `xref` is "paper".
xanchor
Sets the legend's horizontal position anchor.
This anchor binds the `x` position to the
"left", "center" or "right" of the legend.
Value "auto" anchors legends to the right for
`x` values greater than or equal to 2/3,
anchors legends to the left for `x` values less
than or equal to 1/3 and anchors legends with
respect to their center otherwise.
xref
Sets the container `x` refers to. "container"
spans the entire `width` of the plot. "paper"
refers to the width of the plotting area only.
y
Sets the y position with respect to `yref` (in
normalized coordinates) of the legend. When
`yref` is "paper", defaults to 1 for vertical
legends, defaults to "-0.1" for horizontal
legends on graphs w/o range sliders and
defaults to 1.1 for horizontal legends on graph
with one or multiple range sliders. When `yref`
is "container", defaults to 1. Must be between
0 and 1 if `yref` is "container" and between
"-2" and 3 if `yref` is "paper".
yanchor
Sets the legend's vertical position anchor This
anchor binds the `y` position to the "top",
"middle" or "bottom" of the legend. Value
"auto" anchors legends at their bottom for `y`
values less than or equal to 1/3, anchors
legends to at their top for `y` values greater
than or equal to 2/3 and anchors legends with
respect to their middle otherwise.
yref
Sets the container `y` refers to. "container"
spans the entire `height` of the plot. "paper"
refers to the height of the plotting area only.
Returns
-------
plotly.graph_objs.layout.Legend
"""
| /usr/src/app/target_test_cases/failed_tests__layout.legend.txt | def legend(self):
"""
The 'legend' property is an instance of Legend
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.Legend`
- A dict of string/value properties that will be passed
to the Legend constructor
Supported dict properties:
bgcolor
Sets the legend background color. Defaults to
`layout.paper_bgcolor`.
bordercolor
Sets the color of the border enclosing the
legend.
borderwidth
Sets the width (in px) of the border enclosing
the legend.
entrywidth
Sets the width (in px or fraction) of the
legend. Use 0 to size the entry based on the
text width, when `entrywidthmode` is set to
"pixels".
entrywidthmode
Determines what entrywidth means.
font
Sets the font used to text the legend items.
groupclick
Determines the behavior on legend group item
click. "toggleitem" toggles the visibility of
the individual item clicked on the graph.
"togglegroup" toggles the visibility of all
items in the same legendgroup as the item
clicked on the graph.
grouptitlefont
Sets the font for group titles in legend.
Defaults to `legend.font` with its size
increased about 10%.
indentation
Sets the indentation (in px) of the legend
entries.
itemclick
Determines the behavior on legend item click.
"toggle" toggles the visibility of the item
clicked on the graph. "toggleothers" makes the
clicked item the sole visible item on the
graph. False disables legend item click
interactions.
itemdoubleclick
Determines the behavior on legend item double-
click. "toggle" toggles the visibility of the
item clicked on the graph. "toggleothers" makes
the clicked item the sole visible item on the
graph. False disables legend item double-click
interactions.
itemsizing
Determines if the legend items symbols scale
with their corresponding "trace" attributes or
remain "constant" independent of the symbol
size on the graph.
itemwidth
Sets the width (in px) of the legend item
symbols (the part other than the title.text).
orientation
Sets the orientation of the legend.
title
:class:`plotly.graph_objects.layout.legend.Titl
e` instance or dict with compatible properties
tracegroupgap
Sets the amount of vertical space (in px)
between legend groups.
traceorder
Determines the order at which the legend items
are displayed. If "normal", the items are
displayed top-to-bottom in the same order as
the input data. If "reversed", the items are
displayed in the opposite order as "normal". If
"grouped", the items are displayed in groups
(when a trace `legendgroup` is provided). if
"grouped+reversed", the items are displayed in
the opposite order as "grouped".
uirevision
Controls persistence of legend-driven changes
in trace and pie label visibility. Defaults to
`layout.uirevision`.
valign
Sets the vertical alignment of the symbols with
respect to their associated text.
visible
Determines whether or not this legend is
visible.
x
Sets the x position with respect to `xref` (in
normalized coordinates) of the legend. When
`xref` is "paper", defaults to 1.02 for
vertical legends and defaults to 0 for
horizontal legends. When `xref` is "container",
defaults to 1 for vertical legends and defaults
to 0 for horizontal legends. Must be between 0
and 1 if `xref` is "container". and between
"-2" and 3 if `xref` is "paper".
xanchor
Sets the legend's horizontal position anchor.
This anchor binds the `x` position to the
"left", "center" or "right" of the legend.
Value "auto" anchors legends to the right for
`x` values greater than or equal to 2/3,
anchors legends to the left for `x` values less
than or equal to 1/3 and anchors legends with
respect to their center otherwise.
xref
Sets the container `x` refers to. "container"
spans the entire `width` of the plot. "paper"
refers to the width of the plotting area only.
y
Sets the y position with respect to `yref` (in
normalized coordinates) of the legend. When
`yref` is "paper", defaults to 1 for vertical
legends, defaults to "-0.1" for horizontal
legends on graphs w/o range sliders and
defaults to 1.1 for horizontal legends on graph
with one or multiple range sliders. When `yref`
is "container", defaults to 1. Must be between
0 and 1 if `yref` is "container" and between
"-2" and 3 if `yref` is "paper".
yanchor
Sets the legend's vertical position anchor This
anchor binds the `y` position to the "top",
"middle" or "bottom" of the legend. Value
"auto" anchors legends at their bottom for `y`
values less than or equal to 1/3, anchors
legends to at their top for `y` values greater
than or equal to 2/3 and anchors legends with
respect to their middle otherwise.
yref
Sets the container `y` refers to. "container"
spans the entire `height` of the plot. "paper"
refers to the height of the plotting area only.
Returns
-------
plotly.graph_objs.layout.Legend
"""
return self["legend"]
| _layout.legend |
plotly.py | 24 | packages/python/plotly/plotly/graph_objs/_layout.py | def mapbox(self):
"""
The 'mapbox' property is an instance of Mapbox
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.Mapbox`
- A dict of string/value properties that will be passed
to the Mapbox constructor
Supported dict properties:
accesstoken
Sets the mapbox access token to be used for
this mapbox map. Alternatively, the mapbox
access token can be set in the configuration
options under `mapboxAccessToken`. Note that
accessToken are only required when `style` (e.g
with values : basic, streets, outdoors, light,
dark, satellite, satellite-streets ) and/or a
layout layer references the Mapbox server.
bearing
Sets the bearing angle of the map in degrees
counter-clockwise from North (mapbox.bearing).
bounds
:class:`plotly.graph_objects.layout.mapbox.Boun
ds` instance or dict with compatible properties
center
:class:`plotly.graph_objects.layout.mapbox.Cent
er` instance or dict with compatible properties
domain
:class:`plotly.graph_objects.layout.mapbox.Doma
in` instance or dict with compatible properties
layers
A tuple of :class:`plotly.graph_objects.layout.
mapbox.Layer` instances or dicts with
compatible properties
layerdefaults
When used in a template (as
layout.template.layout.mapbox.layerdefaults),
sets the default property values to use for
elements of layout.mapbox.layers
pitch
Sets the pitch angle of the map (in degrees,
where 0 means perpendicular to the surface of
the map) (mapbox.pitch).
style
Defines the map layers that are rendered by
default below the trace layers defined in
`data`, which are themselves by default
rendered below the layers defined in
`layout.mapbox.layers`. These layers can be
defined either explicitly as a Mapbox Style
object which can contain multiple layer
definitions that load data from any public or
private Tile Map Service (TMS or XYZ) or Web
Map Service (WMS) or implicitly by using one of
the built-in style objects which use WMSes
which do not require any access tokens, or by
using a default Mapbox style or custom Mapbox
style URL, both of which require a Mapbox
access token Note that Mapbox access token can
be set in the `accesstoken` attribute or in the
`mapboxAccessToken` config option. Mapbox
Style objects are of the form described in the
Mapbox GL JS documentation available at
https://docs.mapbox.com/mapbox-gl-js/style-spec
The built-in plotly.js styles objects are:
carto-darkmatter, carto-positron, open-street-
map, stamen-terrain, stamen-toner, stamen-
watercolor, white-bg The built-in Mapbox
styles are: basic, streets, outdoors, light,
dark, satellite, satellite-streets Mapbox
style URLs are of the form:
mapbox://mapbox.mapbox-<name>-<version>
uirevision
Controls persistence of user-driven changes in
the view: `center`, `zoom`, `bearing`, `pitch`.
Defaults to `layout.uirevision`.
zoom
Sets the zoom level of the map (mapbox.zoom).
Returns
-------
plotly.graph_objs.layout.Mapbox
"""
| /usr/src/app/target_test_cases/failed_tests__layout.mapbox.txt | def mapbox(self):
"""
The 'mapbox' property is an instance of Mapbox
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.Mapbox`
- A dict of string/value properties that will be passed
to the Mapbox constructor
Supported dict properties:
accesstoken
Sets the mapbox access token to be used for
this mapbox map. Alternatively, the mapbox
access token can be set in the configuration
options under `mapboxAccessToken`. Note that
accessToken are only required when `style` (e.g
with values : basic, streets, outdoors, light,
dark, satellite, satellite-streets ) and/or a
layout layer references the Mapbox server.
bearing
Sets the bearing angle of the map in degrees
counter-clockwise from North (mapbox.bearing).
bounds
:class:`plotly.graph_objects.layout.mapbox.Boun
ds` instance or dict with compatible properties
center
:class:`plotly.graph_objects.layout.mapbox.Cent
er` instance or dict with compatible properties
domain
:class:`plotly.graph_objects.layout.mapbox.Doma
in` instance or dict with compatible properties
layers
A tuple of :class:`plotly.graph_objects.layout.
mapbox.Layer` instances or dicts with
compatible properties
layerdefaults
When used in a template (as
layout.template.layout.mapbox.layerdefaults),
sets the default property values to use for
elements of layout.mapbox.layers
pitch
Sets the pitch angle of the map (in degrees,
where 0 means perpendicular to the surface of
the map) (mapbox.pitch).
style
Defines the map layers that are rendered by
default below the trace layers defined in
`data`, which are themselves by default
rendered below the layers defined in
`layout.mapbox.layers`. These layers can be
defined either explicitly as a Mapbox Style
object which can contain multiple layer
definitions that load data from any public or
private Tile Map Service (TMS or XYZ) or Web
Map Service (WMS) or implicitly by using one of
the built-in style objects which use WMSes
which do not require any access tokens, or by
using a default Mapbox style or custom Mapbox
style URL, both of which require a Mapbox
access token Note that Mapbox access token can
be set in the `accesstoken` attribute or in the
`mapboxAccessToken` config option. Mapbox
Style objects are of the form described in the
Mapbox GL JS documentation available at
https://docs.mapbox.com/mapbox-gl-js/style-spec
The built-in plotly.js styles objects are:
carto-darkmatter, carto-positron, open-street-
map, stamen-terrain, stamen-toner, stamen-
watercolor, white-bg The built-in Mapbox
styles are: basic, streets, outdoors, light,
dark, satellite, satellite-streets Mapbox
style URLs are of the form:
mapbox://mapbox.mapbox-<name>-<version>
uirevision
Controls persistence of user-driven changes in
the view: `center`, `zoom`, `bearing`, `pitch`.
Defaults to `layout.uirevision`.
zoom
Sets the zoom level of the map (mapbox.zoom).
Returns
-------
plotly.graph_objs.layout.Mapbox
"""
return self["mapbox"]
| _layout.mapbox |
plotly.py | 25 | packages/python/plotly/plotly/graph_objs/_layout.py | def scene(self):
"""
The 'scene' property is an instance of Scene
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.Scene`
- A dict of string/value properties that will be passed
to the Scene constructor
Supported dict properties:
annotations
A tuple of :class:`plotly.graph_objects.layout.
scene.Annotation` instances or dicts with
compatible properties
annotationdefaults
When used in a template (as layout.template.lay
out.scene.annotationdefaults), sets the default
property values to use for elements of
layout.scene.annotations
aspectmode
If "cube", this scene's axes are drawn as a
cube, regardless of the axes' ranges. If
"data", this scene's axes are drawn in
proportion with the axes' ranges. If "manual",
this scene's axes are drawn in proportion with
the input of "aspectratio" (the default
behavior if "aspectratio" is provided). If
"auto", this scene's axes are drawn using the
results of "data" except when one axis is more
than four times the size of the two others,
where in that case the results of "cube" are
used.
aspectratio
Sets this scene's axis aspectratio.
bgcolor
camera
:class:`plotly.graph_objects.layout.scene.Camer
a` instance or dict with compatible properties
domain
:class:`plotly.graph_objects.layout.scene.Domai
n` instance or dict with compatible properties
dragmode
Determines the mode of drag interactions for
this scene.
hovermode
Determines the mode of hover interactions for
this scene.
uirevision
Controls persistence of user-driven changes in
camera attributes. Defaults to
`layout.uirevision`.
xaxis
:class:`plotly.graph_objects.layout.scene.XAxis
` instance or dict with compatible properties
yaxis
:class:`plotly.graph_objects.layout.scene.YAxis
` instance or dict with compatible properties
zaxis
:class:`plotly.graph_objects.layout.scene.ZAxis
` instance or dict with compatible properties
Returns
-------
plotly.graph_objs.layout.Scene
"""
| /usr/src/app/target_test_cases/failed_tests__layout.scene.txt | def scene(self):
"""
The 'scene' property is an instance of Scene
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.Scene`
- A dict of string/value properties that will be passed
to the Scene constructor
Supported dict properties:
annotations
A tuple of :class:`plotly.graph_objects.layout.
scene.Annotation` instances or dicts with
compatible properties
annotationdefaults
When used in a template (as layout.template.lay
out.scene.annotationdefaults), sets the default
property values to use for elements of
layout.scene.annotations
aspectmode
If "cube", this scene's axes are drawn as a
cube, regardless of the axes' ranges. If
"data", this scene's axes are drawn in
proportion with the axes' ranges. If "manual",
this scene's axes are drawn in proportion with
the input of "aspectratio" (the default
behavior if "aspectratio" is provided). If
"auto", this scene's axes are drawn using the
results of "data" except when one axis is more
than four times the size of the two others,
where in that case the results of "cube" are
used.
aspectratio
Sets this scene's axis aspectratio.
bgcolor
camera
:class:`plotly.graph_objects.layout.scene.Camer
a` instance or dict with compatible properties
domain
:class:`plotly.graph_objects.layout.scene.Domai
n` instance or dict with compatible properties
dragmode
Determines the mode of drag interactions for
this scene.
hovermode
Determines the mode of hover interactions for
this scene.
uirevision
Controls persistence of user-driven changes in
camera attributes. Defaults to
`layout.uirevision`.
xaxis
:class:`plotly.graph_objects.layout.scene.XAxis
` instance or dict with compatible properties
yaxis
:class:`plotly.graph_objects.layout.scene.YAxis
` instance or dict with compatible properties
zaxis
:class:`plotly.graph_objects.layout.scene.ZAxis
` instance or dict with compatible properties
Returns
-------
plotly.graph_objs.layout.Scene
"""
return self["scene"]
| _layout.scene |
plotly.py | 26 | packages/python/plotly/plotly/graph_objs/_layout.py | def shapes(self):
"""
The 'shapes' property is a tuple of instances of
Shape that may be specified as:
- A list or tuple of instances of plotly.graph_objs.layout.Shape
- A list or tuple of dicts of string/value properties that
will be passed to the Shape constructor
Supported dict properties:
editable
Determines whether the shape could be activated
for edit or not. Has no effect when the older
editable shapes mode is enabled via
`config.editable` or
`config.edits.shapePosition`.
fillcolor
Sets the color filling the shape's interior.
Only applies to closed shapes.
fillrule
Determines which regions of complex paths
constitute the interior. For more info please
visit https://developer.mozilla.org/en-
US/docs/Web/SVG/Attribute/fill-rule
label
:class:`plotly.graph_objects.layout.shape.Label
` instance or dict with compatible properties
layer
Specifies whether shapes are drawn below
gridlines ("below"), between gridlines and
traces ("between") or above traces ("above").
legend
Sets the reference to a legend to show this
shape in. References to these legends are
"legend", "legend2", "legend3", etc. Settings
for these legends are set in the layout, under
`layout.legend`, `layout.legend2`, etc.
legendgroup
Sets the legend group for this shape. Traces
and shapes part of the same legend group
hide/show at the same time when toggling legend
items.
legendgrouptitle
:class:`plotly.graph_objects.layout.shape.Legen
dgrouptitle` instance or dict with compatible
properties
legendrank
Sets the legend rank for this shape. Items and
groups with smaller ranks are presented on
top/left side while with "reversed"
`legend.traceorder` they are on bottom/right
side. The default legendrank is 1000, so that
you can use ranks less than 1000 to place
certain items before all unranked items, and
ranks greater than 1000 to go after all
unranked items. When having unranked or equal
rank items shapes would be displayed after
traces i.e. according to their order in data
and layout.
legendwidth
Sets the width (in px or fraction) of the
legend for this shape.
line
:class:`plotly.graph_objects.layout.shape.Line`
instance or dict with compatible properties
name
When used in a template, named items are
created in the output figure in addition to any
items the figure already has in this array. You
can modify these items in the output figure by
making your own item with `templateitemname`
matching this `name` alongside your
modifications (including `visible: false` or
`enabled: false` to hide it). Has no effect
outside of a template.
opacity
Sets the opacity of the shape.
path
For `type` "path" - a valid SVG path with the
pixel values replaced by data values in
`xsizemode`/`ysizemode` being "scaled" and
taken unmodified as pixels relative to
`xanchor` and `yanchor` in case of "pixel" size
mode. There are a few restrictions / quirks
only absolute instructions, not relative. So
the allowed segments are: M, L, H, V, Q, C, T,
S, and Z arcs (A) are not allowed because
radius rx and ry are relative. In the future we
could consider supporting relative commands,
but we would have to decide on how to handle
date and log axes. Note that even as is, Q and
C Bezier paths that are smooth on linear axes
may not be smooth on log, and vice versa. no
chained "polybezier" commands - specify the
segment type for each one. On category axes,
values are numbers scaled to the serial numbers
of categories because using the categories
themselves there would be no way to describe
fractional positions On data axes: because
space and T are both normal components of path
strings, we can't use either to separate date
from time parts. Therefore we'll use underscore
for this purpose: 2015-02-21_13:45:56.789
showlegend
Determines whether or not this shape is shown
in the legend.
templateitemname
Used to refer to a named item in this array in
the template. Named items from the template
will be created even without a matching item in
the input figure, but you can modify one by
making an item with `templateitemname` matching
its `name`, alongside your modifications
(including `visible: false` or `enabled: false`
to hide it). If there is no template or no
matching item, this item will be hidden unless
you explicitly show it with `visible: true`.
type
Specifies the shape type to be drawn. If
"line", a line is drawn from (`x0`,`y0`) to
(`x1`,`y1`) with respect to the axes' sizing
mode. If "circle", a circle is drawn from
((`x0`+`x1`)/2, (`y0`+`y1`)/2)) with radius
(|(`x0`+`x1`)/2 - `x0`|, |(`y0`+`y1`)/2
-`y0`)|) with respect to the axes' sizing mode.
If "rect", a rectangle is drawn linking
(`x0`,`y0`), (`x1`,`y0`), (`x1`,`y1`),
(`x0`,`y1`), (`x0`,`y0`) with respect to the
axes' sizing mode. If "path", draw a custom SVG
path using `path`. with respect to the axes'
sizing mode.
visible
Determines whether or not this shape is
visible. If "legendonly", the shape is not
drawn, but can appear as a legend item
(provided that the legend itself is visible).
x0
Sets the shape's starting x position. See
`type` and `xsizemode` for more info.
x0shift
Shifts `x0` away from the center of the
category when `xref` is a "category" or
"multicategory" axis. -0.5 corresponds to the
start of the category and 0.5 corresponds to
the end of the category.
x1
Sets the shape's end x position. See `type` and
`xsizemode` for more info.
x1shift
Shifts `x1` away from the center of the
category when `xref` is a "category" or
"multicategory" axis. -0.5 corresponds to the
start of the category and 0.5 corresponds to
the end of the category.
xanchor
Only relevant in conjunction with `xsizemode`
set to "pixel". Specifies the anchor point on
the x axis to which `x0`, `x1` and x
coordinates within `path` are relative to. E.g.
useful to attach a pixel sized shape to a
certain data value. No effect when `xsizemode`
not set to "pixel".
xref
Sets the shape's x coordinate axis. If set to a
x axis id (e.g. "x" or "x2"), the `x` position
refers to a x coordinate. If set to "paper",
the `x` position refers to the distance from
the left of the plotting area in normalized
coordinates where 0 (1) corresponds to the left
(right). If set to a x axis ID followed by
"domain" (separated by a space), the position
behaves like for "paper", but refers to the
distance in fractions of the domain length from
the left of the domain of that axis: e.g., *x2
domain* refers to the domain of the second x
axis and a x position of 0.5 refers to the
point between the left and the right of the
domain of the second x axis.
xsizemode
Sets the shapes's sizing mode along the x axis.
If set to "scaled", `x0`, `x1` and x
coordinates within `path` refer to data values
on the x axis or a fraction of the plot area's
width (`xref` set to "paper"). If set to
"pixel", `xanchor` specifies the x position in
terms of data or plot fraction but `x0`, `x1`
and x coordinates within `path` are pixels
relative to `xanchor`. This way, the shape can
have a fixed width while maintaining a position
relative to data or plot fraction.
y0
Sets the shape's starting y position. See
`type` and `ysizemode` for more info.
y0shift
Shifts `y0` away from the center of the
category when `yref` is a "category" or
"multicategory" axis. -0.5 corresponds to the
start of the category and 0.5 corresponds to
the end of the category.
y1
Sets the shape's end y position. See `type` and
`ysizemode` for more info.
y1shift
Shifts `y1` away from the center of the
category when `yref` is a "category" or
"multicategory" axis. -0.5 corresponds to the
start of the category and 0.5 corresponds to
the end of the category.
yanchor
Only relevant in conjunction with `ysizemode`
set to "pixel". Specifies the anchor point on
the y axis to which `y0`, `y1` and y
coordinates within `path` are relative to. E.g.
useful to attach a pixel sized shape to a
certain data value. No effect when `ysizemode`
not set to "pixel".
yref
Sets the shape's y coordinate axis. If set to a
y axis id (e.g. "y" or "y2"), the `y` position
refers to a y coordinate. If set to "paper",
the `y` position refers to the distance from
the bottom of the plotting area in normalized
coordinates where 0 (1) corresponds to the
bottom (top). If set to a y axis ID followed by
"domain" (separated by a space), the position
behaves like for "paper", but refers to the
distance in fractions of the domain length from
the bottom of the domain of that axis: e.g.,
*y2 domain* refers to the domain of the second
y axis and a y position of 0.5 refers to the
point between the bottom and the top of the
domain of the second y axis.
ysizemode
Sets the shapes's sizing mode along the y axis.
If set to "scaled", `y0`, `y1` and y
coordinates within `path` refer to data values
on the y axis or a fraction of the plot area's
height (`yref` set to "paper"). If set to
"pixel", `yanchor` specifies the y position in
terms of data or plot fraction but `y0`, `y1`
and y coordinates within `path` are pixels
relative to `yanchor`. This way, the shape can
have a fixed height while maintaining a
position relative to data or plot fraction.
Returns
-------
tuple[plotly.graph_objs.layout.Shape]
"""
| /usr/src/app/target_test_cases/failed_tests__layout.shapes.txt | def shapes(self):
"""
The 'shapes' property is a tuple of instances of
Shape that may be specified as:
- A list or tuple of instances of plotly.graph_objs.layout.Shape
- A list or tuple of dicts of string/value properties that
will be passed to the Shape constructor
Supported dict properties:
editable
Determines whether the shape could be activated
for edit or not. Has no effect when the older
editable shapes mode is enabled via
`config.editable` or
`config.edits.shapePosition`.
fillcolor
Sets the color filling the shape's interior.
Only applies to closed shapes.
fillrule
Determines which regions of complex paths
constitute the interior. For more info please
visit https://developer.mozilla.org/en-
US/docs/Web/SVG/Attribute/fill-rule
label
:class:`plotly.graph_objects.layout.shape.Label
` instance or dict with compatible properties
layer
Specifies whether shapes are drawn below
gridlines ("below"), between gridlines and
traces ("between") or above traces ("above").
legend
Sets the reference to a legend to show this
shape in. References to these legends are
"legend", "legend2", "legend3", etc. Settings
for these legends are set in the layout, under
`layout.legend`, `layout.legend2`, etc.
legendgroup
Sets the legend group for this shape. Traces
and shapes part of the same legend group
hide/show at the same time when toggling legend
items.
legendgrouptitle
:class:`plotly.graph_objects.layout.shape.Legen
dgrouptitle` instance or dict with compatible
properties
legendrank
Sets the legend rank for this shape. Items and
groups with smaller ranks are presented on
top/left side while with "reversed"
`legend.traceorder` they are on bottom/right
side. The default legendrank is 1000, so that
you can use ranks less than 1000 to place
certain items before all unranked items, and
ranks greater than 1000 to go after all
unranked items. When having unranked or equal
rank items shapes would be displayed after
traces i.e. according to their order in data
and layout.
legendwidth
Sets the width (in px or fraction) of the
legend for this shape.
line
:class:`plotly.graph_objects.layout.shape.Line`
instance or dict with compatible properties
name
When used in a template, named items are
created in the output figure in addition to any
items the figure already has in this array. You
can modify these items in the output figure by
making your own item with `templateitemname`
matching this `name` alongside your
modifications (including `visible: false` or
`enabled: false` to hide it). Has no effect
outside of a template.
opacity
Sets the opacity of the shape.
path
For `type` "path" - a valid SVG path with the
pixel values replaced by data values in
`xsizemode`/`ysizemode` being "scaled" and
taken unmodified as pixels relative to
`xanchor` and `yanchor` in case of "pixel" size
mode. There are a few restrictions / quirks
only absolute instructions, not relative. So
the allowed segments are: M, L, H, V, Q, C, T,
S, and Z arcs (A) are not allowed because
radius rx and ry are relative. In the future we
could consider supporting relative commands,
but we would have to decide on how to handle
date and log axes. Note that even as is, Q and
C Bezier paths that are smooth on linear axes
may not be smooth on log, and vice versa. no
chained "polybezier" commands - specify the
segment type for each one. On category axes,
values are numbers scaled to the serial numbers
of categories because using the categories
themselves there would be no way to describe
fractional positions On data axes: because
space and T are both normal components of path
strings, we can't use either to separate date
from time parts. Therefore we'll use underscore
for this purpose: 2015-02-21_13:45:56.789
showlegend
Determines whether or not this shape is shown
in the legend.
templateitemname
Used to refer to a named item in this array in
the template. Named items from the template
will be created even without a matching item in
the input figure, but you can modify one by
making an item with `templateitemname` matching
its `name`, alongside your modifications
(including `visible: false` or `enabled: false`
to hide it). If there is no template or no
matching item, this item will be hidden unless
you explicitly show it with `visible: true`.
type
Specifies the shape type to be drawn. If
"line", a line is drawn from (`x0`,`y0`) to
(`x1`,`y1`) with respect to the axes' sizing
mode. If "circle", a circle is drawn from
((`x0`+`x1`)/2, (`y0`+`y1`)/2)) with radius
(|(`x0`+`x1`)/2 - `x0`|, |(`y0`+`y1`)/2
-`y0`)|) with respect to the axes' sizing mode.
If "rect", a rectangle is drawn linking
(`x0`,`y0`), (`x1`,`y0`), (`x1`,`y1`),
(`x0`,`y1`), (`x0`,`y0`) with respect to the
axes' sizing mode. If "path", draw a custom SVG
path using `path`. with respect to the axes'
sizing mode.
visible
Determines whether or not this shape is
visible. If "legendonly", the shape is not
drawn, but can appear as a legend item
(provided that the legend itself is visible).
x0
Sets the shape's starting x position. See
`type` and `xsizemode` for more info.
x0shift
Shifts `x0` away from the center of the
category when `xref` is a "category" or
"multicategory" axis. -0.5 corresponds to the
start of the category and 0.5 corresponds to
the end of the category.
x1
Sets the shape's end x position. See `type` and
`xsizemode` for more info.
x1shift
Shifts `x1` away from the center of the
category when `xref` is a "category" or
"multicategory" axis. -0.5 corresponds to the
start of the category and 0.5 corresponds to
the end of the category.
xanchor
Only relevant in conjunction with `xsizemode`
set to "pixel". Specifies the anchor point on
the x axis to which `x0`, `x1` and x
coordinates within `path` are relative to. E.g.
useful to attach a pixel sized shape to a
certain data value. No effect when `xsizemode`
not set to "pixel".
xref
Sets the shape's x coordinate axis. If set to a
x axis id (e.g. "x" or "x2"), the `x` position
refers to a x coordinate. If set to "paper",
the `x` position refers to the distance from
the left of the plotting area in normalized
coordinates where 0 (1) corresponds to the left
(right). If set to a x axis ID followed by
"domain" (separated by a space), the position
behaves like for "paper", but refers to the
distance in fractions of the domain length from
the left of the domain of that axis: e.g., *x2
domain* refers to the domain of the second x
axis and a x position of 0.5 refers to the
point between the left and the right of the
domain of the second x axis.
xsizemode
Sets the shapes's sizing mode along the x axis.
If set to "scaled", `x0`, `x1` and x
coordinates within `path` refer to data values
on the x axis or a fraction of the plot area's
width (`xref` set to "paper"). If set to
"pixel", `xanchor` specifies the x position in
terms of data or plot fraction but `x0`, `x1`
and x coordinates within `path` are pixels
relative to `xanchor`. This way, the shape can
have a fixed width while maintaining a position
relative to data or plot fraction.
y0
Sets the shape's starting y position. See
`type` and `ysizemode` for more info.
y0shift
Shifts `y0` away from the center of the
category when `yref` is a "category" or
"multicategory" axis. -0.5 corresponds to the
start of the category and 0.5 corresponds to
the end of the category.
y1
Sets the shape's end y position. See `type` and
`ysizemode` for more info.
y1shift
Shifts `y1` away from the center of the
category when `yref` is a "category" or
"multicategory" axis. -0.5 corresponds to the
start of the category and 0.5 corresponds to
the end of the category.
yanchor
Only relevant in conjunction with `ysizemode`
set to "pixel". Specifies the anchor point on
the y axis to which `y0`, `y1` and y
coordinates within `path` are relative to. E.g.
useful to attach a pixel sized shape to a
certain data value. No effect when `ysizemode`
not set to "pixel".
yref
Sets the shape's y coordinate axis. If set to a
y axis id (e.g. "y" or "y2"), the `y` position
refers to a y coordinate. If set to "paper",
the `y` position refers to the distance from
the bottom of the plotting area in normalized
coordinates where 0 (1) corresponds to the
bottom (top). If set to a y axis ID followed by
"domain" (separated by a space), the position
behaves like for "paper", but refers to the
distance in fractions of the domain length from
the bottom of the domain of that axis: e.g.,
*y2 domain* refers to the domain of the second
y axis and a y position of 0.5 refers to the
point between the bottom and the top of the
domain of the second y axis.
ysizemode
Sets the shapes's sizing mode along the y axis.
If set to "scaled", `y0`, `y1` and y
coordinates within `path` refer to data values
on the y axis or a fraction of the plot area's
height (`yref` set to "paper"). If set to
"pixel", `yanchor` specifies the y position in
terms of data or plot fraction but `y0`, `y1`
and y coordinates within `path` are pixels
relative to `yanchor`. This way, the shape can
have a fixed height while maintaining a
position relative to data or plot fraction.
Returns
-------
tuple[plotly.graph_objs.layout.Shape]
"""
return self["shapes"]
| _layout.shapes |
plotly.py | 27 | packages/python/plotly/plotly/graph_objs/_layout.py | def sliders(self):
"""
The 'sliders' property is a tuple of instances of
Slider that may be specified as:
- A list or tuple of instances of plotly.graph_objs.layout.Slider
- A list or tuple of dicts of string/value properties that
will be passed to the Slider constructor
Supported dict properties:
active
Determines which button (by index starting from
0) is considered active.
activebgcolor
Sets the background color of the slider grip
while dragging.
bgcolor
Sets the background color of the slider.
bordercolor
Sets the color of the border enclosing the
slider.
borderwidth
Sets the width (in px) of the border enclosing
the slider.
currentvalue
:class:`plotly.graph_objects.layout.slider.Curr
entvalue` instance or dict with compatible
properties
font
Sets the font of the slider step labels.
len
Sets the length of the slider This measure
excludes the padding of both ends. That is, the
slider's length is this length minus the
padding on both ends.
lenmode
Determines whether this slider length is set in
units of plot "fraction" or in *pixels. Use
`len` to set the value.
minorticklen
Sets the length in pixels of minor step tick
marks
name
When used in a template, named items are
created in the output figure in addition to any
items the figure already has in this array. You
can modify these items in the output figure by
making your own item with `templateitemname`
matching this `name` alongside your
modifications (including `visible: false` or
`enabled: false` to hide it). Has no effect
outside of a template.
pad
Set the padding of the slider component along
each side.
steps
A tuple of :class:`plotly.graph_objects.layout.
slider.Step` instances or dicts with compatible
properties
stepdefaults
When used in a template (as
layout.template.layout.slider.stepdefaults),
sets the default property values to use for
elements of layout.slider.steps
templateitemname
Used to refer to a named item in this array in
the template. Named items from the template
will be created even without a matching item in
the input figure, but you can modify one by
making an item with `templateitemname` matching
its `name`, alongside your modifications
(including `visible: false` or `enabled: false`
to hide it). If there is no template or no
matching item, this item will be hidden unless
you explicitly show it with `visible: true`.
tickcolor
Sets the color of the border enclosing the
slider.
ticklen
Sets the length in pixels of step tick marks
tickwidth
Sets the tick width (in px).
transition
:class:`plotly.graph_objects.layout.slider.Tran
sition` instance or dict with compatible
properties
visible
Determines whether or not the slider is
visible.
x
Sets the x position (in normalized coordinates)
of the slider.
xanchor
Sets the slider's horizontal position anchor.
This anchor binds the `x` position to the
"left", "center" or "right" of the range
selector.
y
Sets the y position (in normalized coordinates)
of the slider.
yanchor
Sets the slider's vertical position anchor This
anchor binds the `y` position to the "top",
"middle" or "bottom" of the range selector.
Returns
-------
tuple[plotly.graph_objs.layout.Slider]
"""
| /usr/src/app/target_test_cases/failed_tests__layout.sliders.txt | def sliders(self):
"""
The 'sliders' property is a tuple of instances of
Slider that may be specified as:
- A list or tuple of instances of plotly.graph_objs.layout.Slider
- A list or tuple of dicts of string/value properties that
will be passed to the Slider constructor
Supported dict properties:
active
Determines which button (by index starting from
0) is considered active.
activebgcolor
Sets the background color of the slider grip
while dragging.
bgcolor
Sets the background color of the slider.
bordercolor
Sets the color of the border enclosing the
slider.
borderwidth
Sets the width (in px) of the border enclosing
the slider.
currentvalue
:class:`plotly.graph_objects.layout.slider.Curr
entvalue` instance or dict with compatible
properties
font
Sets the font of the slider step labels.
len
Sets the length of the slider This measure
excludes the padding of both ends. That is, the
slider's length is this length minus the
padding on both ends.
lenmode
Determines whether this slider length is set in
units of plot "fraction" or in *pixels. Use
`len` to set the value.
minorticklen
Sets the length in pixels of minor step tick
marks
name
When used in a template, named items are
created in the output figure in addition to any
items the figure already has in this array. You
can modify these items in the output figure by
making your own item with `templateitemname`
matching this `name` alongside your
modifications (including `visible: false` or
`enabled: false` to hide it). Has no effect
outside of a template.
pad
Set the padding of the slider component along
each side.
steps
A tuple of :class:`plotly.graph_objects.layout.
slider.Step` instances or dicts with compatible
properties
stepdefaults
When used in a template (as
layout.template.layout.slider.stepdefaults),
sets the default property values to use for
elements of layout.slider.steps
templateitemname
Used to refer to a named item in this array in
the template. Named items from the template
will be created even without a matching item in
the input figure, but you can modify one by
making an item with `templateitemname` matching
its `name`, alongside your modifications
(including `visible: false` or `enabled: false`
to hide it). If there is no template or no
matching item, this item will be hidden unless
you explicitly show it with `visible: true`.
tickcolor
Sets the color of the border enclosing the
slider.
ticklen
Sets the length in pixels of step tick marks
tickwidth
Sets the tick width (in px).
transition
:class:`plotly.graph_objects.layout.slider.Tran
sition` instance or dict with compatible
properties
visible
Determines whether or not the slider is
visible.
x
Sets the x position (in normalized coordinates)
of the slider.
xanchor
Sets the slider's horizontal position anchor.
This anchor binds the `x` position to the
"left", "center" or "right" of the range
selector.
y
Sets the y position (in normalized coordinates)
of the slider.
yanchor
Sets the slider's vertical position anchor This
anchor binds the `y` position to the "top",
"middle" or "bottom" of the range selector.
Returns
-------
tuple[plotly.graph_objs.layout.Slider]
"""
return self["sliders"]
| _layout.sliders |
plotly.py | 28 | packages/python/plotly/plotly/graph_objs/_layout.py | def title(self):
"""
The 'title' property is an instance of Title
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.Title`
- A dict of string/value properties that will be passed
to the Title constructor
Supported dict properties:
automargin
Determines whether the title can automatically
push the figure margins. If `yref='paper'` then
the margin will expand to ensure that the title
doesn’t overlap with the edges of the
container. If `yref='container'` then the
margins will ensure that the title doesn’t
overlap with the plot area, tick labels, and
axis titles. If `automargin=true` and the
margins need to be expanded, then y will be set
to a default 1 and yanchor will be set to an
appropriate default to ensure that minimal
margin space is needed. Note that when
`yref='paper'`, only 1 or 0 are allowed y
values. Invalid values will be reset to the
default 1.
font
Sets the title font. Note that the title's font
used to be customized by the now deprecated
`titlefont` attribute.
pad
Sets the padding of the title. Each padding
value only applies when the corresponding
`xanchor`/`yanchor` value is set accordingly.
E.g. for left padding to take effect, `xanchor`
must be set to "left". The same rule applies if
`xanchor`/`yanchor` is determined
automatically. Padding is muted if the
respective anchor value is "middle*/*center".
subtitle
:class:`plotly.graph_objects.layout.title.Subti
tle` instance or dict with compatible
properties
text
Sets the plot's title. Note that before the
existence of `title.text`, the title's contents
used to be defined as the `title` attribute
itself. This behavior has been deprecated.
x
Sets the x position with respect to `xref` in
normalized coordinates from 0 (left) to 1
(right).
xanchor
Sets the title's horizontal alignment with
respect to its x position. "left" means that
the title starts at x, "right" means that the
title ends at x and "center" means that the
title's center is at x. "auto" divides `xref`
by three and calculates the `xanchor` value
automatically based on the value of `x`.
xref
Sets the container `x` refers to. "container"
spans the entire `width` of the plot. "paper"
refers to the width of the plotting area only.
y
Sets the y position with respect to `yref` in
normalized coordinates from 0 (bottom) to 1
(top). "auto" places the baseline of the title
onto the vertical center of the top margin.
yanchor
Sets the title's vertical alignment with
respect to its y position. "top" means that the
title's cap line is at y, "bottom" means that
the title's baseline is at y and "middle" means
that the title's midline is at y. "auto"
divides `yref` by three and calculates the
`yanchor` value automatically based on the
value of `y`.
yref
Sets the container `y` refers to. "container"
spans the entire `height` of the plot. "paper"
refers to the height of the plotting area only.
Returns
-------
plotly.graph_objs.layout.Title
"""
| /usr/src/app/target_test_cases/failed_tests__layout.title.txt | def title(self):
"""
The 'title' property is an instance of Title
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.Title`
- A dict of string/value properties that will be passed
to the Title constructor
Supported dict properties:
automargin
Determines whether the title can automatically
push the figure margins. If `yref='paper'` then
the margin will expand to ensure that the title
doesn’t overlap with the edges of the
container. If `yref='container'` then the
margins will ensure that the title doesn’t
overlap with the plot area, tick labels, and
axis titles. If `automargin=true` and the
margins need to be expanded, then y will be set
to a default 1 and yanchor will be set to an
appropriate default to ensure that minimal
margin space is needed. Note that when
`yref='paper'`, only 1 or 0 are allowed y
values. Invalid values will be reset to the
default 1.
font
Sets the title font. Note that the title's font
used to be customized by the now deprecated
`titlefont` attribute.
pad
Sets the padding of the title. Each padding
value only applies when the corresponding
`xanchor`/`yanchor` value is set accordingly.
E.g. for left padding to take effect, `xanchor`
must be set to "left". The same rule applies if
`xanchor`/`yanchor` is determined
automatically. Padding is muted if the
respective anchor value is "middle*/*center".
subtitle
:class:`plotly.graph_objects.layout.title.Subti
tle` instance or dict with compatible
properties
text
Sets the plot's title. Note that before the
existence of `title.text`, the title's contents
used to be defined as the `title` attribute
itself. This behavior has been deprecated.
x
Sets the x position with respect to `xref` in
normalized coordinates from 0 (left) to 1
(right).
xanchor
Sets the title's horizontal alignment with
respect to its x position. "left" means that
the title starts at x, "right" means that the
title ends at x and "center" means that the
title's center is at x. "auto" divides `xref`
by three and calculates the `xanchor` value
automatically based on the value of `x`.
xref
Sets the container `x` refers to. "container"
spans the entire `width` of the plot. "paper"
refers to the width of the plotting area only.
y
Sets the y position with respect to `yref` in
normalized coordinates from 0 (bottom) to 1
(top). "auto" places the baseline of the title
onto the vertical center of the top margin.
yanchor
Sets the title's vertical alignment with
respect to its y position. "top" means that the
title's cap line is at y, "bottom" means that
the title's baseline is at y and "middle" means
that the title's midline is at y. "auto"
divides `yref` by three and calculates the
`yanchor` value automatically based on the
value of `y`.
yref
Sets the container `y` refers to. "container"
spans the entire `height` of the plot. "paper"
refers to the height of the plotting area only.
Returns
-------
plotly.graph_objs.layout.Title
"""
return self["title"]
| _layout.title |
plotly.py | 29 | packages/python/plotly/plotly/graph_objs/layout/_legend.py | def __init__(
self,
arg=None,
bgcolor=None,
bordercolor=None,
borderwidth=None,
entrywidth=None,
entrywidthmode=None,
font=None,
groupclick=None,
grouptitlefont=None,
indentation=None,
itemclick=None,
itemdoubleclick=None,
itemsizing=None,
itemwidth=None,
orientation=None,
title=None,
tracegroupgap=None,
traceorder=None,
uirevision=None,
valign=None,
visible=None,
x=None,
xanchor=None,
xref=None,
y=None,
yanchor=None,
yref=None,
**kwargs,
):
"""
Construct a new Legend object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.layout.Legend`
bgcolor
Sets the legend background color. Defaults to
`layout.paper_bgcolor`.
bordercolor
Sets the color of the border enclosing the legend.
borderwidth
Sets the width (in px) of the border enclosing the
legend.
entrywidth
Sets the width (in px or fraction) of the legend. Use 0
to size the entry based on the text width, when
`entrywidthmode` is set to "pixels".
entrywidthmode
Determines what entrywidth means.
font
Sets the font used to text the legend items.
groupclick
Determines the behavior on legend group item click.
"toggleitem" toggles the visibility of the individual
item clicked on the graph. "togglegroup" toggles the
visibility of all items in the same legendgroup as the
item clicked on the graph.
grouptitlefont
Sets the font for group titles in legend. Defaults to
`legend.font` with its size increased about 10%.
indentation
Sets the indentation (in px) of the legend entries.
itemclick
Determines the behavior on legend item click. "toggle"
toggles the visibility of the item clicked on the
graph. "toggleothers" makes the clicked item the sole
visible item on the graph. False disables legend item
click interactions.
itemdoubleclick
Determines the behavior on legend item double-click.
"toggle" toggles the visibility of the item clicked on
the graph. "toggleothers" makes the clicked item the
sole visible item on the graph. False disables legend
item double-click interactions.
itemsizing
Determines if the legend items symbols scale with their
corresponding "trace" attributes or remain "constant"
independent of the symbol size on the graph.
itemwidth
Sets the width (in px) of the legend item symbols (the
part other than the title.text).
orientation
Sets the orientation of the legend.
title
:class:`plotly.graph_objects.layout.legend.Title`
instance or dict with compatible properties
tracegroupgap
Sets the amount of vertical space (in px) between
legend groups.
traceorder
Determines the order at which the legend items are
displayed. If "normal", the items are displayed top-to-
bottom in the same order as the input data. If
"reversed", the items are displayed in the opposite
order as "normal". If "grouped", the items are
displayed in groups (when a trace `legendgroup` is
provided). if "grouped+reversed", the items are
displayed in the opposite order as "grouped".
uirevision
Controls persistence of legend-driven changes in trace
and pie label visibility. Defaults to
`layout.uirevision`.
valign
Sets the vertical alignment of the symbols with respect
to their associated text.
visible
Determines whether or not this legend is visible.
x
Sets the x position with respect to `xref` (in
normalized coordinates) of the legend. When `xref` is
"paper", defaults to 1.02 for vertical legends and
defaults to 0 for horizontal legends. When `xref` is
"container", defaults to 1 for vertical legends and
defaults to 0 for horizontal legends. Must be between 0
and 1 if `xref` is "container". and between "-2" and 3
if `xref` is "paper".
xanchor
Sets the legend's horizontal position anchor. This
anchor binds the `x` position to the "left", "center"
or "right" of the legend. Value "auto" anchors legends
to the right for `x` values greater than or equal to
2/3, anchors legends to the left for `x` values less
than or equal to 1/3 and anchors legends with respect
to their center otherwise.
xref
Sets the container `x` refers to. "container" spans the
entire `width` of the plot. "paper" refers to the width
of the plotting area only.
y
Sets the y position with respect to `yref` (in
normalized coordinates) of the legend. When `yref` is
"paper", defaults to 1 for vertical legends, defaults
to "-0.1" for horizontal legends on graphs w/o range
sliders and defaults to 1.1 for horizontal legends on
graph with one or multiple range sliders. When `yref`
is "container", defaults to 1. Must be between 0 and 1
if `yref` is "container" and between "-2" and 3 if
`yref` is "paper".
yanchor
Sets the legend's vertical position anchor This anchor
binds the `y` position to the "top", "middle" or
"bottom" of the legend. Value "auto" anchors legends at
their bottom for `y` values less than or equal to 1/3,
anchors legends to at their top for `y` values greater
than or equal to 2/3 and anchors legends with respect
to their middle otherwise.
yref
Sets the container `y` refers to. "container" spans the
entire `height` of the plot. "paper" refers to the
height of the plotting area only.
Returns
-------
Legend
"""
| /usr/src/app/target_test_cases/failed_tests__legend.Legend.__init__.txt | def __init__(
self,
arg=None,
bgcolor=None,
bordercolor=None,
borderwidth=None,
entrywidth=None,
entrywidthmode=None,
font=None,
groupclick=None,
grouptitlefont=None,
indentation=None,
itemclick=None,
itemdoubleclick=None,
itemsizing=None,
itemwidth=None,
orientation=None,
title=None,
tracegroupgap=None,
traceorder=None,
uirevision=None,
valign=None,
visible=None,
x=None,
xanchor=None,
xref=None,
y=None,
yanchor=None,
yref=None,
**kwargs,
):
"""
Construct a new Legend object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.layout.Legend`
bgcolor
Sets the legend background color. Defaults to
`layout.paper_bgcolor`.
bordercolor
Sets the color of the border enclosing the legend.
borderwidth
Sets the width (in px) of the border enclosing the
legend.
entrywidth
Sets the width (in px or fraction) of the legend. Use 0
to size the entry based on the text width, when
`entrywidthmode` is set to "pixels".
entrywidthmode
Determines what entrywidth means.
font
Sets the font used to text the legend items.
groupclick
Determines the behavior on legend group item click.
"toggleitem" toggles the visibility of the individual
item clicked on the graph. "togglegroup" toggles the
visibility of all items in the same legendgroup as the
item clicked on the graph.
grouptitlefont
Sets the font for group titles in legend. Defaults to
`legend.font` with its size increased about 10%.
indentation
Sets the indentation (in px) of the legend entries.
itemclick
Determines the behavior on legend item click. "toggle"
toggles the visibility of the item clicked on the
graph. "toggleothers" makes the clicked item the sole
visible item on the graph. False disables legend item
click interactions.
itemdoubleclick
Determines the behavior on legend item double-click.
"toggle" toggles the visibility of the item clicked on
the graph. "toggleothers" makes the clicked item the
sole visible item on the graph. False disables legend
item double-click interactions.
itemsizing
Determines if the legend items symbols scale with their
corresponding "trace" attributes or remain "constant"
independent of the symbol size on the graph.
itemwidth
Sets the width (in px) of the legend item symbols (the
part other than the title.text).
orientation
Sets the orientation of the legend.
title
:class:`plotly.graph_objects.layout.legend.Title`
instance or dict with compatible properties
tracegroupgap
Sets the amount of vertical space (in px) between
legend groups.
traceorder
Determines the order at which the legend items are
displayed. If "normal", the items are displayed top-to-
bottom in the same order as the input data. If
"reversed", the items are displayed in the opposite
order as "normal". If "grouped", the items are
displayed in groups (when a trace `legendgroup` is
provided). if "grouped+reversed", the items are
displayed in the opposite order as "grouped".
uirevision
Controls persistence of legend-driven changes in trace
and pie label visibility. Defaults to
`layout.uirevision`.
valign
Sets the vertical alignment of the symbols with respect
to their associated text.
visible
Determines whether or not this legend is visible.
x
Sets the x position with respect to `xref` (in
normalized coordinates) of the legend. When `xref` is
"paper", defaults to 1.02 for vertical legends and
defaults to 0 for horizontal legends. When `xref` is
"container", defaults to 1 for vertical legends and
defaults to 0 for horizontal legends. Must be between 0
and 1 if `xref` is "container". and between "-2" and 3
if `xref` is "paper".
xanchor
Sets the legend's horizontal position anchor. This
anchor binds the `x` position to the "left", "center"
or "right" of the legend. Value "auto" anchors legends
to the right for `x` values greater than or equal to
2/3, anchors legends to the left for `x` values less
than or equal to 1/3 and anchors legends with respect
to their center otherwise.
xref
Sets the container `x` refers to. "container" spans the
entire `width` of the plot. "paper" refers to the width
of the plotting area only.
y
Sets the y position with respect to `yref` (in
normalized coordinates) of the legend. When `yref` is
"paper", defaults to 1 for vertical legends, defaults
to "-0.1" for horizontal legends on graphs w/o range
sliders and defaults to 1.1 for horizontal legends on
graph with one or multiple range sliders. When `yref`
is "container", defaults to 1. Must be between 0 and 1
if `yref` is "container" and between "-2" and 3 if
`yref` is "paper".
yanchor
Sets the legend's vertical position anchor This anchor
binds the `y` position to the "top", "middle" or
"bottom" of the legend. Value "auto" anchors legends at
their bottom for `y` values less than or equal to 1/3,
anchors legends to at their top for `y` values greater
than or equal to 2/3 and anchors legends with respect
to their middle otherwise.
yref
Sets the container `y` refers to. "container" spans the
entire `height` of the plot. "paper" refers to the
height of the plotting area only.
Returns
-------
Legend
"""
super(Legend, self).__init__("legend")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.layout.Legend
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.Legend`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("bgcolor", None)
_v = bgcolor if bgcolor is not None else _v
if _v is not None:
self["bgcolor"] = _v
_v = arg.pop("bordercolor", None)
_v = bordercolor if bordercolor is not None else _v
if _v is not None:
self["bordercolor"] = _v
_v = arg.pop("borderwidth", None)
_v = borderwidth if borderwidth is not None else _v
if _v is not None:
self["borderwidth"] = _v
_v = arg.pop("entrywidth", None)
_v = entrywidth if entrywidth is not None else _v
if _v is not None:
self["entrywidth"] = _v
_v = arg.pop("entrywidthmode", None)
_v = entrywidthmode if entrywidthmode is not None else _v
if _v is not None:
self["entrywidthmode"] = _v
_v = arg.pop("font", None)
_v = font if font is not None else _v
if _v is not None:
self["font"] = _v
_v = arg.pop("groupclick", None)
_v = groupclick if groupclick is not None else _v
if _v is not None:
self["groupclick"] = _v
_v = arg.pop("grouptitlefont", None)
_v = grouptitlefont if grouptitlefont is not None else _v
if _v is not None:
self["grouptitlefont"] = _v
_v = arg.pop("indentation", None)
_v = indentation if indentation is not None else _v
if _v is not None:
self["indentation"] = _v
_v = arg.pop("itemclick", None)
_v = itemclick if itemclick is not None else _v
if _v is not None:
self["itemclick"] = _v
_v = arg.pop("itemdoubleclick", None)
_v = itemdoubleclick if itemdoubleclick is not None else _v
if _v is not None:
self["itemdoubleclick"] = _v
_v = arg.pop("itemsizing", None)
_v = itemsizing if itemsizing is not None else _v
if _v is not None:
self["itemsizing"] = _v
_v = arg.pop("itemwidth", None)
_v = itemwidth if itemwidth is not None else _v
if _v is not None:
self["itemwidth"] = _v
_v = arg.pop("orientation", None)
_v = orientation if orientation is not None else _v
if _v is not None:
self["orientation"] = _v
_v = arg.pop("title", None)
_v = title if title is not None else _v
if _v is not None:
self["title"] = _v
_v = arg.pop("tracegroupgap", None)
_v = tracegroupgap if tracegroupgap is not None else _v
if _v is not None:
self["tracegroupgap"] = _v
_v = arg.pop("traceorder", None)
_v = traceorder if traceorder is not None else _v
if _v is not None:
self["traceorder"] = _v
_v = arg.pop("uirevision", None)
_v = uirevision if uirevision is not None else _v
if _v is not None:
self["uirevision"] = _v
_v = arg.pop("valign", None)
_v = valign if valign is not None else _v
if _v is not None:
self["valign"] = _v
_v = arg.pop("visible", None)
_v = visible if visible is not None else _v
if _v is not None:
self["visible"] = _v
_v = arg.pop("x", None)
_v = x if x is not None else _v
if _v is not None:
self["x"] = _v
_v = arg.pop("xanchor", None)
_v = xanchor if xanchor is not None else _v
if _v is not None:
self["xanchor"] = _v
_v = arg.pop("xref", None)
_v = xref if xref is not None else _v
if _v is not None:
self["xref"] = _v
_v = arg.pop("y", None)
_v = y if y is not None else _v
if _v is not None:
self["y"] = _v
_v = arg.pop("yanchor", None)
_v = yanchor if yanchor is not None else _v
if _v is not None:
self["yanchor"] = _v
_v = arg.pop("yref", None)
_v = yref if yref is not None else _v
if _v is not None:
self["yref"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| _legend.Legend.__init__ |
plotly.py | 30 | packages/python/plotly/plotly/graph_objs/scatter/_marker.py | def colorbar(self):
"""
The 'colorbar' property is an instance of ColorBar
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter.marker.ColorBar`
- A dict of string/value properties that will be passed
to the ColorBar constructor
Supported dict properties:
bgcolor
Sets the color of padded area.
bordercolor
Sets the axis line color.
borderwidth
Sets the width (in px) or the border enclosing
this color bar.
dtick
Sets the step in-between ticks on this axis.
Use with `tick0`. Must be a positive number, or
special strings available to "log" and "date"
axes. If the axis `type` is "log", then ticks
are set every 10^(n*dtick) where n is the tick
number. For example, to set a tick mark at 1,
10, 100, 1000, ... set dtick to 1. To set tick
marks at 1, 100, 10000, ... set dtick to 2. To
set tick marks at 1, 5, 25, 125, 625, 3125, ...
set dtick to log_10(5), or 0.69897000433. "log"
has several special values; "L<f>", where `f`
is a positive number, gives ticks linearly
spaced in value (but not position). For example
`tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10
plus small digits between, use "D1" (all
digits) or "D2" (only 2 and 5). `tick0` is
ignored for "D1" and "D2". If the axis `type`
is "date", then you must convert the time to
milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to
86400000.0. "date" also has special values
"M<n>" gives ticks spaced by a number of
months. `n` must be a positive integer. To set
ticks on the 15th of every third month, set
`tick0` to "2000-01-15" and `dtick` to "M3". To
set ticks every 4 years, set `dtick` to "M48"
exponentformat
Determines a formatting rule for the tick
exponents. For example, consider the number
1,000,000,000. If "none", it appears as
1,000,000,000. If "e", 1e+9. If "E", 1E+9. If
"power", 1x10^9 (with 9 in a super script). If
"SI", 1G. If "B", 1B.
labelalias
Replacement text for specific tick or hover
labels. For example using {US: 'USA', CA:
'Canada'} changes US to USA and CA to Canada.
The labels we would have shown must match the
keys exactly, after adding any tickprefix or
ticksuffix. For negative numbers the minus sign
symbol used (U+2212) is wider than the regular
ascii dash. That means you need to use −1
instead of -1. labelalias can be used with any
axis type, and both keys (if needed) and values
(if desired) can include html-like tags or
MathJax.
len
Sets the length of the color bar This measure
excludes the padding of both ends. That is, the
color bar length is this length minus the
padding on both ends.
lenmode
Determines whether this color bar's length
(i.e. the measure in the color variation
direction) is set in units of plot "fraction"
or in *pixels. Use `len` to set the value.
minexponent
Hide SI prefix for 10^n if |n| is below this
number. This only has an effect when
`tickformat` is "SI" or "B".
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks
will be chosen automatically to be less than or
equal to `nticks`. Has an effect only if
`tickmode` is set to "auto".
orientation
Sets the orientation of the colorbar.
outlinecolor
Sets the axis line color.
outlinewidth
Sets the width (in px) of the axis line.
separatethousands
If "true", even 4-digit integers are separated
showexponent
If "all", all exponents are shown besides their
significands. If "first", only the exponent of
the first tick is shown. If "last", only the
exponent of the last tick is shown. If "none",
no exponents appear.
showticklabels
Determines whether or not the tick labels are
drawn.
showtickprefix
If "all", all tick labels are displayed with a
prefix. If "first", only the first tick is
displayed with a prefix. If "last", only the
last tick is displayed with a suffix. If
"none", tick prefixes are hidden.
showticksuffix
Same as `showtickprefix` but for tick suffixes.
thickness
Sets the thickness of the color bar This
measure excludes the size of the padding, ticks
and labels.
thicknessmode
Determines whether this color bar's thickness
(i.e. the measure in the constant color
direction) is set in units of plot "fraction"
or in "pixels". Use `thickness` to set the
value.
tick0
Sets the placement of the first tick on this
axis. Use with `dtick`. If the axis `type` is
"log", then you must take the log of your
starting tick (e.g. to set the starting tick to
100, set the `tick0` to 2) except when
`dtick`=*L<f>* (see `dtick` for more info). If
the axis `type` is "date", it should be a date
string, like date data. If the axis `type` is
"category", it should be a number, using the
scale where each category is assigned a serial
number from zero in the order it appears.
tickangle
Sets the angle of the tick labels with respect
to the horizontal. For example, a `tickangle`
of -90 draws the tick labels vertically.
tickcolor
Sets the tick color.
tickfont
Sets the color bar's tick label font
tickformat
Sets the tick label formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see: h
ttps://github.com/d3/d3-format/tree/v1.4.5#d3-
format. And for dates see:
https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two
items to d3's date formatter: "%h" for half of
the year as a decimal number as well as "%{n}f"
for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with
tickformat "%H~%M~%S.%2f" would display
"09~15~23.46"
tickformatstops
A tuple of :class:`plotly.graph_objects.scatter
.marker.colorbar.Tickformatstop` instances or
dicts with compatible properties
tickformatstopdefaults
When used in a template (as layout.template.dat
a.scatter.marker.colorbar.tickformatstopdefault
s), sets the default property values to use for
elements of
scatter.marker.colorbar.tickformatstops
ticklabeloverflow
Determines how we handle tick labels that would
overflow either the graph div or the domain of
the axis. The default value for inside tick
labels is *hide past domain*. In other cases
the default is *hide past div*.
ticklabelposition
Determines where tick labels are drawn relative
to the ticks. Left and right options are used
when `orientation` is "h", top and bottom when
`orientation` is "v".
ticklabelstep
Sets the spacing between tick labels as
compared to the spacing between ticks. A value
of 1 (default) means each tick gets a label. A
value of 2 means shows every 2nd label. A
larger value n means only every nth tick is
labeled. `tick0` determines which labels are
shown. Not implemented for axes with `type`
"log" or "multicategory", or when `tickmode` is
"array".
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto",
the number of ticks is set via `nticks`. If
"linear", the placement of the ticks is
determined by a starting position `tick0` and a
tick step `dtick` ("linear" is the default
value if `tick0` and `dtick` are provided). If
"array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`.
("array" is the default value if `tickvals` is
provided).
tickprefix
Sets a tick label prefix.
ticks
Determines whether ticks are drawn or not. If
"", this axis' ticks are not drawn. If
"outside" ("inside"), this axis' are drawn
outside (inside) the axis lines.
ticksuffix
Sets a tick label suffix.
ticktext
Sets the text displayed at the ticks position
via `tickvals`. Only has an effect if
`tickmode` is set to "array". Used with
`tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud
for `ticktext`.
tickvals
Sets the values at which ticks on this axis
appear. Only has an effect if `tickmode` is set
to "array". Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud
for `tickvals`.
tickwidth
Sets the tick width (in px).
title
:class:`plotly.graph_objects.scatter.marker.col
orbar.Title` instance or dict with compatible
properties
titlefont
Deprecated: Please use
scatter.marker.colorbar.title.font instead.
Sets this color bar's title font. Note that the
title's font used to be set by the now
deprecated `titlefont` attribute.
titleside
Deprecated: Please use
scatter.marker.colorbar.title.side instead.
Determines the location of color bar's title
with respect to the color bar. Defaults to
"top" when `orientation` if "v" and defaults
to "right" when `orientation` if "h". Note that
the title's location used to be set by the now
deprecated `titleside` attribute.
x
Sets the x position with respect to `xref` of
the color bar (in plot fraction). When `xref`
is "paper", defaults to 1.02 when `orientation`
is "v" and 0.5 when `orientation` is "h". When
`xref` is "container", defaults to 1 when
`orientation` is "v" and 0.5 when `orientation`
is "h". Must be between 0 and 1 if `xref` is
"container" and between "-2" and 3 if `xref` is
"paper".
xanchor
Sets this color bar's horizontal position
anchor. This anchor binds the `x` position to
the "left", "center" or "right" of the color
bar. Defaults to "left" when `orientation` is
"v" and "center" when `orientation` is "h".
xpad
Sets the amount of padding (in px) along the x
direction.
xref
Sets the container `x` refers to. "container"
spans the entire `width` of the plot. "paper"
refers to the width of the plotting area only.
y
Sets the y position with respect to `yref` of
the color bar (in plot fraction). When `yref`
is "paper", defaults to 0.5 when `orientation`
is "v" and 1.02 when `orientation` is "h". When
`yref` is "container", defaults to 0.5 when
`orientation` is "v" and 1 when `orientation`
is "h". Must be between 0 and 1 if `yref` is
"container" and between "-2" and 3 if `yref` is
"paper".
yanchor
Sets this color bar's vertical position anchor
This anchor binds the `y` position to the
"top", "middle" or "bottom" of the color bar.
Defaults to "middle" when `orientation` is "v"
and "bottom" when `orientation` is "h".
ypad
Sets the amount of padding (in px) along the y
direction.
yref
Sets the container `y` refers to. "container"
spans the entire `height` of the plot. "paper"
refers to the height of the plotting area only.
Returns
-------
plotly.graph_objs.scatter.marker.ColorBar
"""
| /usr/src/app/target_test_cases/failed_tests__marker.colorbar.txt | def colorbar(self):
"""
The 'colorbar' property is an instance of ColorBar
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter.marker.ColorBar`
- A dict of string/value properties that will be passed
to the ColorBar constructor
Supported dict properties:
bgcolor
Sets the color of padded area.
bordercolor
Sets the axis line color.
borderwidth
Sets the width (in px) or the border enclosing
this color bar.
dtick
Sets the step in-between ticks on this axis.
Use with `tick0`. Must be a positive number, or
special strings available to "log" and "date"
axes. If the axis `type` is "log", then ticks
are set every 10^(n*dtick) where n is the tick
number. For example, to set a tick mark at 1,
10, 100, 1000, ... set dtick to 1. To set tick
marks at 1, 100, 10000, ... set dtick to 2. To
set tick marks at 1, 5, 25, 125, 625, 3125, ...
set dtick to log_10(5), or 0.69897000433. "log"
has several special values; "L<f>", where `f`
is a positive number, gives ticks linearly
spaced in value (but not position). For example
`tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10
plus small digits between, use "D1" (all
digits) or "D2" (only 2 and 5). `tick0` is
ignored for "D1" and "D2". If the axis `type`
is "date", then you must convert the time to
milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to
86400000.0. "date" also has special values
"M<n>" gives ticks spaced by a number of
months. `n` must be a positive integer. To set
ticks on the 15th of every third month, set
`tick0` to "2000-01-15" and `dtick` to "M3". To
set ticks every 4 years, set `dtick` to "M48"
exponentformat
Determines a formatting rule for the tick
exponents. For example, consider the number
1,000,000,000. If "none", it appears as
1,000,000,000. If "e", 1e+9. If "E", 1E+9. If
"power", 1x10^9 (with 9 in a super script). If
"SI", 1G. If "B", 1B.
labelalias
Replacement text for specific tick or hover
labels. For example using {US: 'USA', CA:
'Canada'} changes US to USA and CA to Canada.
The labels we would have shown must match the
keys exactly, after adding any tickprefix or
ticksuffix. For negative numbers the minus sign
symbol used (U+2212) is wider than the regular
ascii dash. That means you need to use −1
instead of -1. labelalias can be used with any
axis type, and both keys (if needed) and values
(if desired) can include html-like tags or
MathJax.
len
Sets the length of the color bar This measure
excludes the padding of both ends. That is, the
color bar length is this length minus the
padding on both ends.
lenmode
Determines whether this color bar's length
(i.e. the measure in the color variation
direction) is set in units of plot "fraction"
or in *pixels. Use `len` to set the value.
minexponent
Hide SI prefix for 10^n if |n| is below this
number. This only has an effect when
`tickformat` is "SI" or "B".
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks
will be chosen automatically to be less than or
equal to `nticks`. Has an effect only if
`tickmode` is set to "auto".
orientation
Sets the orientation of the colorbar.
outlinecolor
Sets the axis line color.
outlinewidth
Sets the width (in px) of the axis line.
separatethousands
If "true", even 4-digit integers are separated
showexponent
If "all", all exponents are shown besides their
significands. If "first", only the exponent of
the first tick is shown. If "last", only the
exponent of the last tick is shown. If "none",
no exponents appear.
showticklabels
Determines whether or not the tick labels are
drawn.
showtickprefix
If "all", all tick labels are displayed with a
prefix. If "first", only the first tick is
displayed with a prefix. If "last", only the
last tick is displayed with a suffix. If
"none", tick prefixes are hidden.
showticksuffix
Same as `showtickprefix` but for tick suffixes.
thickness
Sets the thickness of the color bar This
measure excludes the size of the padding, ticks
and labels.
thicknessmode
Determines whether this color bar's thickness
(i.e. the measure in the constant color
direction) is set in units of plot "fraction"
or in "pixels". Use `thickness` to set the
value.
tick0
Sets the placement of the first tick on this
axis. Use with `dtick`. If the axis `type` is
"log", then you must take the log of your
starting tick (e.g. to set the starting tick to
100, set the `tick0` to 2) except when
`dtick`=*L<f>* (see `dtick` for more info). If
the axis `type` is "date", it should be a date
string, like date data. If the axis `type` is
"category", it should be a number, using the
scale where each category is assigned a serial
number from zero in the order it appears.
tickangle
Sets the angle of the tick labels with respect
to the horizontal. For example, a `tickangle`
of -90 draws the tick labels vertically.
tickcolor
Sets the tick color.
tickfont
Sets the color bar's tick label font
tickformat
Sets the tick label formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see: h
ttps://github.com/d3/d3-format/tree/v1.4.5#d3-
format. And for dates see:
https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two
items to d3's date formatter: "%h" for half of
the year as a decimal number as well as "%{n}f"
for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with
tickformat "%H~%M~%S.%2f" would display
"09~15~23.46"
tickformatstops
A tuple of :class:`plotly.graph_objects.scatter
.marker.colorbar.Tickformatstop` instances or
dicts with compatible properties
tickformatstopdefaults
When used in a template (as layout.template.dat
a.scatter.marker.colorbar.tickformatstopdefault
s), sets the default property values to use for
elements of
scatter.marker.colorbar.tickformatstops
ticklabeloverflow
Determines how we handle tick labels that would
overflow either the graph div or the domain of
the axis. The default value for inside tick
labels is *hide past domain*. In other cases
the default is *hide past div*.
ticklabelposition
Determines where tick labels are drawn relative
to the ticks. Left and right options are used
when `orientation` is "h", top and bottom when
`orientation` is "v".
ticklabelstep
Sets the spacing between tick labels as
compared to the spacing between ticks. A value
of 1 (default) means each tick gets a label. A
value of 2 means shows every 2nd label. A
larger value n means only every nth tick is
labeled. `tick0` determines which labels are
shown. Not implemented for axes with `type`
"log" or "multicategory", or when `tickmode` is
"array".
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto",
the number of ticks is set via `nticks`. If
"linear", the placement of the ticks is
determined by a starting position `tick0` and a
tick step `dtick` ("linear" is the default
value if `tick0` and `dtick` are provided). If
"array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`.
("array" is the default value if `tickvals` is
provided).
tickprefix
Sets a tick label prefix.
ticks
Determines whether ticks are drawn or not. If
"", this axis' ticks are not drawn. If
"outside" ("inside"), this axis' are drawn
outside (inside) the axis lines.
ticksuffix
Sets a tick label suffix.
ticktext
Sets the text displayed at the ticks position
via `tickvals`. Only has an effect if
`tickmode` is set to "array". Used with
`tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud
for `ticktext`.
tickvals
Sets the values at which ticks on this axis
appear. Only has an effect if `tickmode` is set
to "array". Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud
for `tickvals`.
tickwidth
Sets the tick width (in px).
title
:class:`plotly.graph_objects.scatter.marker.col
orbar.Title` instance or dict with compatible
properties
titlefont
Deprecated: Please use
scatter.marker.colorbar.title.font instead.
Sets this color bar's title font. Note that the
title's font used to be set by the now
deprecated `titlefont` attribute.
titleside
Deprecated: Please use
scatter.marker.colorbar.title.side instead.
Determines the location of color bar's title
with respect to the color bar. Defaults to
"top" when `orientation` if "v" and defaults
to "right" when `orientation` if "h". Note that
the title's location used to be set by the now
deprecated `titleside` attribute.
x
Sets the x position with respect to `xref` of
the color bar (in plot fraction). When `xref`
is "paper", defaults to 1.02 when `orientation`
is "v" and 0.5 when `orientation` is "h". When
`xref` is "container", defaults to 1 when
`orientation` is "v" and 0.5 when `orientation`
is "h". Must be between 0 and 1 if `xref` is
"container" and between "-2" and 3 if `xref` is
"paper".
xanchor
Sets this color bar's horizontal position
anchor. This anchor binds the `x` position to
the "left", "center" or "right" of the color
bar. Defaults to "left" when `orientation` is
"v" and "center" when `orientation` is "h".
xpad
Sets the amount of padding (in px) along the x
direction.
xref
Sets the container `x` refers to. "container"
spans the entire `width` of the plot. "paper"
refers to the width of the plotting area only.
y
Sets the y position with respect to `yref` of
the color bar (in plot fraction). When `yref`
is "paper", defaults to 0.5 when `orientation`
is "v" and 1.02 when `orientation` is "h". When
`yref` is "container", defaults to 0.5 when
`orientation` is "v" and 1 when `orientation`
is "h". Must be between 0 and 1 if `yref` is
"container" and between "-2" and 3 if `yref` is
"paper".
yanchor
Sets this color bar's vertical position anchor
This anchor binds the `y` position to the
"top", "middle" or "bottom" of the color bar.
Defaults to "middle" when `orientation` is "v"
and "bottom" when `orientation` is "h".
ypad
Sets the amount of padding (in px) along the y
direction.
yref
Sets the container `y` refers to. "container"
spans the entire `height` of the plot. "paper"
refers to the height of the plotting area only.
Returns
-------
plotly.graph_objs.scatter.marker.ColorBar
"""
return self["colorbar"]
| _marker.colorbar |
plotly.py | 31 | packages/python/plotly/plotly/graph_objs/layout/_modebar.py | def __init__(
self,
arg=None,
activecolor=None,
add=None,
addsrc=None,
bgcolor=None,
color=None,
orientation=None,
remove=None,
removesrc=None,
uirevision=None,
**kwargs,
):
"""
Construct a new Modebar object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.layout.Modebar`
activecolor
Sets the color of the active or hovered on icons in the
modebar.
add
Determines which predefined modebar buttons to add.
Please note that these buttons will only be shown if
they are compatible with all trace types used in a
graph. Similar to `config.modeBarButtonsToAdd` option.
This may include "v1hovermode", "hoverclosest",
"hovercompare", "togglehover", "togglespikelines",
"drawline", "drawopenpath", "drawclosedpath",
"drawcircle", "drawrect", "eraseshape".
addsrc
Sets the source reference on Chart Studio Cloud for
`add`.
bgcolor
Sets the background color of the modebar.
color
Sets the color of the icons in the modebar.
orientation
Sets the orientation of the modebar.
remove
Determines which predefined modebar buttons to remove.
Similar to `config.modeBarButtonsToRemove` option. This
may include "autoScale2d", "autoscale",
"editInChartStudio", "editinchartstudio",
"hoverCompareCartesian", "hovercompare", "lasso",
"lasso2d", "orbitRotation", "orbitrotation", "pan",
"pan2d", "pan3d", "reset", "resetCameraDefault3d",
"resetCameraLastSave3d", "resetGeo",
"resetSankeyGroup", "resetScale2d", "resetViewMap",
"resetViewMapbox", "resetViews", "resetcameradefault",
"resetcameralastsave", "resetsankeygroup",
"resetscale", "resetview", "resetviews", "select",
"select2d", "sendDataToCloud", "senddatatocloud",
"tableRotation", "tablerotation", "toImage",
"toggleHover", "toggleSpikelines", "togglehover",
"togglespikelines", "toimage", "zoom", "zoom2d",
"zoom3d", "zoomIn2d", "zoomInGeo", "zoomInMap",
"zoomInMapbox", "zoomOut2d", "zoomOutGeo",
"zoomOutMap", "zoomOutMapbox", "zoomin", "zoomout".
removesrc
Sets the source reference on Chart Studio Cloud for
`remove`.
uirevision
Controls persistence of user-driven changes related to
the modebar, including `hovermode`, `dragmode`, and
`showspikes` at both the root level and inside
subplots. Defaults to `layout.uirevision`.
Returns
-------
Modebar
"""
| /usr/src/app/target_test_cases/failed_tests__modebar.Modebar.__init__.txt | def __init__(
self,
arg=None,
activecolor=None,
add=None,
addsrc=None,
bgcolor=None,
color=None,
orientation=None,
remove=None,
removesrc=None,
uirevision=None,
**kwargs,
):
"""
Construct a new Modebar object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.layout.Modebar`
activecolor
Sets the color of the active or hovered on icons in the
modebar.
add
Determines which predefined modebar buttons to add.
Please note that these buttons will only be shown if
they are compatible with all trace types used in a
graph. Similar to `config.modeBarButtonsToAdd` option.
This may include "v1hovermode", "hoverclosest",
"hovercompare", "togglehover", "togglespikelines",
"drawline", "drawopenpath", "drawclosedpath",
"drawcircle", "drawrect", "eraseshape".
addsrc
Sets the source reference on Chart Studio Cloud for
`add`.
bgcolor
Sets the background color of the modebar.
color
Sets the color of the icons in the modebar.
orientation
Sets the orientation of the modebar.
remove
Determines which predefined modebar buttons to remove.
Similar to `config.modeBarButtonsToRemove` option. This
may include "autoScale2d", "autoscale",
"editInChartStudio", "editinchartstudio",
"hoverCompareCartesian", "hovercompare", "lasso",
"lasso2d", "orbitRotation", "orbitrotation", "pan",
"pan2d", "pan3d", "reset", "resetCameraDefault3d",
"resetCameraLastSave3d", "resetGeo",
"resetSankeyGroup", "resetScale2d", "resetViewMap",
"resetViewMapbox", "resetViews", "resetcameradefault",
"resetcameralastsave", "resetsankeygroup",
"resetscale", "resetview", "resetviews", "select",
"select2d", "sendDataToCloud", "senddatatocloud",
"tableRotation", "tablerotation", "toImage",
"toggleHover", "toggleSpikelines", "togglehover",
"togglespikelines", "toimage", "zoom", "zoom2d",
"zoom3d", "zoomIn2d", "zoomInGeo", "zoomInMap",
"zoomInMapbox", "zoomOut2d", "zoomOutGeo",
"zoomOutMap", "zoomOutMapbox", "zoomin", "zoomout".
removesrc
Sets the source reference on Chart Studio Cloud for
`remove`.
uirevision
Controls persistence of user-driven changes related to
the modebar, including `hovermode`, `dragmode`, and
`showspikes` at both the root level and inside
subplots. Defaults to `layout.uirevision`.
Returns
-------
Modebar
"""
super(Modebar, self).__init__("modebar")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.layout.Modebar
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.Modebar`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("activecolor", None)
_v = activecolor if activecolor is not None else _v
if _v is not None:
self["activecolor"] = _v
_v = arg.pop("add", None)
_v = add if add is not None else _v
if _v is not None:
self["add"] = _v
_v = arg.pop("addsrc", None)
_v = addsrc if addsrc is not None else _v
if _v is not None:
self["addsrc"] = _v
_v = arg.pop("bgcolor", None)
_v = bgcolor if bgcolor is not None else _v
if _v is not None:
self["bgcolor"] = _v
_v = arg.pop("color", None)
_v = color if color is not None else _v
if _v is not None:
self["color"] = _v
_v = arg.pop("orientation", None)
_v = orientation if orientation is not None else _v
if _v is not None:
self["orientation"] = _v
_v = arg.pop("remove", None)
_v = remove if remove is not None else _v
if _v is not None:
self["remove"] = _v
_v = arg.pop("removesrc", None)
_v = removesrc if removesrc is not None else _v
if _v is not None:
self["removesrc"] = _v
_v = arg.pop("uirevision", None)
_v = uirevision if uirevision is not None else _v
if _v is not None:
self["uirevision"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| _modebar.Modebar.__init__ |
plotly.py | 32 | packages/python/plotly/plotly/graph_objs/layout/_newshape.py | def __init__(
self,
arg=None,
drawdirection=None,
fillcolor=None,
fillrule=None,
label=None,
layer=None,
legend=None,
legendgroup=None,
legendgrouptitle=None,
legendrank=None,
legendwidth=None,
line=None,
name=None,
opacity=None,
showlegend=None,
visible=None,
**kwargs,
):
"""
Construct a new Newshape object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.layout.Newshape`
drawdirection
When `dragmode` is set to "drawrect", "drawline" or
"drawcircle" this limits the drag to be horizontal,
vertical or diagonal. Using "diagonal" there is no
limit e.g. in drawing lines in any direction. "ortho"
limits the draw to be either horizontal or vertical.
"horizontal" allows horizontal extend. "vertical"
allows vertical extend.
fillcolor
Sets the color filling new shapes' interior. Please
note that if using a fillcolor with alpha greater than
half, drag inside the active shape starts moving the
shape underneath, otherwise a new shape could be
started over.
fillrule
Determines the path's interior. For more info please
visit https://developer.mozilla.org/en-
US/docs/Web/SVG/Attribute/fill-rule
label
:class:`plotly.graph_objects.layout.newshape.Label`
instance or dict with compatible properties
layer
Specifies whether new shapes are drawn below gridlines
("below"), between gridlines and traces ("between") or
above traces ("above").
legend
Sets the reference to a legend to show new shape in.
References to these legends are "legend", "legend2",
"legend3", etc. Settings for these legends are set in
the layout, under `layout.legend`, `layout.legend2`,
etc.
legendgroup
Sets the legend group for new shape. Traces and shapes
part of the same legend group hide/show at the same
time when toggling legend items.
legendgrouptitle
:class:`plotly.graph_objects.layout.newshape.Legendgrou
ptitle` instance or dict with compatible properties
legendrank
Sets the legend rank for new shape. Items and groups
with smaller ranks are presented on top/left side while
with "reversed" `legend.traceorder` they are on
bottom/right side. The default legendrank is 1000, so
that you can use ranks less than 1000 to place certain
items before all unranked items, and ranks greater than
1000 to go after all unranked items.
legendwidth
Sets the width (in px or fraction) of the legend for
new shape.
line
:class:`plotly.graph_objects.layout.newshape.Line`
instance or dict with compatible properties
name
Sets new shape name. The name appears as the legend
item.
opacity
Sets the opacity of new shapes.
showlegend
Determines whether or not new shape is shown in the
legend.
visible
Determines whether or not new shape is visible. If
"legendonly", the shape is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
Returns
-------
Newshape
"""
| /usr/src/app/target_test_cases/failed_tests__newshape.Newshape.__init__.txt | def __init__(
self,
arg=None,
drawdirection=None,
fillcolor=None,
fillrule=None,
label=None,
layer=None,
legend=None,
legendgroup=None,
legendgrouptitle=None,
legendrank=None,
legendwidth=None,
line=None,
name=None,
opacity=None,
showlegend=None,
visible=None,
**kwargs,
):
"""
Construct a new Newshape object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.layout.Newshape`
drawdirection
When `dragmode` is set to "drawrect", "drawline" or
"drawcircle" this limits the drag to be horizontal,
vertical or diagonal. Using "diagonal" there is no
limit e.g. in drawing lines in any direction. "ortho"
limits the draw to be either horizontal or vertical.
"horizontal" allows horizontal extend. "vertical"
allows vertical extend.
fillcolor
Sets the color filling new shapes' interior. Please
note that if using a fillcolor with alpha greater than
half, drag inside the active shape starts moving the
shape underneath, otherwise a new shape could be
started over.
fillrule
Determines the path's interior. For more info please
visit https://developer.mozilla.org/en-
US/docs/Web/SVG/Attribute/fill-rule
label
:class:`plotly.graph_objects.layout.newshape.Label`
instance or dict with compatible properties
layer
Specifies whether new shapes are drawn below gridlines
("below"), between gridlines and traces ("between") or
above traces ("above").
legend
Sets the reference to a legend to show new shape in.
References to these legends are "legend", "legend2",
"legend3", etc. Settings for these legends are set in
the layout, under `layout.legend`, `layout.legend2`,
etc.
legendgroup
Sets the legend group for new shape. Traces and shapes
part of the same legend group hide/show at the same
time when toggling legend items.
legendgrouptitle
:class:`plotly.graph_objects.layout.newshape.Legendgrou
ptitle` instance or dict with compatible properties
legendrank
Sets the legend rank for new shape. Items and groups
with smaller ranks are presented on top/left side while
with "reversed" `legend.traceorder` they are on
bottom/right side. The default legendrank is 1000, so
that you can use ranks less than 1000 to place certain
items before all unranked items, and ranks greater than
1000 to go after all unranked items.
legendwidth
Sets the width (in px or fraction) of the legend for
new shape.
line
:class:`plotly.graph_objects.layout.newshape.Line`
instance or dict with compatible properties
name
Sets new shape name. The name appears as the legend
item.
opacity
Sets the opacity of new shapes.
showlegend
Determines whether or not new shape is shown in the
legend.
visible
Determines whether or not new shape is visible. If
"legendonly", the shape is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
Returns
-------
Newshape
"""
super(Newshape, self).__init__("newshape")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.layout.Newshape
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.Newshape`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("drawdirection", None)
_v = drawdirection if drawdirection is not None else _v
if _v is not None:
self["drawdirection"] = _v
_v = arg.pop("fillcolor", None)
_v = fillcolor if fillcolor is not None else _v
if _v is not None:
self["fillcolor"] = _v
_v = arg.pop("fillrule", None)
_v = fillrule if fillrule is not None else _v
if _v is not None:
self["fillrule"] = _v
_v = arg.pop("label", None)
_v = label if label is not None else _v
if _v is not None:
self["label"] = _v
_v = arg.pop("layer", None)
_v = layer if layer is not None else _v
if _v is not None:
self["layer"] = _v
_v = arg.pop("legend", None)
_v = legend if legend is not None else _v
if _v is not None:
self["legend"] = _v
_v = arg.pop("legendgroup", None)
_v = legendgroup if legendgroup is not None else _v
if _v is not None:
self["legendgroup"] = _v
_v = arg.pop("legendgrouptitle", None)
_v = legendgrouptitle if legendgrouptitle is not None else _v
if _v is not None:
self["legendgrouptitle"] = _v
_v = arg.pop("legendrank", None)
_v = legendrank if legendrank is not None else _v
if _v is not None:
self["legendrank"] = _v
_v = arg.pop("legendwidth", None)
_v = legendwidth if legendwidth is not None else _v
if _v is not None:
self["legendwidth"] = _v
_v = arg.pop("line", None)
_v = line if line is not None else _v
if _v is not None:
self["line"] = _v
_v = arg.pop("name", None)
_v = name if name is not None else _v
if _v is not None:
self["name"] = _v
_v = arg.pop("opacity", None)
_v = opacity if opacity is not None else _v
if _v is not None:
self["opacity"] = _v
_v = arg.pop("showlegend", None)
_v = showlegend if showlegend is not None else _v
if _v is not None:
self["showlegend"] = _v
_v = arg.pop("visible", None)
_v = visible if visible is not None else _v
if _v is not None:
self["visible"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| _newshape.Newshape.__init__ |
plotly.py | 33 | packages/python/plotly/plotly/graph_objs/_parcats.py | def __init__(
self,
arg=None,
arrangement=None,
bundlecolors=None,
counts=None,
countssrc=None,
dimensions=None,
dimensiondefaults=None,
domain=None,
hoverinfo=None,
hoveron=None,
hovertemplate=None,
labelfont=None,
legendgrouptitle=None,
legendwidth=None,
line=None,
meta=None,
metasrc=None,
name=None,
sortpaths=None,
stream=None,
tickfont=None,
uid=None,
uirevision=None,
visible=None,
**kwargs,
):
"""
Construct a new Parcats object
Parallel categories diagram for multidimensional categorical
data.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.Parcats`
arrangement
Sets the drag interaction mode for categories and
dimensions. If `perpendicular`, the categories can only
move along a line perpendicular to the paths. If
`freeform`, the categories can freely move on the
plane. If `fixed`, the categories and dimensions are
stationary.
bundlecolors
Sort paths so that like colors are bundled together
within each category.
counts
The number of observations represented by each state.
Defaults to 1 so that each state represents one
observation
countssrc
Sets the source reference on Chart Studio Cloud for
`counts`.
dimensions
The dimensions (variables) of the parallel categories
diagram.
dimensiondefaults
When used in a template (as
layout.template.data.parcats.dimensiondefaults), sets
the default property values to use for elements of
parcats.dimensions
domain
:class:`plotly.graph_objects.parcats.Domain` instance
or dict with compatible properties
hoverinfo
Determines which trace information appear on hover. If
`none` or `skip` are set, no information is displayed
upon hovering. But, if `none` is set, click and hover
events are still fired.
hoveron
Sets the hover interaction mode for the parcats
diagram. If `category`, hover interaction take place
per category. If `color`, hover interactions take place
per color per category. If `dimension`, hover
interactions take place across all categories per
dimension.
hovertemplate
Template string used for rendering the information that
appear on hover box. Note that this will override
`hoverinfo`. Variables are inserted using %{variable},
for example "y: %{y}" as well as %{xother}, {%_xother},
{%_xother_}, {%xother_}. When showing info for several
points, "xother" will be added to those with different
x positions from the first point. An underscore before
or after "(x|y)other" will add a space on that side,
only when this field is shown. Numbers are formatted
using d3-format's syntax %{variable:d3-format}, for
example "Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. The variables available in
`hovertemplate` are the ones emitted as event data
described at this link
https://plotly.com/javascript/plotlyjs-events/#event-
data. Additionally, every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. This value here applies when hovering
over dimensions. Note that `*categorycount`,
"colorcount" and "bandcolorcount" are only available
when `hoveron` contains the "color" flagFinally, the
template string has access to variables `count`,
`probability`, `category`, `categorycount`,
`colorcount` and `bandcolorcount`. Anything contained
in tag `<extra>` is displayed in the secondary box, for
example "<extra>{fullData.name}</extra>". To hide the
secondary box completely, use an empty tag
`<extra></extra>`.
labelfont
Sets the font for the `dimension` labels.
legendgrouptitle
:class:`plotly.graph_objects.parcats.Legendgrouptitle`
instance or dict with compatible properties
legendwidth
Sets the width (in px or fraction) of the legend for
this trace.
line
:class:`plotly.graph_objects.parcats.Line` instance or
dict with compatible properties
meta
Assigns extra meta information associated with this
trace that can be used in various text attributes.
Attributes such as trace `name`, graph, axis and
colorbar `title.text`, annotation `text`
`rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta`
values in an attribute in the same trace, simply use
`%{meta[i]}` where `i` is the index or key of the
`meta` item in question. To access trace `meta` in
layout attributes, use `%{data[n[.meta[i]}` where `i`
is the index or key of the `meta` and `n` is the trace
index.
metasrc
Sets the source reference on Chart Studio Cloud for
`meta`.
name
Sets the trace name. The trace name appears as the
legend item and on hover.
sortpaths
Sets the path sorting algorithm. If `forward`, sort
paths based on dimension categories from left to right.
If `backward`, sort paths based on dimensions
categories from right to left.
stream
:class:`plotly.graph_objects.parcats.Stream` instance
or dict with compatible properties
tickfont
Sets the font for the `category` labels.
uid
Assign an id to this trace, Use this to provide object
constancy between traces during animations and
transitions.
uirevision
Controls persistence of some user-driven changes to the
trace: `constraintrange` in `parcoords` traces, as well
as some `editable: true` modifications such as `name`
and `colorbar.title`. Defaults to `layout.uirevision`.
Note that other user-driven trace attribute changes are
controlled by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
Returns
-------
Parcats
"""
| /usr/src/app/target_test_cases/failed_tests__parcats.Parcats.__init__.txt | def __init__(
self,
arg=None,
arrangement=None,
bundlecolors=None,
counts=None,
countssrc=None,
dimensions=None,
dimensiondefaults=None,
domain=None,
hoverinfo=None,
hoveron=None,
hovertemplate=None,
labelfont=None,
legendgrouptitle=None,
legendwidth=None,
line=None,
meta=None,
metasrc=None,
name=None,
sortpaths=None,
stream=None,
tickfont=None,
uid=None,
uirevision=None,
visible=None,
**kwargs,
):
"""
Construct a new Parcats object
Parallel categories diagram for multidimensional categorical
data.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.Parcats`
arrangement
Sets the drag interaction mode for categories and
dimensions. If `perpendicular`, the categories can only
move along a line perpendicular to the paths. If
`freeform`, the categories can freely move on the
plane. If `fixed`, the categories and dimensions are
stationary.
bundlecolors
Sort paths so that like colors are bundled together
within each category.
counts
The number of observations represented by each state.
Defaults to 1 so that each state represents one
observation
countssrc
Sets the source reference on Chart Studio Cloud for
`counts`.
dimensions
The dimensions (variables) of the parallel categories
diagram.
dimensiondefaults
When used in a template (as
layout.template.data.parcats.dimensiondefaults), sets
the default property values to use for elements of
parcats.dimensions
domain
:class:`plotly.graph_objects.parcats.Domain` instance
or dict with compatible properties
hoverinfo
Determines which trace information appear on hover. If
`none` or `skip` are set, no information is displayed
upon hovering. But, if `none` is set, click and hover
events are still fired.
hoveron
Sets the hover interaction mode for the parcats
diagram. If `category`, hover interaction take place
per category. If `color`, hover interactions take place
per color per category. If `dimension`, hover
interactions take place across all categories per
dimension.
hovertemplate
Template string used for rendering the information that
appear on hover box. Note that this will override
`hoverinfo`. Variables are inserted using %{variable},
for example "y: %{y}" as well as %{xother}, {%_xother},
{%_xother_}, {%xother_}. When showing info for several
points, "xother" will be added to those with different
x positions from the first point. An underscore before
or after "(x|y)other" will add a space on that side,
only when this field is shown. Numbers are formatted
using d3-format's syntax %{variable:d3-format}, for
example "Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. The variables available in
`hovertemplate` are the ones emitted as event data
described at this link
https://plotly.com/javascript/plotlyjs-events/#event-
data. Additionally, every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. This value here applies when hovering
over dimensions. Note that `*categorycount`,
"colorcount" and "bandcolorcount" are only available
when `hoveron` contains the "color" flagFinally, the
template string has access to variables `count`,
`probability`, `category`, `categorycount`,
`colorcount` and `bandcolorcount`. Anything contained
in tag `<extra>` is displayed in the secondary box, for
example "<extra>{fullData.name}</extra>". To hide the
secondary box completely, use an empty tag
`<extra></extra>`.
labelfont
Sets the font for the `dimension` labels.
legendgrouptitle
:class:`plotly.graph_objects.parcats.Legendgrouptitle`
instance or dict with compatible properties
legendwidth
Sets the width (in px or fraction) of the legend for
this trace.
line
:class:`plotly.graph_objects.parcats.Line` instance or
dict with compatible properties
meta
Assigns extra meta information associated with this
trace that can be used in various text attributes.
Attributes such as trace `name`, graph, axis and
colorbar `title.text`, annotation `text`
`rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta`
values in an attribute in the same trace, simply use
`%{meta[i]}` where `i` is the index or key of the
`meta` item in question. To access trace `meta` in
layout attributes, use `%{data[n[.meta[i]}` where `i`
is the index or key of the `meta` and `n` is the trace
index.
metasrc
Sets the source reference on Chart Studio Cloud for
`meta`.
name
Sets the trace name. The trace name appears as the
legend item and on hover.
sortpaths
Sets the path sorting algorithm. If `forward`, sort
paths based on dimension categories from left to right.
If `backward`, sort paths based on dimensions
categories from right to left.
stream
:class:`plotly.graph_objects.parcats.Stream` instance
or dict with compatible properties
tickfont
Sets the font for the `category` labels.
uid
Assign an id to this trace, Use this to provide object
constancy between traces during animations and
transitions.
uirevision
Controls persistence of some user-driven changes to the
trace: `constraintrange` in `parcoords` traces, as well
as some `editable: true` modifications such as `name`
and `colorbar.title`. Defaults to `layout.uirevision`.
Note that other user-driven trace attribute changes are
controlled by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
Returns
-------
Parcats
"""
super(Parcats, self).__init__("parcats")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.Parcats
constructor must be a dict or
an instance of :class:`plotly.graph_objs.Parcats`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("arrangement", None)
_v = arrangement if arrangement is not None else _v
if _v is not None:
self["arrangement"] = _v
_v = arg.pop("bundlecolors", None)
_v = bundlecolors if bundlecolors is not None else _v
if _v is not None:
self["bundlecolors"] = _v
_v = arg.pop("counts", None)
_v = counts if counts is not None else _v
if _v is not None:
self["counts"] = _v
_v = arg.pop("countssrc", None)
_v = countssrc if countssrc is not None else _v
if _v is not None:
self["countssrc"] = _v
_v = arg.pop("dimensions", None)
_v = dimensions if dimensions is not None else _v
if _v is not None:
self["dimensions"] = _v
_v = arg.pop("dimensiondefaults", None)
_v = dimensiondefaults if dimensiondefaults is not None else _v
if _v is not None:
self["dimensiondefaults"] = _v
_v = arg.pop("domain", None)
_v = domain if domain is not None else _v
if _v is not None:
self["domain"] = _v
_v = arg.pop("hoverinfo", None)
_v = hoverinfo if hoverinfo is not None else _v
if _v is not None:
self["hoverinfo"] = _v
_v = arg.pop("hoveron", None)
_v = hoveron if hoveron is not None else _v
if _v is not None:
self["hoveron"] = _v
_v = arg.pop("hovertemplate", None)
_v = hovertemplate if hovertemplate is not None else _v
if _v is not None:
self["hovertemplate"] = _v
_v = arg.pop("labelfont", None)
_v = labelfont if labelfont is not None else _v
if _v is not None:
self["labelfont"] = _v
_v = arg.pop("legendgrouptitle", None)
_v = legendgrouptitle if legendgrouptitle is not None else _v
if _v is not None:
self["legendgrouptitle"] = _v
_v = arg.pop("legendwidth", None)
_v = legendwidth if legendwidth is not None else _v
if _v is not None:
self["legendwidth"] = _v
_v = arg.pop("line", None)
_v = line if line is not None else _v
if _v is not None:
self["line"] = _v
_v = arg.pop("meta", None)
_v = meta if meta is not None else _v
if _v is not None:
self["meta"] = _v
_v = arg.pop("metasrc", None)
_v = metasrc if metasrc is not None else _v
if _v is not None:
self["metasrc"] = _v
_v = arg.pop("name", None)
_v = name if name is not None else _v
if _v is not None:
self["name"] = _v
_v = arg.pop("sortpaths", None)
_v = sortpaths if sortpaths is not None else _v
if _v is not None:
self["sortpaths"] = _v
_v = arg.pop("stream", None)
_v = stream if stream is not None else _v
if _v is not None:
self["stream"] = _v
_v = arg.pop("tickfont", None)
_v = tickfont if tickfont is not None else _v
if _v is not None:
self["tickfont"] = _v
_v = arg.pop("uid", None)
_v = uid if uid is not None else _v
if _v is not None:
self["uid"] = _v
_v = arg.pop("uirevision", None)
_v = uirevision if uirevision is not None else _v
if _v is not None:
self["uirevision"] = _v
_v = arg.pop("visible", None)
_v = visible if visible is not None else _v
if _v is not None:
self["visible"] = _v
# Read-only literals
# ------------------
self._props["type"] = "parcats"
arg.pop("type", None)
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| _parcats.Parcats.__init__ |
plotly.py | 34 | packages/python/plotly/plotly/graph_objs/_parcats.py | def dimensions(self):
"""
The dimensions (variables) of the parallel categories diagram.
The 'dimensions' property is a tuple of instances of
Dimension that may be specified as:
- A list or tuple of instances of plotly.graph_objs.parcats.Dimension
- A list or tuple of dicts of string/value properties that
will be passed to the Dimension constructor
Supported dict properties:
categoryarray
Sets the order in which categories in this
dimension appear. Only has an effect if
`categoryorder` is set to "array". Used with
`categoryorder`.
categoryarraysrc
Sets the source reference on Chart Studio Cloud
for `categoryarray`.
categoryorder
Specifies the ordering logic for the categories
in the dimension. By default, plotly uses
"trace", which specifies the order that is
present in the data supplied. Set
`categoryorder` to *category ascending* or
*category descending* if order should be
determined by the alphanumerical order of the
category names. Set `categoryorder` to "array"
to derive the ordering from the attribute
`categoryarray`. If a category is not found in
the `categoryarray` array, the sorting behavior
for that attribute will be identical to the
"trace" mode. The unspecified categories will
follow the categories in `categoryarray`.
displayindex
The display index of dimension, from left to
right, zero indexed, defaults to dimension
index.
label
The shown name of the dimension.
ticktext
Sets alternative tick labels for the categories
in this dimension. Only has an effect if
`categoryorder` is set to "array". Should be an
array the same length as `categoryarray` Used
with `categoryorder`.
ticktextsrc
Sets the source reference on Chart Studio Cloud
for `ticktext`.
values
Dimension values. `values[n]` represents the
category value of the `n`th point in the
dataset, therefore the `values` vector for all
dimensions must be the same (longer vectors
will be truncated).
valuessrc
Sets the source reference on Chart Studio Cloud
for `values`.
visible
Shows the dimension when set to `true` (the
default). Hides the dimension for `false`.
Returns
-------
tuple[plotly.graph_objs.parcats.Dimension]
"""
| /usr/src/app/target_test_cases/failed_tests__parcats.dimensions.txt | def dimensions(self):
"""
The dimensions (variables) of the parallel categories diagram.
The 'dimensions' property is a tuple of instances of
Dimension that may be specified as:
- A list or tuple of instances of plotly.graph_objs.parcats.Dimension
- A list or tuple of dicts of string/value properties that
will be passed to the Dimension constructor
Supported dict properties:
categoryarray
Sets the order in which categories in this
dimension appear. Only has an effect if
`categoryorder` is set to "array". Used with
`categoryorder`.
categoryarraysrc
Sets the source reference on Chart Studio Cloud
for `categoryarray`.
categoryorder
Specifies the ordering logic for the categories
in the dimension. By default, plotly uses
"trace", which specifies the order that is
present in the data supplied. Set
`categoryorder` to *category ascending* or
*category descending* if order should be
determined by the alphanumerical order of the
category names. Set `categoryorder` to "array"
to derive the ordering from the attribute
`categoryarray`. If a category is not found in
the `categoryarray` array, the sorting behavior
for that attribute will be identical to the
"trace" mode. The unspecified categories will
follow the categories in `categoryarray`.
displayindex
The display index of dimension, from left to
right, zero indexed, defaults to dimension
index.
label
The shown name of the dimension.
ticktext
Sets alternative tick labels for the categories
in this dimension. Only has an effect if
`categoryorder` is set to "array". Should be an
array the same length as `categoryarray` Used
with `categoryorder`.
ticktextsrc
Sets the source reference on Chart Studio Cloud
for `ticktext`.
values
Dimension values. `values[n]` represents the
category value of the `n`th point in the
dataset, therefore the `values` vector for all
dimensions must be the same (longer vectors
will be truncated).
valuessrc
Sets the source reference on Chart Studio Cloud
for `values`.
visible
Shows the dimension when set to `true` (the
default). Hides the dimension for `false`.
Returns
-------
tuple[plotly.graph_objs.parcats.Dimension]
"""
return self["dimensions"]
| _parcats.dimensions |
plotly.py | 35 | packages/python/plotly/plotly/graph_objs/_parcoords.py | def dimensions(self):
"""
The dimensions (variables) of the parallel coordinates chart.
2..60 dimensions are supported.
The 'dimensions' property is a tuple of instances of
Dimension that may be specified as:
- A list or tuple of instances of plotly.graph_objs.parcoords.Dimension
- A list or tuple of dicts of string/value properties that
will be passed to the Dimension constructor
Supported dict properties:
constraintrange
The domain range to which the filter on the
dimension is constrained. Must be an array of
`[fromValue, toValue]` with `fromValue <=
toValue`, or if `multiselect` is not disabled,
you may give an array of arrays, where each
inner array is `[fromValue, toValue]`.
label
The shown name of the dimension.
multiselect
Do we allow multiple selection ranges or just a
single range?
name
When used in a template, named items are
created in the output figure in addition to any
items the figure already has in this array. You
can modify these items in the output figure by
making your own item with `templateitemname`
matching this `name` alongside your
modifications (including `visible: false` or
`enabled: false` to hide it). Has no effect
outside of a template.
range
The domain range that represents the full,
shown axis extent. Defaults to the `values`
extent. Must be an array of `[fromValue,
toValue]` with finite numbers as elements.
templateitemname
Used to refer to a named item in this array in
the template. Named items from the template
will be created even without a matching item in
the input figure, but you can modify one by
making an item with `templateitemname` matching
its `name`, alongside your modifications
(including `visible: false` or `enabled: false`
to hide it). If there is no template or no
matching item, this item will be hidden unless
you explicitly show it with `visible: true`.
tickformat
Sets the tick label formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see: h
ttps://github.com/d3/d3-format/tree/v1.4.5#d3-
format. And for dates see:
https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two
items to d3's date formatter: "%h" for half of
the year as a decimal number as well as "%{n}f"
for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with
tickformat "%H~%M~%S.%2f" would display
"09~15~23.46"
ticktext
Sets the text displayed at the ticks position
via `tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud
for `ticktext`.
tickvals
Sets the values at which ticks on this axis
appear.
tickvalssrc
Sets the source reference on Chart Studio Cloud
for `tickvals`.
values
Dimension values. `values[n]` represents the
value of the `n`th point in the dataset,
therefore the `values` vector for all
dimensions must be the same (longer vectors
will be truncated). Each value must be a finite
number.
valuessrc
Sets the source reference on Chart Studio Cloud
for `values`.
visible
Shows the dimension when set to `true` (the
default). Hides the dimension for `false`.
Returns
-------
tuple[plotly.graph_objs.parcoords.Dimension]
"""
| /usr/src/app/target_test_cases/failed_tests__parcoords.dimensions.txt | def dimensions(self):
"""
The dimensions (variables) of the parallel coordinates chart.
2..60 dimensions are supported.
The 'dimensions' property is a tuple of instances of
Dimension that may be specified as:
- A list or tuple of instances of plotly.graph_objs.parcoords.Dimension
- A list or tuple of dicts of string/value properties that
will be passed to the Dimension constructor
Supported dict properties:
constraintrange
The domain range to which the filter on the
dimension is constrained. Must be an array of
`[fromValue, toValue]` with `fromValue <=
toValue`, or if `multiselect` is not disabled,
you may give an array of arrays, where each
inner array is `[fromValue, toValue]`.
label
The shown name of the dimension.
multiselect
Do we allow multiple selection ranges or just a
single range?
name
When used in a template, named items are
created in the output figure in addition to any
items the figure already has in this array. You
can modify these items in the output figure by
making your own item with `templateitemname`
matching this `name` alongside your
modifications (including `visible: false` or
`enabled: false` to hide it). Has no effect
outside of a template.
range
The domain range that represents the full,
shown axis extent. Defaults to the `values`
extent. Must be an array of `[fromValue,
toValue]` with finite numbers as elements.
templateitemname
Used to refer to a named item in this array in
the template. Named items from the template
will be created even without a matching item in
the input figure, but you can modify one by
making an item with `templateitemname` matching
its `name`, alongside your modifications
(including `visible: false` or `enabled: false`
to hide it). If there is no template or no
matching item, this item will be hidden unless
you explicitly show it with `visible: true`.
tickformat
Sets the tick label formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see: h
ttps://github.com/d3/d3-format/tree/v1.4.5#d3-
format. And for dates see:
https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two
items to d3's date formatter: "%h" for half of
the year as a decimal number as well as "%{n}f"
for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with
tickformat "%H~%M~%S.%2f" would display
"09~15~23.46"
ticktext
Sets the text displayed at the ticks position
via `tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud
for `ticktext`.
tickvals
Sets the values at which ticks on this axis
appear.
tickvalssrc
Sets the source reference on Chart Studio Cloud
for `tickvals`.
values
Dimension values. `values[n]` represents the
value of the `n`th point in the dataset,
therefore the `values` vector for all
dimensions must be the same (longer vectors
will be truncated). Each value must be a finite
number.
valuessrc
Sets the source reference on Chart Studio Cloud
for `values`.
visible
Shows the dimension when set to `true` (the
default). Hides the dimension for `false`.
Returns
-------
tuple[plotly.graph_objs.parcoords.Dimension]
"""
return self["dimensions"]
| _parcoords.dimensions |
plotly.py | 36 | packages/python/plotly/plotly/graph_objs/_parcoords.py | def line(self):
"""
The 'line' property is an instance of Line
that may be specified as:
- An instance of :class:`plotly.graph_objs.parcoords.Line`
- A dict of string/value properties that will be passed
to the Line constructor
Supported dict properties:
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `line.colorscale`. Has an effect
only if in `line.color` is set to a numerical
array. In case `colorscale` is unspecified or
`autocolorscale` is true, the default palette
will be chosen according to whether numbers in
the `color` array are all positive, all
negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `line.color`) or the bounds set in
`line.cmin` and `line.cmax` Has an effect only
if in `line.color` is set to a numerical array.
Defaults to `false` when `line.cmin` and
`line.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `line.color` is set to a
numerical array. Value should have the same
units as in `line.color` and if set,
`line.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `line.cmin` and/or `line.cmax` to be
equidistant to this point. Has an effect only
if in `line.color` is set to a numerical array.
Value should have the same units as in
`line.color`. Has no effect when `line.cauto`
is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `line.color` is set to a
numerical array. Value should have the same
units as in `line.color` and if set,
`line.cmax` must be set as well.
color
Sets the line color. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`line.cmin` and `line.cmax` if set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.parcoords.line.Col
orBar` instance or dict with compatible
properties
colorscale
Sets the colorscale. Has an effect only if in
`line.color` is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `line.cmin` and `line.cmax`.
Alternatively, `colorscale` may be a palette
name string of the following list: Blackbody,Bl
uered,Blues,Cividis,Earth,Electric,Greens,Greys
,Hot,Jet,Picnic,Portland,Rainbow,RdBu,Reds,Viri
dis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud
for `color`.
reversescale
Reverses the color mapping if true. Has an
effect only if in `line.color` is set to a
numerical array. If true, `line.cmin` will
correspond to the last color in the array and
`line.cmax` will correspond to the first color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
in `line.color` is set to a numerical array.
Returns
-------
plotly.graph_objs.parcoords.Line
"""
| /usr/src/app/target_test_cases/failed_tests__parcoords.line.txt | def line(self):
"""
The 'line' property is an instance of Line
that may be specified as:
- An instance of :class:`plotly.graph_objs.parcoords.Line`
- A dict of string/value properties that will be passed
to the Line constructor
Supported dict properties:
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `line.colorscale`. Has an effect
only if in `line.color` is set to a numerical
array. In case `colorscale` is unspecified or
`autocolorscale` is true, the default palette
will be chosen according to whether numbers in
the `color` array are all positive, all
negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `line.color`) or the bounds set in
`line.cmin` and `line.cmax` Has an effect only
if in `line.color` is set to a numerical array.
Defaults to `false` when `line.cmin` and
`line.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `line.color` is set to a
numerical array. Value should have the same
units as in `line.color` and if set,
`line.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `line.cmin` and/or `line.cmax` to be
equidistant to this point. Has an effect only
if in `line.color` is set to a numerical array.
Value should have the same units as in
`line.color`. Has no effect when `line.cauto`
is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `line.color` is set to a
numerical array. Value should have the same
units as in `line.color` and if set,
`line.cmax` must be set as well.
color
Sets the line color. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`line.cmin` and `line.cmax` if set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.parcoords.line.Col
orBar` instance or dict with compatible
properties
colorscale
Sets the colorscale. Has an effect only if in
`line.color` is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `line.cmin` and `line.cmax`.
Alternatively, `colorscale` may be a palette
name string of the following list: Blackbody,Bl
uered,Blues,Cividis,Earth,Electric,Greens,Greys
,Hot,Jet,Picnic,Portland,Rainbow,RdBu,Reds,Viri
dis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud
for `color`.
reversescale
Reverses the color mapping if true. Has an
effect only if in `line.color` is set to a
numerical array. If true, `line.cmin` will
correspond to the last color in the array and
`line.cmax` will correspond to the first color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
in `line.color` is set to a numerical array.
Returns
-------
plotly.graph_objs.parcoords.Line
"""
return self["line"]
| _parcoords.line |
plotly.py | 37 | packages/python/plotly/plotly/graph_objs/layout/_polar.py | def angularaxis(self):
"""
The 'angularaxis' property is an instance of AngularAxis
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.polar.AngularAxis`
- A dict of string/value properties that will be passed
to the AngularAxis constructor
Supported dict properties:
autotypenumbers
Using "strict" a numeric string in trace data
is not converted to a number. Using *convert
types* a numeric string in trace data may be
treated as a number during automatic axis
`type` detection. Defaults to
layout.autotypenumbers.
categoryarray
Sets the order in which categories on this axis
appear. Only has an effect if `categoryorder`
is set to "array". Used with `categoryorder`.
categoryarraysrc
Sets the source reference on Chart Studio Cloud
for `categoryarray`.
categoryorder
Specifies the ordering logic for the case of
categorical variables. By default, plotly uses
"trace", which specifies the order that is
present in the data supplied. Set
`categoryorder` to *category ascending* or
*category descending* if order should be
determined by the alphanumerical order of the
category names. Set `categoryorder` to "array"
to derive the ordering from the attribute
`categoryarray`. If a category is not found in
the `categoryarray` array, the sorting behavior
for that attribute will be identical to the
"trace" mode. The unspecified categories will
follow the categories in `categoryarray`. Set
`categoryorder` to *total ascending* or *total
descending* if order should be determined by
the numerical order of the values. Similarly,
the order can be determined by the min, max,
sum, mean, geometric mean or median of all the
values.
color
Sets default for all colors associated with
this axis all at once: line, font, tick, and
grid colors. Grid color is lightened by
blending this with the plot background
Individual pieces can override this.
direction
Sets the direction corresponding to positive
angles.
dtick
Sets the step in-between ticks on this axis.
Use with `tick0`. Must be a positive number, or
special strings available to "log" and "date"
axes. If the axis `type` is "log", then ticks
are set every 10^(n*dtick) where n is the tick
number. For example, to set a tick mark at 1,
10, 100, 1000, ... set dtick to 1. To set tick
marks at 1, 100, 10000, ... set dtick to 2. To
set tick marks at 1, 5, 25, 125, 625, 3125, ...
set dtick to log_10(5), or 0.69897000433. "log"
has several special values; "L<f>", where `f`
is a positive number, gives ticks linearly
spaced in value (but not position). For example
`tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10
plus small digits between, use "D1" (all
digits) or "D2" (only 2 and 5). `tick0` is
ignored for "D1" and "D2". If the axis `type`
is "date", then you must convert the time to
milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to
86400000.0. "date" also has special values
"M<n>" gives ticks spaced by a number of
months. `n` must be a positive integer. To set
ticks on the 15th of every third month, set
`tick0` to "2000-01-15" and `dtick` to "M3". To
set ticks every 4 years, set `dtick` to "M48"
exponentformat
Determines a formatting rule for the tick
exponents. For example, consider the number
1,000,000,000. If "none", it appears as
1,000,000,000. If "e", 1e+9. If "E", 1E+9. If
"power", 1x10^9 (with 9 in a super script). If
"SI", 1G. If "B", 1B.
gridcolor
Sets the color of the grid lines.
griddash
Sets the dash style of lines. Set to a dash
type string ("solid", "dot", "dash",
"longdash", "dashdot", or "longdashdot") or a
dash length list in px (eg "5px,10px,2px,2px").
gridwidth
Sets the width (in px) of the grid lines.
hoverformat
Sets the hover text formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see: h
ttps://github.com/d3/d3-format/tree/v1.4.5#d3-
format. And for dates see:
https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two
items to d3's date formatter: "%h" for half of
the year as a decimal number as well as "%{n}f"
for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with
tickformat "%H~%M~%S.%2f" would display
"09~15~23.46"
labelalias
Replacement text for specific tick or hover
labels. For example using {US: 'USA', CA:
'Canada'} changes US to USA and CA to Canada.
The labels we would have shown must match the
keys exactly, after adding any tickprefix or
ticksuffix. For negative numbers the minus sign
symbol used (U+2212) is wider than the regular
ascii dash. That means you need to use −1
instead of -1. labelalias can be used with any
axis type, and both keys (if needed) and values
(if desired) can include html-like tags or
MathJax.
layer
Sets the layer on which this axis is displayed.
If *above traces*, this axis is displayed above
all the subplot's traces If *below traces*,
this axis is displayed below all the subplot's
traces, but above the grid lines. Useful when
used together with scatter-like traces with
`cliponaxis` set to False to show markers
and/or text nodes above this axis.
linecolor
Sets the axis line color.
linewidth
Sets the width (in px) of the axis line.
minexponent
Hide SI prefix for 10^n if |n| is below this
number. This only has an effect when
`tickformat` is "SI" or "B".
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks
will be chosen automatically to be less than or
equal to `nticks`. Has an effect only if
`tickmode` is set to "auto".
period
Set the angular period. Has an effect only when
`angularaxis.type` is "category".
rotation
Sets that start position (in degrees) of the
angular axis By default, polar subplots with
`direction` set to "counterclockwise" get a
`rotation` of 0 which corresponds to due East
(like what mathematicians prefer). In turn,
polar with `direction` set to "clockwise" get a
rotation of 90 which corresponds to due North
(like on a compass),
separatethousands
If "true", even 4-digit integers are separated
showexponent
If "all", all exponents are shown besides their
significands. If "first", only the exponent of
the first tick is shown. If "last", only the
exponent of the last tick is shown. If "none",
no exponents appear.
showgrid
Determines whether or not grid lines are drawn.
If True, the grid lines are drawn at every tick
mark.
showline
Determines whether or not a line bounding this
axis is drawn.
showticklabels
Determines whether or not the tick labels are
drawn.
showtickprefix
If "all", all tick labels are displayed with a
prefix. If "first", only the first tick is
displayed with a prefix. If "last", only the
last tick is displayed with a suffix. If
"none", tick prefixes are hidden.
showticksuffix
Same as `showtickprefix` but for tick suffixes.
thetaunit
Sets the format unit of the formatted "theta"
values. Has an effect only when
`angularaxis.type` is "linear".
tick0
Sets the placement of the first tick on this
axis. Use with `dtick`. If the axis `type` is
"log", then you must take the log of your
starting tick (e.g. to set the starting tick to
100, set the `tick0` to 2) except when
`dtick`=*L<f>* (see `dtick` for more info). If
the axis `type` is "date", it should be a date
string, like date data. If the axis `type` is
"category", it should be a number, using the
scale where each category is assigned a serial
number from zero in the order it appears.
tickangle
Sets the angle of the tick labels with respect
to the horizontal. For example, a `tickangle`
of -90 draws the tick labels vertically.
tickcolor
Sets the tick color.
tickfont
Sets the tick font.
tickformat
Sets the tick label formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see: h
ttps://github.com/d3/d3-format/tree/v1.4.5#d3-
format. And for dates see:
https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two
items to d3's date formatter: "%h" for half of
the year as a decimal number as well as "%{n}f"
for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with
tickformat "%H~%M~%S.%2f" would display
"09~15~23.46"
tickformatstops
A tuple of :class:`plotly.graph_objects.layout.
polar.angularaxis.Tickformatstop` instances or
dicts with compatible properties
tickformatstopdefaults
When used in a template (as layout.template.lay
out.polar.angularaxis.tickformatstopdefaults),
sets the default property values to use for
elements of
layout.polar.angularaxis.tickformatstops
ticklabelstep
Sets the spacing between tick labels as
compared to the spacing between ticks. A value
of 1 (default) means each tick gets a label. A
value of 2 means shows every 2nd label. A
larger value n means only every nth tick is
labeled. `tick0` determines which labels are
shown. Not implemented for axes with `type`
"log" or "multicategory", or when `tickmode` is
"array".
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto",
the number of ticks is set via `nticks`. If
"linear", the placement of the ticks is
determined by a starting position `tick0` and a
tick step `dtick` ("linear" is the default
value if `tick0` and `dtick` are provided). If
"array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`.
("array" is the default value if `tickvals` is
provided).
tickprefix
Sets a tick label prefix.
ticks
Determines whether ticks are drawn or not. If
"", this axis' ticks are not drawn. If
"outside" ("inside"), this axis' are drawn
outside (inside) the axis lines.
ticksuffix
Sets a tick label suffix.
ticktext
Sets the text displayed at the ticks position
via `tickvals`. Only has an effect if
`tickmode` is set to "array". Used with
`tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud
for `ticktext`.
tickvals
Sets the values at which ticks on this axis
appear. Only has an effect if `tickmode` is set
to "array". Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud
for `tickvals`.
tickwidth
Sets the tick width (in px).
type
Sets the angular axis type. If "linear", set
`thetaunit` to determine the unit in which axis
value are shown. If *category, use `period` to
set the number of integer coordinates around
polar axis.
uirevision
Controls persistence of user-driven changes in
axis `rotation`. Defaults to
`polar<N>.uirevision`.
visible
A single toggle to hide the axis while
preserving interaction like dragging. Default
is true when a cheater plot is present on the
axis, otherwise false
Returns
-------
plotly.graph_objs.layout.polar.AngularAxis
"""
| /usr/src/app/target_test_cases/failed_tests__polar.angularaxis.txt | def angularaxis(self):
"""
The 'angularaxis' property is an instance of AngularAxis
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.polar.AngularAxis`
- A dict of string/value properties that will be passed
to the AngularAxis constructor
Supported dict properties:
autotypenumbers
Using "strict" a numeric string in trace data
is not converted to a number. Using *convert
types* a numeric string in trace data may be
treated as a number during automatic axis
`type` detection. Defaults to
layout.autotypenumbers.
categoryarray
Sets the order in which categories on this axis
appear. Only has an effect if `categoryorder`
is set to "array". Used with `categoryorder`.
categoryarraysrc
Sets the source reference on Chart Studio Cloud
for `categoryarray`.
categoryorder
Specifies the ordering logic for the case of
categorical variables. By default, plotly uses
"trace", which specifies the order that is
present in the data supplied. Set
`categoryorder` to *category ascending* or
*category descending* if order should be
determined by the alphanumerical order of the
category names. Set `categoryorder` to "array"
to derive the ordering from the attribute
`categoryarray`. If a category is not found in
the `categoryarray` array, the sorting behavior
for that attribute will be identical to the
"trace" mode. The unspecified categories will
follow the categories in `categoryarray`. Set
`categoryorder` to *total ascending* or *total
descending* if order should be determined by
the numerical order of the values. Similarly,
the order can be determined by the min, max,
sum, mean, geometric mean or median of all the
values.
color
Sets default for all colors associated with
this axis all at once: line, font, tick, and
grid colors. Grid color is lightened by
blending this with the plot background
Individual pieces can override this.
direction
Sets the direction corresponding to positive
angles.
dtick
Sets the step in-between ticks on this axis.
Use with `tick0`. Must be a positive number, or
special strings available to "log" and "date"
axes. If the axis `type` is "log", then ticks
are set every 10^(n*dtick) where n is the tick
number. For example, to set a tick mark at 1,
10, 100, 1000, ... set dtick to 1. To set tick
marks at 1, 100, 10000, ... set dtick to 2. To
set tick marks at 1, 5, 25, 125, 625, 3125, ...
set dtick to log_10(5), or 0.69897000433. "log"
has several special values; "L<f>", where `f`
is a positive number, gives ticks linearly
spaced in value (but not position). For example
`tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10
plus small digits between, use "D1" (all
digits) or "D2" (only 2 and 5). `tick0` is
ignored for "D1" and "D2". If the axis `type`
is "date", then you must convert the time to
milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to
86400000.0. "date" also has special values
"M<n>" gives ticks spaced by a number of
months. `n` must be a positive integer. To set
ticks on the 15th of every third month, set
`tick0` to "2000-01-15" and `dtick` to "M3". To
set ticks every 4 years, set `dtick` to "M48"
exponentformat
Determines a formatting rule for the tick
exponents. For example, consider the number
1,000,000,000. If "none", it appears as
1,000,000,000. If "e", 1e+9. If "E", 1E+9. If
"power", 1x10^9 (with 9 in a super script). If
"SI", 1G. If "B", 1B.
gridcolor
Sets the color of the grid lines.
griddash
Sets the dash style of lines. Set to a dash
type string ("solid", "dot", "dash",
"longdash", "dashdot", or "longdashdot") or a
dash length list in px (eg "5px,10px,2px,2px").
gridwidth
Sets the width (in px) of the grid lines.
hoverformat
Sets the hover text formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see: h
ttps://github.com/d3/d3-format/tree/v1.4.5#d3-
format. And for dates see:
https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two
items to d3's date formatter: "%h" for half of
the year as a decimal number as well as "%{n}f"
for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with
tickformat "%H~%M~%S.%2f" would display
"09~15~23.46"
labelalias
Replacement text for specific tick or hover
labels. For example using {US: 'USA', CA:
'Canada'} changes US to USA and CA to Canada.
The labels we would have shown must match the
keys exactly, after adding any tickprefix or
ticksuffix. For negative numbers the minus sign
symbol used (U+2212) is wider than the regular
ascii dash. That means you need to use −1
instead of -1. labelalias can be used with any
axis type, and both keys (if needed) and values
(if desired) can include html-like tags or
MathJax.
layer
Sets the layer on which this axis is displayed.
If *above traces*, this axis is displayed above
all the subplot's traces If *below traces*,
this axis is displayed below all the subplot's
traces, but above the grid lines. Useful when
used together with scatter-like traces with
`cliponaxis` set to False to show markers
and/or text nodes above this axis.
linecolor
Sets the axis line color.
linewidth
Sets the width (in px) of the axis line.
minexponent
Hide SI prefix for 10^n if |n| is below this
number. This only has an effect when
`tickformat` is "SI" or "B".
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks
will be chosen automatically to be less than or
equal to `nticks`. Has an effect only if
`tickmode` is set to "auto".
period
Set the angular period. Has an effect only when
`angularaxis.type` is "category".
rotation
Sets that start position (in degrees) of the
angular axis By default, polar subplots with
`direction` set to "counterclockwise" get a
`rotation` of 0 which corresponds to due East
(like what mathematicians prefer). In turn,
polar with `direction` set to "clockwise" get a
rotation of 90 which corresponds to due North
(like on a compass),
separatethousands
If "true", even 4-digit integers are separated
showexponent
If "all", all exponents are shown besides their
significands. If "first", only the exponent of
the first tick is shown. If "last", only the
exponent of the last tick is shown. If "none",
no exponents appear.
showgrid
Determines whether or not grid lines are drawn.
If True, the grid lines are drawn at every tick
mark.
showline
Determines whether or not a line bounding this
axis is drawn.
showticklabels
Determines whether or not the tick labels are
drawn.
showtickprefix
If "all", all tick labels are displayed with a
prefix. If "first", only the first tick is
displayed with a prefix. If "last", only the
last tick is displayed with a suffix. If
"none", tick prefixes are hidden.
showticksuffix
Same as `showtickprefix` but for tick suffixes.
thetaunit
Sets the format unit of the formatted "theta"
values. Has an effect only when
`angularaxis.type` is "linear".
tick0
Sets the placement of the first tick on this
axis. Use with `dtick`. If the axis `type` is
"log", then you must take the log of your
starting tick (e.g. to set the starting tick to
100, set the `tick0` to 2) except when
`dtick`=*L<f>* (see `dtick` for more info). If
the axis `type` is "date", it should be a date
string, like date data. If the axis `type` is
"category", it should be a number, using the
scale where each category is assigned a serial
number from zero in the order it appears.
tickangle
Sets the angle of the tick labels with respect
to the horizontal. For example, a `tickangle`
of -90 draws the tick labels vertically.
tickcolor
Sets the tick color.
tickfont
Sets the tick font.
tickformat
Sets the tick label formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see: h
ttps://github.com/d3/d3-format/tree/v1.4.5#d3-
format. And for dates see:
https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two
items to d3's date formatter: "%h" for half of
the year as a decimal number as well as "%{n}f"
for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with
tickformat "%H~%M~%S.%2f" would display
"09~15~23.46"
tickformatstops
A tuple of :class:`plotly.graph_objects.layout.
polar.angularaxis.Tickformatstop` instances or
dicts with compatible properties
tickformatstopdefaults
When used in a template (as layout.template.lay
out.polar.angularaxis.tickformatstopdefaults),
sets the default property values to use for
elements of
layout.polar.angularaxis.tickformatstops
ticklabelstep
Sets the spacing between tick labels as
compared to the spacing between ticks. A value
of 1 (default) means each tick gets a label. A
value of 2 means shows every 2nd label. A
larger value n means only every nth tick is
labeled. `tick0` determines which labels are
shown. Not implemented for axes with `type`
"log" or "multicategory", or when `tickmode` is
"array".
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto",
the number of ticks is set via `nticks`. If
"linear", the placement of the ticks is
determined by a starting position `tick0` and a
tick step `dtick` ("linear" is the default
value if `tick0` and `dtick` are provided). If
"array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`.
("array" is the default value if `tickvals` is
provided).
tickprefix
Sets a tick label prefix.
ticks
Determines whether ticks are drawn or not. If
"", this axis' ticks are not drawn. If
"outside" ("inside"), this axis' are drawn
outside (inside) the axis lines.
ticksuffix
Sets a tick label suffix.
ticktext
Sets the text displayed at the ticks position
via `tickvals`. Only has an effect if
`tickmode` is set to "array". Used with
`tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud
for `ticktext`.
tickvals
Sets the values at which ticks on this axis
appear. Only has an effect if `tickmode` is set
to "array". Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud
for `tickvals`.
tickwidth
Sets the tick width (in px).
type
Sets the angular axis type. If "linear", set
`thetaunit` to determine the unit in which axis
value are shown. If *category, use `period` to
set the number of integer coordinates around
polar axis.
uirevision
Controls persistence of user-driven changes in
axis `rotation`. Defaults to
`polar<N>.uirevision`.
visible
A single toggle to hide the axis while
preserving interaction like dragging. Default
is true when a cheater plot is present on the
axis, otherwise false
Returns
-------
plotly.graph_objs.layout.polar.AngularAxis
"""
return self["angularaxis"]
| _polar.angularaxis |
plotly.py | 38 | packages/python/plotly/plotly/figure_factory/_quiver.py | def create_quiver(
x, y, u, v, scale=0.1, arrow_scale=0.3, angle=math.pi / 9, scaleratio=None, **kwargs
):
"""
Returns data for a quiver plot.
:param (list|ndarray) x: x coordinates of the arrow locations
:param (list|ndarray) y: y coordinates of the arrow locations
:param (list|ndarray) u: x components of the arrow vectors
:param (list|ndarray) v: y components of the arrow vectors
:param (float in [0,1]) scale: scales size of the arrows(ideally to
avoid overlap). Default = .1
:param (float in [0,1]) arrow_scale: value multiplied to length of barb
to get length of arrowhead. Default = .3
:param (angle in radians) angle: angle of arrowhead. Default = pi/9
:param (positive float) scaleratio: the ratio between the scale of the y-axis
and the scale of the x-axis (scale_y / scale_x). Default = None, the
scale ratio is not fixed.
:param kwargs: kwargs passed through plotly.graph_objs.Scatter
for more information on valid kwargs call
help(plotly.graph_objs.Scatter)
:rtype (dict): returns a representation of quiver figure.
Example 1: Trivial Quiver
>>> from plotly.figure_factory import create_quiver
>>> import math
>>> # 1 Arrow from (0,0) to (1,1)
>>> fig = create_quiver(x=[0], y=[0], u=[1], v=[1], scale=1)
>>> fig.show()
Example 2: Quiver plot using meshgrid
>>> from plotly.figure_factory import create_quiver
>>> import numpy as np
>>> import math
>>> # Add data
>>> x,y = np.meshgrid(np.arange(0, 2, .2), np.arange(0, 2, .2))
>>> u = np.cos(x)*y
>>> v = np.sin(x)*y
>>> #Create quiver
>>> fig = create_quiver(x, y, u, v)
>>> fig.show()
Example 3: Styling the quiver plot
>>> from plotly.figure_factory import create_quiver
>>> import numpy as np
>>> import math
>>> # Add data
>>> x, y = np.meshgrid(np.arange(-np.pi, math.pi, .5),
... np.arange(-math.pi, math.pi, .5))
>>> u = np.cos(x)*y
>>> v = np.sin(x)*y
>>> # Create quiver
>>> fig = create_quiver(x, y, u, v, scale=.2, arrow_scale=.3, angle=math.pi/6,
... name='Wind Velocity', line=dict(width=1))
>>> # Add title to layout
>>> fig.update_layout(title='Quiver Plot') # doctest: +SKIP
>>> fig.show()
Example 4: Forcing a fix scale ratio to maintain the arrow length
>>> from plotly.figure_factory import create_quiver
>>> import numpy as np
>>> # Add data
>>> x,y = np.meshgrid(np.arange(0.5, 3.5, .5), np.arange(0.5, 4.5, .5))
>>> u = x
>>> v = y
>>> angle = np.arctan(v / u)
>>> norm = 0.25
>>> u = norm * np.cos(angle)
>>> v = norm * np.sin(angle)
>>> # Create quiver with a fix scale ratio
>>> fig = create_quiver(x, y, u, v, scale = 1, scaleratio = 0.5)
>>> fig.show()
"""
| /usr/src/app/target_test_cases/failed_tests__quiver.create_quiver.txt | def create_quiver(
x, y, u, v, scale=0.1, arrow_scale=0.3, angle=math.pi / 9, scaleratio=None, **kwargs
):
"""
Returns data for a quiver plot.
:param (list|ndarray) x: x coordinates of the arrow locations
:param (list|ndarray) y: y coordinates of the arrow locations
:param (list|ndarray) u: x components of the arrow vectors
:param (list|ndarray) v: y components of the arrow vectors
:param (float in [0,1]) scale: scales size of the arrows(ideally to
avoid overlap). Default = .1
:param (float in [0,1]) arrow_scale: value multiplied to length of barb
to get length of arrowhead. Default = .3
:param (angle in radians) angle: angle of arrowhead. Default = pi/9
:param (positive float) scaleratio: the ratio between the scale of the y-axis
and the scale of the x-axis (scale_y / scale_x). Default = None, the
scale ratio is not fixed.
:param kwargs: kwargs passed through plotly.graph_objs.Scatter
for more information on valid kwargs call
help(plotly.graph_objs.Scatter)
:rtype (dict): returns a representation of quiver figure.
Example 1: Trivial Quiver
>>> from plotly.figure_factory import create_quiver
>>> import math
>>> # 1 Arrow from (0,0) to (1,1)
>>> fig = create_quiver(x=[0], y=[0], u=[1], v=[1], scale=1)
>>> fig.show()
Example 2: Quiver plot using meshgrid
>>> from plotly.figure_factory import create_quiver
>>> import numpy as np
>>> import math
>>> # Add data
>>> x,y = np.meshgrid(np.arange(0, 2, .2), np.arange(0, 2, .2))
>>> u = np.cos(x)*y
>>> v = np.sin(x)*y
>>> #Create quiver
>>> fig = create_quiver(x, y, u, v)
>>> fig.show()
Example 3: Styling the quiver plot
>>> from plotly.figure_factory import create_quiver
>>> import numpy as np
>>> import math
>>> # Add data
>>> x, y = np.meshgrid(np.arange(-np.pi, math.pi, .5),
... np.arange(-math.pi, math.pi, .5))
>>> u = np.cos(x)*y
>>> v = np.sin(x)*y
>>> # Create quiver
>>> fig = create_quiver(x, y, u, v, scale=.2, arrow_scale=.3, angle=math.pi/6,
... name='Wind Velocity', line=dict(width=1))
>>> # Add title to layout
>>> fig.update_layout(title='Quiver Plot') # doctest: +SKIP
>>> fig.show()
Example 4: Forcing a fix scale ratio to maintain the arrow length
>>> from plotly.figure_factory import create_quiver
>>> import numpy as np
>>> # Add data
>>> x,y = np.meshgrid(np.arange(0.5, 3.5, .5), np.arange(0.5, 4.5, .5))
>>> u = x
>>> v = y
>>> angle = np.arctan(v / u)
>>> norm = 0.25
>>> u = norm * np.cos(angle)
>>> v = norm * np.sin(angle)
>>> # Create quiver with a fix scale ratio
>>> fig = create_quiver(x, y, u, v, scale = 1, scaleratio = 0.5)
>>> fig.show()
"""
utils.validate_equal_length(x, y, u, v)
utils.validate_positive_scalars(arrow_scale=arrow_scale, scale=scale)
if scaleratio is None:
quiver_obj = _Quiver(x, y, u, v, scale, arrow_scale, angle)
else:
quiver_obj = _Quiver(x, y, u, v, scale, arrow_scale, angle, scaleratio)
barb_x, barb_y = quiver_obj.get_barbs()
arrow_x, arrow_y = quiver_obj.get_quiver_arrows()
quiver_plot = graph_objs.Scatter(
x=barb_x + arrow_x, y=barb_y + arrow_y, mode="lines", **kwargs
)
data = [quiver_plot]
if scaleratio is None:
layout = graph_objs.Layout(hovermode="closest")
else:
layout = graph_objs.Layout(
hovermode="closest", yaxis=dict(scaleratio=scaleratio, scaleanchor="x")
)
return graph_objs.Figure(data=data, layout=layout)
| _quiver.create_quiver |
plotly.py | 39 | packages/python/plotly/plotly/graph_objs/_sankey.py | def __init__(
self,
arg=None,
arrangement=None,
customdata=None,
customdatasrc=None,
domain=None,
hoverinfo=None,
hoverlabel=None,
ids=None,
idssrc=None,
legend=None,
legendgrouptitle=None,
legendrank=None,
legendwidth=None,
link=None,
meta=None,
metasrc=None,
name=None,
node=None,
orientation=None,
selectedpoints=None,
stream=None,
textfont=None,
uid=None,
uirevision=None,
valueformat=None,
valuesuffix=None,
visible=None,
**kwargs,
):
"""
Construct a new Sankey object
Sankey plots for network flow data analysis. The nodes are
specified in `nodes` and the links between sources and targets
in `links`. The colors are set in `nodes[i].color` and
`links[i].color`, otherwise defaults are used.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.Sankey`
arrangement
If value is `snap` (the default), the node arrangement
is assisted by automatic snapping of elements to
preserve space between nodes specified via `nodepad`.
If value is `perpendicular`, the nodes can only move
along a line perpendicular to the flow. If value is
`freeform`, the nodes can freely move on the plane. If
value is `fixed`, the nodes are stationary.
customdata
Assigns extra data each datum. This may be useful when
listening to hover, click and selection events. Note
that, "scatter" traces also appends customdata items in
the markers DOM elements
customdatasrc
Sets the source reference on Chart Studio Cloud for
`customdata`.
domain
:class:`plotly.graph_objects.sankey.Domain` instance or
dict with compatible properties
hoverinfo
Determines which trace information appear on hover. If
`none` or `skip` are set, no information is displayed
upon hovering. But, if `none` is set, click and hover
events are still fired. Note that this attribute is
superseded by `node.hoverinfo` and `node.hoverinfo` for
nodes and links respectively.
hoverlabel
:class:`plotly.graph_objects.sankey.Hoverlabel`
instance or dict with compatible properties
ids
Assigns id labels to each datum. These ids for object
constancy of data points during animation. Should be an
array of strings, not numbers or any other type.
idssrc
Sets the source reference on Chart Studio Cloud for
`ids`.
legend
Sets the reference to a legend to show this trace in.
References to these legends are "legend", "legend2",
"legend3", etc. Settings for these legends are set in
the layout, under `layout.legend`, `layout.legend2`,
etc.
legendgrouptitle
:class:`plotly.graph_objects.sankey.Legendgrouptitle`
instance or dict with compatible properties
legendrank
Sets the legend rank for this trace. Items and groups
with smaller ranks are presented on top/left side while
with "reversed" `legend.traceorder` they are on
bottom/right side. The default legendrank is 1000, so
that you can use ranks less than 1000 to place certain
items before all unranked items, and ranks greater than
1000 to go after all unranked items. When having
unranked or equal rank items shapes would be displayed
after traces i.e. according to their order in data and
layout.
legendwidth
Sets the width (in px or fraction) of the legend for
this trace.
link
The links of the Sankey plot.
meta
Assigns extra meta information associated with this
trace that can be used in various text attributes.
Attributes such as trace `name`, graph, axis and
colorbar `title.text`, annotation `text`
`rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta`
values in an attribute in the same trace, simply use
`%{meta[i]}` where `i` is the index or key of the
`meta` item in question. To access trace `meta` in
layout attributes, use `%{data[n[.meta[i]}` where `i`
is the index or key of the `meta` and `n` is the trace
index.
metasrc
Sets the source reference on Chart Studio Cloud for
`meta`.
name
Sets the trace name. The trace name appears as the
legend item and on hover.
node
The nodes of the Sankey plot.
orientation
Sets the orientation of the Sankey diagram.
selectedpoints
Array containing integer indices of selected points.
Has an effect only for traces that support selections.
Note that an empty array means an empty selection where
the `unselected` are turned on for all points, whereas,
any other non-array values means no selection all where
the `selected` and `unselected` styles have no effect.
stream
:class:`plotly.graph_objects.sankey.Stream` instance or
dict with compatible properties
textfont
Sets the font for node labels
uid
Assign an id to this trace, Use this to provide object
constancy between traces during animations and
transitions.
uirevision
Controls persistence of some user-driven changes to the
trace: `constraintrange` in `parcoords` traces, as well
as some `editable: true` modifications such as `name`
and `colorbar.title`. Defaults to `layout.uirevision`.
Note that other user-driven trace attribute changes are
controlled by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
valueformat
Sets the value formatting rule using d3 formatting
mini-languages which are very similar to those in
Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
valuesuffix
Adds a unit to follow the value in the hover tooltip.
Add a space if a separation is necessary from the
value.
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
Returns
-------
Sankey
"""
| /usr/src/app/target_test_cases/failed_tests__sankey.Sankey.__init__.txt | def __init__(
self,
arg=None,
arrangement=None,
customdata=None,
customdatasrc=None,
domain=None,
hoverinfo=None,
hoverlabel=None,
ids=None,
idssrc=None,
legend=None,
legendgrouptitle=None,
legendrank=None,
legendwidth=None,
link=None,
meta=None,
metasrc=None,
name=None,
node=None,
orientation=None,
selectedpoints=None,
stream=None,
textfont=None,
uid=None,
uirevision=None,
valueformat=None,
valuesuffix=None,
visible=None,
**kwargs,
):
"""
Construct a new Sankey object
Sankey plots for network flow data analysis. The nodes are
specified in `nodes` and the links between sources and targets
in `links`. The colors are set in `nodes[i].color` and
`links[i].color`, otherwise defaults are used.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.Sankey`
arrangement
If value is `snap` (the default), the node arrangement
is assisted by automatic snapping of elements to
preserve space between nodes specified via `nodepad`.
If value is `perpendicular`, the nodes can only move
along a line perpendicular to the flow. If value is
`freeform`, the nodes can freely move on the plane. If
value is `fixed`, the nodes are stationary.
customdata
Assigns extra data each datum. This may be useful when
listening to hover, click and selection events. Note
that, "scatter" traces also appends customdata items in
the markers DOM elements
customdatasrc
Sets the source reference on Chart Studio Cloud for
`customdata`.
domain
:class:`plotly.graph_objects.sankey.Domain` instance or
dict with compatible properties
hoverinfo
Determines which trace information appear on hover. If
`none` or `skip` are set, no information is displayed
upon hovering. But, if `none` is set, click and hover
events are still fired. Note that this attribute is
superseded by `node.hoverinfo` and `node.hoverinfo` for
nodes and links respectively.
hoverlabel
:class:`plotly.graph_objects.sankey.Hoverlabel`
instance or dict with compatible properties
ids
Assigns id labels to each datum. These ids for object
constancy of data points during animation. Should be an
array of strings, not numbers or any other type.
idssrc
Sets the source reference on Chart Studio Cloud for
`ids`.
legend
Sets the reference to a legend to show this trace in.
References to these legends are "legend", "legend2",
"legend3", etc. Settings for these legends are set in
the layout, under `layout.legend`, `layout.legend2`,
etc.
legendgrouptitle
:class:`plotly.graph_objects.sankey.Legendgrouptitle`
instance or dict with compatible properties
legendrank
Sets the legend rank for this trace. Items and groups
with smaller ranks are presented on top/left side while
with "reversed" `legend.traceorder` they are on
bottom/right side. The default legendrank is 1000, so
that you can use ranks less than 1000 to place certain
items before all unranked items, and ranks greater than
1000 to go after all unranked items. When having
unranked or equal rank items shapes would be displayed
after traces i.e. according to their order in data and
layout.
legendwidth
Sets the width (in px or fraction) of the legend for
this trace.
link
The links of the Sankey plot.
meta
Assigns extra meta information associated with this
trace that can be used in various text attributes.
Attributes such as trace `name`, graph, axis and
colorbar `title.text`, annotation `text`
`rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta`
values in an attribute in the same trace, simply use
`%{meta[i]}` where `i` is the index or key of the
`meta` item in question. To access trace `meta` in
layout attributes, use `%{data[n[.meta[i]}` where `i`
is the index or key of the `meta` and `n` is the trace
index.
metasrc
Sets the source reference on Chart Studio Cloud for
`meta`.
name
Sets the trace name. The trace name appears as the
legend item and on hover.
node
The nodes of the Sankey plot.
orientation
Sets the orientation of the Sankey diagram.
selectedpoints
Array containing integer indices of selected points.
Has an effect only for traces that support selections.
Note that an empty array means an empty selection where
the `unselected` are turned on for all points, whereas,
any other non-array values means no selection all where
the `selected` and `unselected` styles have no effect.
stream
:class:`plotly.graph_objects.sankey.Stream` instance or
dict with compatible properties
textfont
Sets the font for node labels
uid
Assign an id to this trace, Use this to provide object
constancy between traces during animations and
transitions.
uirevision
Controls persistence of some user-driven changes to the
trace: `constraintrange` in `parcoords` traces, as well
as some `editable: true` modifications such as `name`
and `colorbar.title`. Defaults to `layout.uirevision`.
Note that other user-driven trace attribute changes are
controlled by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
valueformat
Sets the value formatting rule using d3 formatting
mini-languages which are very similar to those in
Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
valuesuffix
Adds a unit to follow the value in the hover tooltip.
Add a space if a separation is necessary from the
value.
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
Returns
-------
Sankey
"""
super(Sankey, self).__init__("sankey")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.Sankey
constructor must be a dict or
an instance of :class:`plotly.graph_objs.Sankey`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("arrangement", None)
_v = arrangement if arrangement is not None else _v
if _v is not None:
self["arrangement"] = _v
_v = arg.pop("customdata", None)
_v = customdata if customdata is not None else _v
if _v is not None:
self["customdata"] = _v
_v = arg.pop("customdatasrc", None)
_v = customdatasrc if customdatasrc is not None else _v
if _v is not None:
self["customdatasrc"] = _v
_v = arg.pop("domain", None)
_v = domain if domain is not None else _v
if _v is not None:
self["domain"] = _v
_v = arg.pop("hoverinfo", None)
_v = hoverinfo if hoverinfo is not None else _v
if _v is not None:
self["hoverinfo"] = _v
_v = arg.pop("hoverlabel", None)
_v = hoverlabel if hoverlabel is not None else _v
if _v is not None:
self["hoverlabel"] = _v
_v = arg.pop("ids", None)
_v = ids if ids is not None else _v
if _v is not None:
self["ids"] = _v
_v = arg.pop("idssrc", None)
_v = idssrc if idssrc is not None else _v
if _v is not None:
self["idssrc"] = _v
_v = arg.pop("legend", None)
_v = legend if legend is not None else _v
if _v is not None:
self["legend"] = _v
_v = arg.pop("legendgrouptitle", None)
_v = legendgrouptitle if legendgrouptitle is not None else _v
if _v is not None:
self["legendgrouptitle"] = _v
_v = arg.pop("legendrank", None)
_v = legendrank if legendrank is not None else _v
if _v is not None:
self["legendrank"] = _v
_v = arg.pop("legendwidth", None)
_v = legendwidth if legendwidth is not None else _v
if _v is not None:
self["legendwidth"] = _v
_v = arg.pop("link", None)
_v = link if link is not None else _v
if _v is not None:
self["link"] = _v
_v = arg.pop("meta", None)
_v = meta if meta is not None else _v
if _v is not None:
self["meta"] = _v
_v = arg.pop("metasrc", None)
_v = metasrc if metasrc is not None else _v
if _v is not None:
self["metasrc"] = _v
_v = arg.pop("name", None)
_v = name if name is not None else _v
if _v is not None:
self["name"] = _v
_v = arg.pop("node", None)
_v = node if node is not None else _v
if _v is not None:
self["node"] = _v
_v = arg.pop("orientation", None)
_v = orientation if orientation is not None else _v
if _v is not None:
self["orientation"] = _v
_v = arg.pop("selectedpoints", None)
_v = selectedpoints if selectedpoints is not None else _v
if _v is not None:
self["selectedpoints"] = _v
_v = arg.pop("stream", None)
_v = stream if stream is not None else _v
if _v is not None:
self["stream"] = _v
_v = arg.pop("textfont", None)
_v = textfont if textfont is not None else _v
if _v is not None:
self["textfont"] = _v
_v = arg.pop("uid", None)
_v = uid if uid is not None else _v
if _v is not None:
self["uid"] = _v
_v = arg.pop("uirevision", None)
_v = uirevision if uirevision is not None else _v
if _v is not None:
self["uirevision"] = _v
_v = arg.pop("valueformat", None)
_v = valueformat if valueformat is not None else _v
if _v is not None:
self["valueformat"] = _v
_v = arg.pop("valuesuffix", None)
_v = valuesuffix if valuesuffix is not None else _v
if _v is not None:
self["valuesuffix"] = _v
_v = arg.pop("visible", None)
_v = visible if visible is not None else _v
if _v is not None:
self["visible"] = _v
# Read-only literals
# ------------------
self._props["type"] = "sankey"
arg.pop("type", None)
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| _sankey.Sankey.__init__ |
plotly.py | 40 | packages/python/plotly/plotly/graph_objs/_scatter.py | def error_x(self):
"""
The 'error_x' property is an instance of ErrorX
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter.ErrorX`
- A dict of string/value properties that will be passed
to the ErrorX constructor
Supported dict properties:
array
Sets the data corresponding the length of each
error bar. Values are plotted relative to the
underlying data.
arrayminus
Sets the data corresponding the length of each
error bar in the bottom (left) direction for
vertical (horizontal) bars Values are plotted
relative to the underlying data.
arrayminussrc
Sets the source reference on Chart Studio Cloud
for `arrayminus`.
arraysrc
Sets the source reference on Chart Studio Cloud
for `array`.
color
Sets the stoke color of the error bars.
copy_ystyle
symmetric
Determines whether or not the error bars have
the same length in both direction (top/bottom
for vertical bars, left/right for horizontal
bars.
thickness
Sets the thickness (in px) of the error bars.
traceref
tracerefminus
type
Determines the rule used to generate the error
bars. If *constant`, the bar lengths are of a
constant value. Set this constant in `value`.
If "percent", the bar lengths correspond to a
percentage of underlying data. Set this
percentage in `value`. If "sqrt", the bar
lengths correspond to the square of the
underlying data. If "data", the bar lengths are
set with data set `array`.
value
Sets the value of either the percentage (if
`type` is set to "percent") or the constant (if
`type` is set to "constant") corresponding to
the lengths of the error bars.
valueminus
Sets the value of either the percentage (if
`type` is set to "percent") or the constant (if
`type` is set to "constant") corresponding to
the lengths of the error bars in the bottom
(left) direction for vertical (horizontal) bars
visible
Determines whether or not this set of error
bars is visible.
width
Sets the width (in px) of the cross-bar at both
ends of the error bars.
Returns
-------
plotly.graph_objs.scatter.ErrorX
"""
| /usr/src/app/target_test_cases/failed_tests__scatter.error_x.txt | def error_x(self):
"""
The 'error_x' property is an instance of ErrorX
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter.ErrorX`
- A dict of string/value properties that will be passed
to the ErrorX constructor
Supported dict properties:
array
Sets the data corresponding the length of each
error bar. Values are plotted relative to the
underlying data.
arrayminus
Sets the data corresponding the length of each
error bar in the bottom (left) direction for
vertical (horizontal) bars Values are plotted
relative to the underlying data.
arrayminussrc
Sets the source reference on Chart Studio Cloud
for `arrayminus`.
arraysrc
Sets the source reference on Chart Studio Cloud
for `array`.
color
Sets the stoke color of the error bars.
copy_ystyle
symmetric
Determines whether or not the error bars have
the same length in both direction (top/bottom
for vertical bars, left/right for horizontal
bars.
thickness
Sets the thickness (in px) of the error bars.
traceref
tracerefminus
type
Determines the rule used to generate the error
bars. If *constant`, the bar lengths are of a
constant value. Set this constant in `value`.
If "percent", the bar lengths correspond to a
percentage of underlying data. Set this
percentage in `value`. If "sqrt", the bar
lengths correspond to the square of the
underlying data. If "data", the bar lengths are
set with data set `array`.
value
Sets the value of either the percentage (if
`type` is set to "percent") or the constant (if
`type` is set to "constant") corresponding to
the lengths of the error bars.
valueminus
Sets the value of either the percentage (if
`type` is set to "percent") or the constant (if
`type` is set to "constant") corresponding to
the lengths of the error bars in the bottom
(left) direction for vertical (horizontal) bars
visible
Determines whether or not this set of error
bars is visible.
width
Sets the width (in px) of the cross-bar at both
ends of the error bars.
Returns
-------
plotly.graph_objs.scatter.ErrorX
"""
return self["error_x"]
| _scatter.error_x |
plotly.py | 41 | packages/python/plotly/plotly/graph_objs/_scatter.py | def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Supported dict properties:
angle
Sets the marker angle in respect to `angleref`.
angleref
Sets the reference for marker angle. With
"previous", angle 0 points along the line from
the previous point to this one. With "up",
angle 0 points toward the top of the screen.
anglesrc
Sets the source reference on Chart Studio Cloud
for `angle`.
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.colorscale`. Has an
effect only if in `marker.color` is set to a
numerical array. In case `colorscale` is
unspecified or `autocolorscale` is true, the
default palette will be chosen according to
whether numbers in the `color` array are all
positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `marker.color`) or the bounds set in
`marker.cmin` and `marker.cmax` Has an effect
only if in `marker.color` is set to a numerical
array. Defaults to `false` when `marker.cmin`
and `marker.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `marker.cmin` and/or `marker.cmax` to
be equidistant to this point. Has an effect
only if in `marker.color` is set to a numerical
array. Value should have the same units as in
`marker.color`. Has no effect when
`marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmax` must be set as well.
color
Sets the marker color. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`marker.cmin` and `marker.cmax` if set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.scatter.marker.Col
orBar` instance or dict with compatible
properties
colorscale
Sets the colorscale. Has an effect only if in
`marker.color` is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `marker.cmin` and
`marker.cmax`. Alternatively, `colorscale` may
be a palette name string of the following list:
Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud
for `color`.
gradient
:class:`plotly.graph_objects.scatter.marker.Gra
dient` instance or dict with compatible
properties
line
:class:`plotly.graph_objects.scatter.marker.Lin
e` instance or dict with compatible properties
maxdisplayed
Sets a maximum number of points to be drawn on
the graph. 0 corresponds to no limit.
opacity
Sets the marker opacity.
opacitysrc
Sets the source reference on Chart Studio Cloud
for `opacity`.
reversescale
Reverses the color mapping if true. Has an
effect only if in `marker.color` is set to a
numerical array. If true, `marker.cmin` will
correspond to the last color in the array and
`marker.cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
in `marker.color` is set to a numerical array.
size
Sets the marker size (in px).
sizemin
Has an effect only if `marker.size` is set to a
numerical array. Sets the minimum size (in px)
of the rendered marker points.
sizemode
Has an effect only if `marker.size` is set to a
numerical array. Sets the rule for which the
data in `size` is converted to pixels.
sizeref
Has an effect only if `marker.size` is set to a
numerical array. Sets the scale factor used to
determine the rendered size of marker points.
Use with `sizemin` and `sizemode`.
sizesrc
Sets the source reference on Chart Studio Cloud
for `size`.
standoff
Moves the marker away from the data point in
the direction of `angle` (in px). This can be
useful for example if you have another marker
at this location and you want to point an
arrowhead marker at it.
standoffsrc
Sets the source reference on Chart Studio Cloud
for `standoff`.
symbol
Sets the marker symbol type. Adding 100 is
equivalent to appending "-open" to a symbol
name. Adding 200 is equivalent to appending
"-dot" to a symbol name. Adding 300 is
equivalent to appending "-open-dot" or "dot-
open" to a symbol name.
symbolsrc
Sets the source reference on Chart Studio Cloud
for `symbol`.
Returns
-------
plotly.graph_objs.scatter.Marker
"""
| /usr/src/app/target_test_cases/failed_tests__scatter.marker.txt | def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Supported dict properties:
angle
Sets the marker angle in respect to `angleref`.
angleref
Sets the reference for marker angle. With
"previous", angle 0 points along the line from
the previous point to this one. With "up",
angle 0 points toward the top of the screen.
anglesrc
Sets the source reference on Chart Studio Cloud
for `angle`.
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.colorscale`. Has an
effect only if in `marker.color` is set to a
numerical array. In case `colorscale` is
unspecified or `autocolorscale` is true, the
default palette will be chosen according to
whether numbers in the `color` array are all
positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `marker.color`) or the bounds set in
`marker.cmin` and `marker.cmax` Has an effect
only if in `marker.color` is set to a numerical
array. Defaults to `false` when `marker.cmin`
and `marker.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `marker.cmin` and/or `marker.cmax` to
be equidistant to this point. Has an effect
only if in `marker.color` is set to a numerical
array. Value should have the same units as in
`marker.color`. Has no effect when
`marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmax` must be set as well.
color
Sets the marker color. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`marker.cmin` and `marker.cmax` if set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.scatter.marker.Col
orBar` instance or dict with compatible
properties
colorscale
Sets the colorscale. Has an effect only if in
`marker.color` is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `marker.cmin` and
`marker.cmax`. Alternatively, `colorscale` may
be a palette name string of the following list:
Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud
for `color`.
gradient
:class:`plotly.graph_objects.scatter.marker.Gra
dient` instance or dict with compatible
properties
line
:class:`plotly.graph_objects.scatter.marker.Lin
e` instance or dict with compatible properties
maxdisplayed
Sets a maximum number of points to be drawn on
the graph. 0 corresponds to no limit.
opacity
Sets the marker opacity.
opacitysrc
Sets the source reference on Chart Studio Cloud
for `opacity`.
reversescale
Reverses the color mapping if true. Has an
effect only if in `marker.color` is set to a
numerical array. If true, `marker.cmin` will
correspond to the last color in the array and
`marker.cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
in `marker.color` is set to a numerical array.
size
Sets the marker size (in px).
sizemin
Has an effect only if `marker.size` is set to a
numerical array. Sets the minimum size (in px)
of the rendered marker points.
sizemode
Has an effect only if `marker.size` is set to a
numerical array. Sets the rule for which the
data in `size` is converted to pixels.
sizeref
Has an effect only if `marker.size` is set to a
numerical array. Sets the scale factor used to
determine the rendered size of marker points.
Use with `sizemin` and `sizemode`.
sizesrc
Sets the source reference on Chart Studio Cloud
for `size`.
standoff
Moves the marker away from the data point in
the direction of `angle` (in px). This can be
useful for example if you have another marker
at this location and you want to point an
arrowhead marker at it.
standoffsrc
Sets the source reference on Chart Studio Cloud
for `standoff`.
symbol
Sets the marker symbol type. Adding 100 is
equivalent to appending "-open" to a symbol
name. Adding 200 is equivalent to appending
"-dot" to a symbol name. Adding 300 is
equivalent to appending "-open-dot" or "dot-
open" to a symbol name.
symbolsrc
Sets the source reference on Chart Studio Cloud
for `symbol`.
Returns
-------
plotly.graph_objs.scatter.Marker
"""
return self["marker"]
| _scatter.marker |
plotly.py | 42 | packages/python/plotly/plotly/graph_objs/_scatter.py | def textfont(self):
"""
Sets the text font.
The 'textfont' property is an instance of Textfont
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter.Textfont`
- A dict of string/value properties that will be passed
to the Textfont constructor
Supported dict properties:
color
colorsrc
Sets the source reference on Chart Studio Cloud
for `color`.
family
HTML font family - the typeface that will be
applied by the web browser. The web browser
will only be able to apply a font if it is
available on the system which it operates.
Provide multiple font families, separated by
commas, to indicate the preference in which to
apply fonts if they aren't available on the
system. The Chart Studio Cloud (at
https://chart-studio.plotly.com or on-premise)
generates images on a server, where only a
select number of fonts are installed and
supported. These include "Arial", "Balto",
"Courier New", "Droid Sans", "Droid Serif",
"Droid Sans Mono", "Gravitas One", "Old
Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
familysrc
Sets the source reference on Chart Studio Cloud
for `family`.
lineposition
Sets the kind of decoration line(s) with text,
such as an "under", "over" or "through" as well
as combinations e.g. "under+over", etc.
linepositionsrc
Sets the source reference on Chart Studio Cloud
for `lineposition`.
shadow
Sets the shape and color of the shadow behind
text. "auto" places minimal shadow and applies
contrast text font color. See
https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional
options.
shadowsrc
Sets the source reference on Chart Studio Cloud
for `shadow`.
size
sizesrc
Sets the source reference on Chart Studio Cloud
for `size`.
style
Sets whether a font should be styled with a
normal or italic face from its family.
stylesrc
Sets the source reference on Chart Studio Cloud
for `style`.
textcase
Sets capitalization of text. It can be used to
make text appear in all-uppercase or all-
lowercase, or with each word capitalized.
textcasesrc
Sets the source reference on Chart Studio Cloud
for `textcase`.
variant
Sets the variant of the font.
variantsrc
Sets the source reference on Chart Studio Cloud
for `variant`.
weight
Sets the weight (or boldness) of the font.
weightsrc
Sets the source reference on Chart Studio Cloud
for `weight`.
Returns
-------
plotly.graph_objs.scatter.Textfont
"""
| /usr/src/app/target_test_cases/failed_tests__scatter.textfont.txt | def textfont(self):
"""
Sets the text font.
The 'textfont' property is an instance of Textfont
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter.Textfont`
- A dict of string/value properties that will be passed
to the Textfont constructor
Supported dict properties:
color
colorsrc
Sets the source reference on Chart Studio Cloud
for `color`.
family
HTML font family - the typeface that will be
applied by the web browser. The web browser
will only be able to apply a font if it is
available on the system which it operates.
Provide multiple font families, separated by
commas, to indicate the preference in which to
apply fonts if they aren't available on the
system. The Chart Studio Cloud (at
https://chart-studio.plotly.com or on-premise)
generates images on a server, where only a
select number of fonts are installed and
supported. These include "Arial", "Balto",
"Courier New", "Droid Sans", "Droid Serif",
"Droid Sans Mono", "Gravitas One", "Old
Standard TT", "Open Sans", "Overpass", "PT Sans
Narrow", "Raleway", "Times New Roman".
familysrc
Sets the source reference on Chart Studio Cloud
for `family`.
lineposition
Sets the kind of decoration line(s) with text,
such as an "under", "over" or "through" as well
as combinations e.g. "under+over", etc.
linepositionsrc
Sets the source reference on Chart Studio Cloud
for `lineposition`.
shadow
Sets the shape and color of the shadow behind
text. "auto" places minimal shadow and applies
contrast text font color. See
https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional
options.
shadowsrc
Sets the source reference on Chart Studio Cloud
for `shadow`.
size
sizesrc
Sets the source reference on Chart Studio Cloud
for `size`.
style
Sets whether a font should be styled with a
normal or italic face from its family.
stylesrc
Sets the source reference on Chart Studio Cloud
for `style`.
textcase
Sets capitalization of text. It can be used to
make text appear in all-uppercase or all-
lowercase, or with each word capitalized.
textcasesrc
Sets the source reference on Chart Studio Cloud
for `textcase`.
variant
Sets the variant of the font.
variantsrc
Sets the source reference on Chart Studio Cloud
for `variant`.
weight
Sets the weight (or boldness) of the font.
weightsrc
Sets the source reference on Chart Studio Cloud
for `weight`.
Returns
-------
plotly.graph_objs.scatter.Textfont
"""
return self["textfont"]
| _scatter.textfont |
plotly.py | 43 | packages/python/plotly/plotly/graph_objs/_scatter3d.py | def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter3d.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Supported dict properties:
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.colorscale`. Has an
effect only if in `marker.color` is set to a
numerical array. In case `colorscale` is
unspecified or `autocolorscale` is true, the
default palette will be chosen according to
whether numbers in the `color` array are all
positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `marker.color`) or the bounds set in
`marker.cmin` and `marker.cmax` Has an effect
only if in `marker.color` is set to a numerical
array. Defaults to `false` when `marker.cmin`
and `marker.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `marker.cmin` and/or `marker.cmax` to
be equidistant to this point. Has an effect
only if in `marker.color` is set to a numerical
array. Value should have the same units as in
`marker.color`. Has no effect when
`marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmax` must be set as well.
color
Sets the marker color. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`marker.cmin` and `marker.cmax` if set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.scatter3d.marker.C
olorBar` instance or dict with compatible
properties
colorscale
Sets the colorscale. Has an effect only if in
`marker.color` is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `marker.cmin` and
`marker.cmax`. Alternatively, `colorscale` may
be a palette name string of the following list:
Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud
for `color`.
line
:class:`plotly.graph_objects.scatter3d.marker.L
ine` instance or dict with compatible
properties
opacity
Sets the marker opacity. Note that the marker
opacity for scatter3d traces must be a scalar
value for performance reasons. To set a
blending opacity value (i.e. which is not
transparent), set "marker.color" to an rgba
color and use its alpha channel.
reversescale
Reverses the color mapping if true. Has an
effect only if in `marker.color` is set to a
numerical array. If true, `marker.cmin` will
correspond to the last color in the array and
`marker.cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
in `marker.color` is set to a numerical array.
size
Sets the marker size (in px).
sizemin
Has an effect only if `marker.size` is set to a
numerical array. Sets the minimum size (in px)
of the rendered marker points.
sizemode
Has an effect only if `marker.size` is set to a
numerical array. Sets the rule for which the
data in `size` is converted to pixels.
sizeref
Has an effect only if `marker.size` is set to a
numerical array. Sets the scale factor used to
determine the rendered size of marker points.
Use with `sizemin` and `sizemode`.
sizesrc
Sets the source reference on Chart Studio Cloud
for `size`.
symbol
Sets the marker symbol type.
symbolsrc
Sets the source reference on Chart Studio Cloud
for `symbol`.
Returns
-------
plotly.graph_objs.scatter3d.Marker
"""
| /usr/src/app/target_test_cases/failed_tests__scatter3d.marker.txt | def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatter3d.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Supported dict properties:
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.colorscale`. Has an
effect only if in `marker.color` is set to a
numerical array. In case `colorscale` is
unspecified or `autocolorscale` is true, the
default palette will be chosen according to
whether numbers in the `color` array are all
positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `marker.color`) or the bounds set in
`marker.cmin` and `marker.cmax` Has an effect
only if in `marker.color` is set to a numerical
array. Defaults to `false` when `marker.cmin`
and `marker.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `marker.cmin` and/or `marker.cmax` to
be equidistant to this point. Has an effect
only if in `marker.color` is set to a numerical
array. Value should have the same units as in
`marker.color`. Has no effect when
`marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmax` must be set as well.
color
Sets the marker color. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`marker.cmin` and `marker.cmax` if set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.scatter3d.marker.C
olorBar` instance or dict with compatible
properties
colorscale
Sets the colorscale. Has an effect only if in
`marker.color` is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `marker.cmin` and
`marker.cmax`. Alternatively, `colorscale` may
be a palette name string of the following list:
Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud
for `color`.
line
:class:`plotly.graph_objects.scatter3d.marker.L
ine` instance or dict with compatible
properties
opacity
Sets the marker opacity. Note that the marker
opacity for scatter3d traces must be a scalar
value for performance reasons. To set a
blending opacity value (i.e. which is not
transparent), set "marker.color" to an rgba
color and use its alpha channel.
reversescale
Reverses the color mapping if true. Has an
effect only if in `marker.color` is set to a
numerical array. If true, `marker.cmin` will
correspond to the last color in the array and
`marker.cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
in `marker.color` is set to a numerical array.
size
Sets the marker size (in px).
sizemin
Has an effect only if `marker.size` is set to a
numerical array. Sets the minimum size (in px)
of the rendered marker points.
sizemode
Has an effect only if `marker.size` is set to a
numerical array. Sets the rule for which the
data in `size` is converted to pixels.
sizeref
Has an effect only if `marker.size` is set to a
numerical array. Sets the scale factor used to
determine the rendered size of marker points.
Use with `sizemin` and `sizemode`.
sizesrc
Sets the source reference on Chart Studio Cloud
for `size`.
symbol
Sets the marker symbol type.
symbolsrc
Sets the source reference on Chart Studio Cloud
for `symbol`.
Returns
-------
plotly.graph_objs.scatter3d.Marker
"""
return self["marker"]
| _scatter3d.marker |
plotly.py | 44 | packages/python/plotly/plotly/graph_objs/_scattergl.py | def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.scattergl.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Supported dict properties:
angle
Sets the marker angle in respect to `angleref`.
anglesrc
Sets the source reference on Chart Studio Cloud
for `angle`.
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.colorscale`. Has an
effect only if in `marker.color` is set to a
numerical array. In case `colorscale` is
unspecified or `autocolorscale` is true, the
default palette will be chosen according to
whether numbers in the `color` array are all
positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `marker.color`) or the bounds set in
`marker.cmin` and `marker.cmax` Has an effect
only if in `marker.color` is set to a numerical
array. Defaults to `false` when `marker.cmin`
and `marker.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `marker.cmin` and/or `marker.cmax` to
be equidistant to this point. Has an effect
only if in `marker.color` is set to a numerical
array. Value should have the same units as in
`marker.color`. Has no effect when
`marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmax` must be set as well.
color
Sets the marker color. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`marker.cmin` and `marker.cmax` if set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.scattergl.marker.C
olorBar` instance or dict with compatible
properties
colorscale
Sets the colorscale. Has an effect only if in
`marker.color` is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `marker.cmin` and
`marker.cmax`. Alternatively, `colorscale` may
be a palette name string of the following list:
Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud
for `color`.
line
:class:`plotly.graph_objects.scattergl.marker.L
ine` instance or dict with compatible
properties
opacity
Sets the marker opacity.
opacitysrc
Sets the source reference on Chart Studio Cloud
for `opacity`.
reversescale
Reverses the color mapping if true. Has an
effect only if in `marker.color` is set to a
numerical array. If true, `marker.cmin` will
correspond to the last color in the array and
`marker.cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
in `marker.color` is set to a numerical array.
size
Sets the marker size (in px).
sizemin
Has an effect only if `marker.size` is set to a
numerical array. Sets the minimum size (in px)
of the rendered marker points.
sizemode
Has an effect only if `marker.size` is set to a
numerical array. Sets the rule for which the
data in `size` is converted to pixels.
sizeref
Has an effect only if `marker.size` is set to a
numerical array. Sets the scale factor used to
determine the rendered size of marker points.
Use with `sizemin` and `sizemode`.
sizesrc
Sets the source reference on Chart Studio Cloud
for `size`.
symbol
Sets the marker symbol type. Adding 100 is
equivalent to appending "-open" to a symbol
name. Adding 200 is equivalent to appending
"-dot" to a symbol name. Adding 300 is
equivalent to appending "-open-dot" or "dot-
open" to a symbol name.
symbolsrc
Sets the source reference on Chart Studio Cloud
for `symbol`.
Returns
-------
plotly.graph_objs.scattergl.Marker
"""
| /usr/src/app/target_test_cases/failed_tests__scattergl.marker.txt | def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.scattergl.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Supported dict properties:
angle
Sets the marker angle in respect to `angleref`.
anglesrc
Sets the source reference on Chart Studio Cloud
for `angle`.
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.colorscale`. Has an
effect only if in `marker.color` is set to a
numerical array. In case `colorscale` is
unspecified or `autocolorscale` is true, the
default palette will be chosen according to
whether numbers in the `color` array are all
positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `marker.color`) or the bounds set in
`marker.cmin` and `marker.cmax` Has an effect
only if in `marker.color` is set to a numerical
array. Defaults to `false` when `marker.cmin`
and `marker.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `marker.cmin` and/or `marker.cmax` to
be equidistant to this point. Has an effect
only if in `marker.color` is set to a numerical
array. Value should have the same units as in
`marker.color`. Has no effect when
`marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmax` must be set as well.
color
Sets the marker color. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`marker.cmin` and `marker.cmax` if set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.scattergl.marker.C
olorBar` instance or dict with compatible
properties
colorscale
Sets the colorscale. Has an effect only if in
`marker.color` is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `marker.cmin` and
`marker.cmax`. Alternatively, `colorscale` may
be a palette name string of the following list:
Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud
for `color`.
line
:class:`plotly.graph_objects.scattergl.marker.L
ine` instance or dict with compatible
properties
opacity
Sets the marker opacity.
opacitysrc
Sets the source reference on Chart Studio Cloud
for `opacity`.
reversescale
Reverses the color mapping if true. Has an
effect only if in `marker.color` is set to a
numerical array. If true, `marker.cmin` will
correspond to the last color in the array and
`marker.cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
in `marker.color` is set to a numerical array.
size
Sets the marker size (in px).
sizemin
Has an effect only if `marker.size` is set to a
numerical array. Sets the minimum size (in px)
of the rendered marker points.
sizemode
Has an effect only if `marker.size` is set to a
numerical array. Sets the rule for which the
data in `size` is converted to pixels.
sizeref
Has an effect only if `marker.size` is set to a
numerical array. Sets the scale factor used to
determine the rendered size of marker points.
Use with `sizemin` and `sizemode`.
sizesrc
Sets the source reference on Chart Studio Cloud
for `size`.
symbol
Sets the marker symbol type. Adding 100 is
equivalent to appending "-open" to a symbol
name. Adding 200 is equivalent to appending
"-dot" to a symbol name. Adding 300 is
equivalent to appending "-open-dot" or "dot-
open" to a symbol name.
symbolsrc
Sets the source reference on Chart Studio Cloud
for `symbol`.
Returns
-------
plotly.graph_objs.scattergl.Marker
"""
return self["marker"]
| _scattergl.marker |
plotly.py | 45 | packages/python/plotly/plotly/figure_factory/_scatterplot.py | def create_scatterplotmatrix(
df,
index=None,
endpts=None,
diag="scatter",
height=500,
width=500,
size=6,
title="Scatterplot Matrix",
colormap=None,
colormap_type="cat",
dataframe=None,
headers=None,
index_vals=None,
**kwargs,
):
"""
Returns data for a scatterplot matrix;
**deprecated**,
use instead the plotly.graph_objects trace
:class:`plotly.graph_objects.Splom`.
:param (array) df: array of the data with column headers
:param (str) index: name of the index column in data array
:param (list|tuple) endpts: takes an increasing sequece of numbers
that defines intervals on the real line. They are used to group
the entries in an index of numbers into their corresponding
interval and therefore can be treated as categorical data
:param (str) diag: sets the chart type for the main diagonal plots.
The options are 'scatter', 'histogram' and 'box'.
:param (int|float) height: sets the height of the chart
:param (int|float) width: sets the width of the chart
:param (float) size: sets the marker size (in px)
:param (str) title: the title label of the scatterplot matrix
:param (str|tuple|list|dict) colormap: either a plotly scale name,
an rgb or hex color, a color tuple, a list of colors or a
dictionary. An rgb color is of the form 'rgb(x, y, z)' where
x, y and z belong to the interval [0, 255] and a color tuple is a
tuple of the form (a, b, c) where a, b and c belong to [0, 1].
If colormap is a list, it must contain valid color types as its
members.
If colormap is a dictionary, all the string entries in
the index column must be a key in colormap. In this case, the
colormap_type is forced to 'cat' or categorical
:param (str) colormap_type: determines how colormap is interpreted.
Valid choices are 'seq' (sequential) and 'cat' (categorical). If
'seq' is selected, only the first two colors in colormap will be
considered (when colormap is a list) and the index values will be
linearly interpolated between those two colors. This option is
forced if all index values are numeric.
If 'cat' is selected, a color from colormap will be assigned to
each category from index, including the intervals if endpts is
being used
:param (dict) **kwargs: a dictionary of scatterplot arguments
The only forbidden parameters are 'size', 'color' and
'colorscale' in 'marker'
Example 1: Vanilla Scatterplot Matrix
>>> from plotly.graph_objs import graph_objs
>>> from plotly.figure_factory import create_scatterplotmatrix
>>> import numpy as np
>>> import pandas as pd
>>> # Create dataframe
>>> df = pd.DataFrame(np.random.randn(10, 2),
... columns=['Column 1', 'Column 2'])
>>> # Create scatterplot matrix
>>> fig = create_scatterplotmatrix(df)
>>> fig.show()
Example 2: Indexing a Column
>>> from plotly.graph_objs import graph_objs
>>> from plotly.figure_factory import create_scatterplotmatrix
>>> import numpy as np
>>> import pandas as pd
>>> # Create dataframe with index
>>> df = pd.DataFrame(np.random.randn(10, 2),
... columns=['A', 'B'])
>>> # Add another column of strings to the dataframe
>>> df['Fruit'] = pd.Series(['apple', 'apple', 'grape', 'apple', 'apple',
... 'grape', 'pear', 'pear', 'apple', 'pear'])
>>> # Create scatterplot matrix
>>> fig = create_scatterplotmatrix(df, index='Fruit', size=10)
>>> fig.show()
Example 3: Styling the Diagonal Subplots
>>> from plotly.graph_objs import graph_objs
>>> from plotly.figure_factory import create_scatterplotmatrix
>>> import numpy as np
>>> import pandas as pd
>>> # Create dataframe with index
>>> df = pd.DataFrame(np.random.randn(10, 4),
... columns=['A', 'B', 'C', 'D'])
>>> # Add another column of strings to the dataframe
>>> df['Fruit'] = pd.Series(['apple', 'apple', 'grape', 'apple', 'apple',
... 'grape', 'pear', 'pear', 'apple', 'pear'])
>>> # Create scatterplot matrix
>>> fig = create_scatterplotmatrix(df, diag='box', index='Fruit', height=1000,
... width=1000)
>>> fig.show()
Example 4: Use a Theme to Style the Subplots
>>> from plotly.graph_objs import graph_objs
>>> from plotly.figure_factory import create_scatterplotmatrix
>>> import numpy as np
>>> import pandas as pd
>>> # Create dataframe with random data
>>> df = pd.DataFrame(np.random.randn(100, 3),
... columns=['A', 'B', 'C'])
>>> # Create scatterplot matrix using a built-in
>>> # Plotly palette scale and indexing column 'A'
>>> fig = create_scatterplotmatrix(df, diag='histogram', index='A',
... colormap='Blues', height=800, width=800)
>>> fig.show()
Example 5: Example 4 with Interval Factoring
>>> from plotly.graph_objs import graph_objs
>>> from plotly.figure_factory import create_scatterplotmatrix
>>> import numpy as np
>>> import pandas as pd
>>> # Create dataframe with random data
>>> df = pd.DataFrame(np.random.randn(100, 3),
... columns=['A', 'B', 'C'])
>>> # Create scatterplot matrix using a list of 2 rgb tuples
>>> # and endpoints at -1, 0 and 1
>>> fig = create_scatterplotmatrix(df, diag='histogram', index='A',
... colormap=['rgb(140, 255, 50)',
... 'rgb(170, 60, 115)', '#6c4774',
... (0.5, 0.1, 0.8)],
... endpts=[-1, 0, 1], height=800, width=800)
>>> fig.show()
Example 6: Using the colormap as a Dictionary
>>> from plotly.graph_objs import graph_objs
>>> from plotly.figure_factory import create_scatterplotmatrix
>>> import numpy as np
>>> import pandas as pd
>>> import random
>>> # Create dataframe with random data
>>> df = pd.DataFrame(np.random.randn(100, 3),
... columns=['Column A',
... 'Column B',
... 'Column C'])
>>> # Add new color column to dataframe
>>> new_column = []
>>> strange_colors = ['turquoise', 'limegreen', 'goldenrod']
>>> for j in range(100):
... new_column.append(random.choice(strange_colors))
>>> df['Colors'] = pd.Series(new_column, index=df.index)
>>> # Create scatterplot matrix using a dictionary of hex color values
>>> # which correspond to actual color names in 'Colors' column
>>> fig = create_scatterplotmatrix(
... df, diag='box', index='Colors',
... colormap= dict(
... turquoise = '#00F5FF',
... limegreen = '#32CD32',
... goldenrod = '#DAA520'
... ),
... colormap_type='cat',
... height=800, width=800
... )
>>> fig.show()
"""
| /usr/src/app/target_test_cases/failed_tests__scatterplot.create_scatterplotmatrix.txt | def create_scatterplotmatrix(
df,
index=None,
endpts=None,
diag="scatter",
height=500,
width=500,
size=6,
title="Scatterplot Matrix",
colormap=None,
colormap_type="cat",
dataframe=None,
headers=None,
index_vals=None,
**kwargs,
):
"""
Returns data for a scatterplot matrix;
**deprecated**,
use instead the plotly.graph_objects trace
:class:`plotly.graph_objects.Splom`.
:param (array) df: array of the data with column headers
:param (str) index: name of the index column in data array
:param (list|tuple) endpts: takes an increasing sequece of numbers
that defines intervals on the real line. They are used to group
the entries in an index of numbers into their corresponding
interval and therefore can be treated as categorical data
:param (str) diag: sets the chart type for the main diagonal plots.
The options are 'scatter', 'histogram' and 'box'.
:param (int|float) height: sets the height of the chart
:param (int|float) width: sets the width of the chart
:param (float) size: sets the marker size (in px)
:param (str) title: the title label of the scatterplot matrix
:param (str|tuple|list|dict) colormap: either a plotly scale name,
an rgb or hex color, a color tuple, a list of colors or a
dictionary. An rgb color is of the form 'rgb(x, y, z)' where
x, y and z belong to the interval [0, 255] and a color tuple is a
tuple of the form (a, b, c) where a, b and c belong to [0, 1].
If colormap is a list, it must contain valid color types as its
members.
If colormap is a dictionary, all the string entries in
the index column must be a key in colormap. In this case, the
colormap_type is forced to 'cat' or categorical
:param (str) colormap_type: determines how colormap is interpreted.
Valid choices are 'seq' (sequential) and 'cat' (categorical). If
'seq' is selected, only the first two colors in colormap will be
considered (when colormap is a list) and the index values will be
linearly interpolated between those two colors. This option is
forced if all index values are numeric.
If 'cat' is selected, a color from colormap will be assigned to
each category from index, including the intervals if endpts is
being used
:param (dict) **kwargs: a dictionary of scatterplot arguments
The only forbidden parameters are 'size', 'color' and
'colorscale' in 'marker'
Example 1: Vanilla Scatterplot Matrix
>>> from plotly.graph_objs import graph_objs
>>> from plotly.figure_factory import create_scatterplotmatrix
>>> import numpy as np
>>> import pandas as pd
>>> # Create dataframe
>>> df = pd.DataFrame(np.random.randn(10, 2),
... columns=['Column 1', 'Column 2'])
>>> # Create scatterplot matrix
>>> fig = create_scatterplotmatrix(df)
>>> fig.show()
Example 2: Indexing a Column
>>> from plotly.graph_objs import graph_objs
>>> from plotly.figure_factory import create_scatterplotmatrix
>>> import numpy as np
>>> import pandas as pd
>>> # Create dataframe with index
>>> df = pd.DataFrame(np.random.randn(10, 2),
... columns=['A', 'B'])
>>> # Add another column of strings to the dataframe
>>> df['Fruit'] = pd.Series(['apple', 'apple', 'grape', 'apple', 'apple',
... 'grape', 'pear', 'pear', 'apple', 'pear'])
>>> # Create scatterplot matrix
>>> fig = create_scatterplotmatrix(df, index='Fruit', size=10)
>>> fig.show()
Example 3: Styling the Diagonal Subplots
>>> from plotly.graph_objs import graph_objs
>>> from plotly.figure_factory import create_scatterplotmatrix
>>> import numpy as np
>>> import pandas as pd
>>> # Create dataframe with index
>>> df = pd.DataFrame(np.random.randn(10, 4),
... columns=['A', 'B', 'C', 'D'])
>>> # Add another column of strings to the dataframe
>>> df['Fruit'] = pd.Series(['apple', 'apple', 'grape', 'apple', 'apple',
... 'grape', 'pear', 'pear', 'apple', 'pear'])
>>> # Create scatterplot matrix
>>> fig = create_scatterplotmatrix(df, diag='box', index='Fruit', height=1000,
... width=1000)
>>> fig.show()
Example 4: Use a Theme to Style the Subplots
>>> from plotly.graph_objs import graph_objs
>>> from plotly.figure_factory import create_scatterplotmatrix
>>> import numpy as np
>>> import pandas as pd
>>> # Create dataframe with random data
>>> df = pd.DataFrame(np.random.randn(100, 3),
... columns=['A', 'B', 'C'])
>>> # Create scatterplot matrix using a built-in
>>> # Plotly palette scale and indexing column 'A'
>>> fig = create_scatterplotmatrix(df, diag='histogram', index='A',
... colormap='Blues', height=800, width=800)
>>> fig.show()
Example 5: Example 4 with Interval Factoring
>>> from plotly.graph_objs import graph_objs
>>> from plotly.figure_factory import create_scatterplotmatrix
>>> import numpy as np
>>> import pandas as pd
>>> # Create dataframe with random data
>>> df = pd.DataFrame(np.random.randn(100, 3),
... columns=['A', 'B', 'C'])
>>> # Create scatterplot matrix using a list of 2 rgb tuples
>>> # and endpoints at -1, 0 and 1
>>> fig = create_scatterplotmatrix(df, diag='histogram', index='A',
... colormap=['rgb(140, 255, 50)',
... 'rgb(170, 60, 115)', '#6c4774',
... (0.5, 0.1, 0.8)],
... endpts=[-1, 0, 1], height=800, width=800)
>>> fig.show()
Example 6: Using the colormap as a Dictionary
>>> from plotly.graph_objs import graph_objs
>>> from plotly.figure_factory import create_scatterplotmatrix
>>> import numpy as np
>>> import pandas as pd
>>> import random
>>> # Create dataframe with random data
>>> df = pd.DataFrame(np.random.randn(100, 3),
... columns=['Column A',
... 'Column B',
... 'Column C'])
>>> # Add new color column to dataframe
>>> new_column = []
>>> strange_colors = ['turquoise', 'limegreen', 'goldenrod']
>>> for j in range(100):
... new_column.append(random.choice(strange_colors))
>>> df['Colors'] = pd.Series(new_column, index=df.index)
>>> # Create scatterplot matrix using a dictionary of hex color values
>>> # which correspond to actual color names in 'Colors' column
>>> fig = create_scatterplotmatrix(
... df, diag='box', index='Colors',
... colormap= dict(
... turquoise = '#00F5FF',
... limegreen = '#32CD32',
... goldenrod = '#DAA520'
... ),
... colormap_type='cat',
... height=800, width=800
... )
>>> fig.show()
"""
# TODO: protected until #282
if dataframe is None:
dataframe = []
if headers is None:
headers = []
if index_vals is None:
index_vals = []
validate_scatterplotmatrix(df, index, diag, colormap_type, **kwargs)
# Validate colormap
if isinstance(colormap, dict):
colormap = clrs.validate_colors_dict(colormap, "rgb")
elif isinstance(colormap, str) and "rgb" not in colormap and "#" not in colormap:
if colormap not in clrs.PLOTLY_SCALES.keys():
raise exceptions.PlotlyError(
"If 'colormap' is a string, it must be the name "
"of a Plotly Colorscale. The available colorscale "
"names are {}".format(clrs.PLOTLY_SCALES.keys())
)
else:
# TODO change below to allow the correct Plotly colorscale
colormap = clrs.colorscale_to_colors(clrs.PLOTLY_SCALES[colormap])
# keep only first and last item - fix later
colormap = [colormap[0]] + [colormap[-1]]
colormap = clrs.validate_colors(colormap, "rgb")
else:
colormap = clrs.validate_colors(colormap, "rgb")
if not index:
for name in df:
headers.append(name)
for name in headers:
dataframe.append(df[name].values.tolist())
# Check for same data-type in df columns
utils.validate_dataframe(dataframe)
figure = scatterplot(
dataframe, headers, diag, size, height, width, title, **kwargs
)
return figure
else:
# Validate index selection
if index not in df:
raise exceptions.PlotlyError(
"Make sure you set the index "
"input variable to one of the "
"column names of your "
"dataframe."
)
index_vals = df[index].values.tolist()
for name in df:
if name != index:
headers.append(name)
for name in headers:
dataframe.append(df[name].values.tolist())
# check for same data-type in each df column
utils.validate_dataframe(dataframe)
utils.validate_index(index_vals)
# check if all colormap keys are in the index
# if colormap is a dictionary
if isinstance(colormap, dict):
for key in colormap:
if not all(index in colormap for index in index_vals):
raise exceptions.PlotlyError(
"If colormap is a "
"dictionary, all the "
"names in the index "
"must be keys."
)
figure = scatterplot_dict(
dataframe,
headers,
diag,
size,
height,
width,
title,
index,
index_vals,
endpts,
colormap,
colormap_type,
**kwargs,
)
return figure
else:
figure = scatterplot_theme(
dataframe,
headers,
diag,
size,
height,
width,
title,
index,
index_vals,
endpts,
colormap,
colormap_type,
**kwargs,
)
return figure
| _scatterplot.create_scatterplotmatrix |
plotly.py | 46 | packages/python/plotly/plotly/graph_objs/_scatterpolar.py | def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatterpolar.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Supported dict properties:
angle
Sets the marker angle in respect to `angleref`.
angleref
Sets the reference for marker angle. With
"previous", angle 0 points along the line from
the previous point to this one. With "up",
angle 0 points toward the top of the screen.
anglesrc
Sets the source reference on Chart Studio Cloud
for `angle`.
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.colorscale`. Has an
effect only if in `marker.color` is set to a
numerical array. In case `colorscale` is
unspecified or `autocolorscale` is true, the
default palette will be chosen according to
whether numbers in the `color` array are all
positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `marker.color`) or the bounds set in
`marker.cmin` and `marker.cmax` Has an effect
only if in `marker.color` is set to a numerical
array. Defaults to `false` when `marker.cmin`
and `marker.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `marker.cmin` and/or `marker.cmax` to
be equidistant to this point. Has an effect
only if in `marker.color` is set to a numerical
array. Value should have the same units as in
`marker.color`. Has no effect when
`marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmax` must be set as well.
color
Sets the marker color. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`marker.cmin` and `marker.cmax` if set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.scatterpolar.marke
r.ColorBar` instance or dict with compatible
properties
colorscale
Sets the colorscale. Has an effect only if in
`marker.color` is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `marker.cmin` and
`marker.cmax`. Alternatively, `colorscale` may
be a palette name string of the following list:
Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud
for `color`.
gradient
:class:`plotly.graph_objects.scatterpolar.marke
r.Gradient` instance or dict with compatible
properties
line
:class:`plotly.graph_objects.scatterpolar.marke
r.Line` instance or dict with compatible
properties
maxdisplayed
Sets a maximum number of points to be drawn on
the graph. 0 corresponds to no limit.
opacity
Sets the marker opacity.
opacitysrc
Sets the source reference on Chart Studio Cloud
for `opacity`.
reversescale
Reverses the color mapping if true. Has an
effect only if in `marker.color` is set to a
numerical array. If true, `marker.cmin` will
correspond to the last color in the array and
`marker.cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
in `marker.color` is set to a numerical array.
size
Sets the marker size (in px).
sizemin
Has an effect only if `marker.size` is set to a
numerical array. Sets the minimum size (in px)
of the rendered marker points.
sizemode
Has an effect only if `marker.size` is set to a
numerical array. Sets the rule for which the
data in `size` is converted to pixels.
sizeref
Has an effect only if `marker.size` is set to a
numerical array. Sets the scale factor used to
determine the rendered size of marker points.
Use with `sizemin` and `sizemode`.
sizesrc
Sets the source reference on Chart Studio Cloud
for `size`.
standoff
Moves the marker away from the data point in
the direction of `angle` (in px). This can be
useful for example if you have another marker
at this location and you want to point an
arrowhead marker at it.
standoffsrc
Sets the source reference on Chart Studio Cloud
for `standoff`.
symbol
Sets the marker symbol type. Adding 100 is
equivalent to appending "-open" to a symbol
name. Adding 200 is equivalent to appending
"-dot" to a symbol name. Adding 300 is
equivalent to appending "-open-dot" or "dot-
open" to a symbol name.
symbolsrc
Sets the source reference on Chart Studio Cloud
for `symbol`.
Returns
-------
plotly.graph_objs.scatterpolar.Marker
"""
| /usr/src/app/target_test_cases/failed_tests__scatterpolar.marker.txt | def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatterpolar.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Supported dict properties:
angle
Sets the marker angle in respect to `angleref`.
angleref
Sets the reference for marker angle. With
"previous", angle 0 points along the line from
the previous point to this one. With "up",
angle 0 points toward the top of the screen.
anglesrc
Sets the source reference on Chart Studio Cloud
for `angle`.
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.colorscale`. Has an
effect only if in `marker.color` is set to a
numerical array. In case `colorscale` is
unspecified or `autocolorscale` is true, the
default palette will be chosen according to
whether numbers in the `color` array are all
positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `marker.color`) or the bounds set in
`marker.cmin` and `marker.cmax` Has an effect
only if in `marker.color` is set to a numerical
array. Defaults to `false` when `marker.cmin`
and `marker.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `marker.cmin` and/or `marker.cmax` to
be equidistant to this point. Has an effect
only if in `marker.color` is set to a numerical
array. Value should have the same units as in
`marker.color`. Has no effect when
`marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmax` must be set as well.
color
Sets the marker color. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`marker.cmin` and `marker.cmax` if set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.scatterpolar.marke
r.ColorBar` instance or dict with compatible
properties
colorscale
Sets the colorscale. Has an effect only if in
`marker.color` is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `marker.cmin` and
`marker.cmax`. Alternatively, `colorscale` may
be a palette name string of the following list:
Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud
for `color`.
gradient
:class:`plotly.graph_objects.scatterpolar.marke
r.Gradient` instance or dict with compatible
properties
line
:class:`plotly.graph_objects.scatterpolar.marke
r.Line` instance or dict with compatible
properties
maxdisplayed
Sets a maximum number of points to be drawn on
the graph. 0 corresponds to no limit.
opacity
Sets the marker opacity.
opacitysrc
Sets the source reference on Chart Studio Cloud
for `opacity`.
reversescale
Reverses the color mapping if true. Has an
effect only if in `marker.color` is set to a
numerical array. If true, `marker.cmin` will
correspond to the last color in the array and
`marker.cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
in `marker.color` is set to a numerical array.
size
Sets the marker size (in px).
sizemin
Has an effect only if `marker.size` is set to a
numerical array. Sets the minimum size (in px)
of the rendered marker points.
sizemode
Has an effect only if `marker.size` is set to a
numerical array. Sets the rule for which the
data in `size` is converted to pixels.
sizeref
Has an effect only if `marker.size` is set to a
numerical array. Sets the scale factor used to
determine the rendered size of marker points.
Use with `sizemin` and `sizemode`.
sizesrc
Sets the source reference on Chart Studio Cloud
for `size`.
standoff
Moves the marker away from the data point in
the direction of `angle` (in px). This can be
useful for example if you have another marker
at this location and you want to point an
arrowhead marker at it.
standoffsrc
Sets the source reference on Chart Studio Cloud
for `standoff`.
symbol
Sets the marker symbol type. Adding 100 is
equivalent to appending "-open" to a symbol
name. Adding 200 is equivalent to appending
"-dot" to a symbol name. Adding 300 is
equivalent to appending "-open-dot" or "dot-
open" to a symbol name.
symbolsrc
Sets the source reference on Chart Studio Cloud
for `symbol`.
Returns
-------
plotly.graph_objs.scatterpolar.Marker
"""
return self["marker"]
| _scatterpolar.marker |
plotly.py | 47 | packages/python/plotly/plotly/graph_objs/layout/_scene.py | def xaxis(self):
"""
The 'xaxis' property is an instance of XAxis
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.scene.XAxis`
- A dict of string/value properties that will be passed
to the XAxis constructor
Supported dict properties:
autorange
Determines whether or not the range of this
axis is computed in relation to the input data.
See `rangemode` for more info. If `range` is
provided and it has a value for both the lower
and upper bound, `autorange` is set to False.
Using "min" applies autorange only to set the
minimum. Using "max" applies autorange only to
set the maximum. Using *min reversed* applies
autorange only to set the minimum on a reversed
axis. Using *max reversed* applies autorange
only to set the maximum on a reversed axis.
Using "reversed" applies autorange on both ends
and reverses the axis direction.
autorangeoptions
:class:`plotly.graph_objects.layout.scene.xaxis
.Autorangeoptions` instance or dict with
compatible properties
autotypenumbers
Using "strict" a numeric string in trace data
is not converted to a number. Using *convert
types* a numeric string in trace data may be
treated as a number during automatic axis
`type` detection. Defaults to
layout.autotypenumbers.
backgroundcolor
Sets the background color of this axis' wall.
calendar
Sets the calendar system to use for `range` and
`tick0` if this is a date axis. This does not
set the calendar for interpreting data on this
axis, that's specified in the trace or via the
global `layout.calendar`
categoryarray
Sets the order in which categories on this axis
appear. Only has an effect if `categoryorder`
is set to "array". Used with `categoryorder`.
categoryarraysrc
Sets the source reference on Chart Studio Cloud
for `categoryarray`.
categoryorder
Specifies the ordering logic for the case of
categorical variables. By default, plotly uses
"trace", which specifies the order that is
present in the data supplied. Set
`categoryorder` to *category ascending* or
*category descending* if order should be
determined by the alphanumerical order of the
category names. Set `categoryorder` to "array"
to derive the ordering from the attribute
`categoryarray`. If a category is not found in
the `categoryarray` array, the sorting behavior
for that attribute will be identical to the
"trace" mode. The unspecified categories will
follow the categories in `categoryarray`. Set
`categoryorder` to *total ascending* or *total
descending* if order should be determined by
the numerical order of the values. Similarly,
the order can be determined by the min, max,
sum, mean, geometric mean or median of all the
values.
color
Sets default for all colors associated with
this axis all at once: line, font, tick, and
grid colors. Grid color is lightened by
blending this with the plot background
Individual pieces can override this.
dtick
Sets the step in-between ticks on this axis.
Use with `tick0`. Must be a positive number, or
special strings available to "log" and "date"
axes. If the axis `type` is "log", then ticks
are set every 10^(n*dtick) where n is the tick
number. For example, to set a tick mark at 1,
10, 100, 1000, ... set dtick to 1. To set tick
marks at 1, 100, 10000, ... set dtick to 2. To
set tick marks at 1, 5, 25, 125, 625, 3125, ...
set dtick to log_10(5), or 0.69897000433. "log"
has several special values; "L<f>", where `f`
is a positive number, gives ticks linearly
spaced in value (but not position). For example
`tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10
plus small digits between, use "D1" (all
digits) or "D2" (only 2 and 5). `tick0` is
ignored for "D1" and "D2". If the axis `type`
is "date", then you must convert the time to
milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to
86400000.0. "date" also has special values
"M<n>" gives ticks spaced by a number of
months. `n` must be a positive integer. To set
ticks on the 15th of every third month, set
`tick0` to "2000-01-15" and `dtick` to "M3". To
set ticks every 4 years, set `dtick` to "M48"
exponentformat
Determines a formatting rule for the tick
exponents. For example, consider the number
1,000,000,000. If "none", it appears as
1,000,000,000. If "e", 1e+9. If "E", 1E+9. If
"power", 1x10^9 (with 9 in a super script). If
"SI", 1G. If "B", 1B.
gridcolor
Sets the color of the grid lines.
gridwidth
Sets the width (in px) of the grid lines.
hoverformat
Sets the hover text formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see: h
ttps://github.com/d3/d3-format/tree/v1.4.5#d3-
format. And for dates see:
https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two
items to d3's date formatter: "%h" for half of
the year as a decimal number as well as "%{n}f"
for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with
tickformat "%H~%M~%S.%2f" would display
"09~15~23.46"
labelalias
Replacement text for specific tick or hover
labels. For example using {US: 'USA', CA:
'Canada'} changes US to USA and CA to Canada.
The labels we would have shown must match the
keys exactly, after adding any tickprefix or
ticksuffix. For negative numbers the minus sign
symbol used (U+2212) is wider than the regular
ascii dash. That means you need to use −1
instead of -1. labelalias can be used with any
axis type, and both keys (if needed) and values
(if desired) can include html-like tags or
MathJax.
linecolor
Sets the axis line color.
linewidth
Sets the width (in px) of the axis line.
maxallowed
Determines the maximum range of this axis.
minallowed
Determines the minimum range of this axis.
minexponent
Hide SI prefix for 10^n if |n| is below this
number. This only has an effect when
`tickformat` is "SI" or "B".
mirror
Determines if the axis lines or/and ticks are
mirrored to the opposite side of the plotting
area. If True, the axis lines are mirrored. If
"ticks", the axis lines and ticks are mirrored.
If False, mirroring is disable. If "all", axis
lines are mirrored on all shared-axes subplots.
If "allticks", axis lines and ticks are
mirrored on all shared-axes subplots.
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks
will be chosen automatically to be less than or
equal to `nticks`. Has an effect only if
`tickmode` is set to "auto".
range
Sets the range of this axis. If the axis `type`
is "log", then you must take the log of your
desired range (e.g. to set the range from 1 to
100, set the range from 0 to 2). If the axis
`type` is "date", it should be date strings,
like date data, though Date objects and unix
milliseconds will be accepted and converted to
strings. If the axis `type` is "category", it
should be numbers, using the scale where each
category is assigned a serial number from zero
in the order it appears. Leaving either or both
elements `null` impacts the default
`autorange`.
rangemode
If "normal", the range is computed in relation
to the extrema of the input data. If *tozero*`,
the range extends to 0, regardless of the input
data If "nonnegative", the range is non-
negative, regardless of the input data. Applies
only to linear axes.
separatethousands
If "true", even 4-digit integers are separated
showaxeslabels
Sets whether or not this axis is labeled
showbackground
Sets whether or not this axis' wall has a
background color.
showexponent
If "all", all exponents are shown besides their
significands. If "first", only the exponent of
the first tick is shown. If "last", only the
exponent of the last tick is shown. If "none",
no exponents appear.
showgrid
Determines whether or not grid lines are drawn.
If True, the grid lines are drawn at every tick
mark.
showline
Determines whether or not a line bounding this
axis is drawn.
showspikes
Sets whether or not spikes starting from data
points to this axis' wall are shown on hover.
showticklabels
Determines whether or not the tick labels are
drawn.
showtickprefix
If "all", all tick labels are displayed with a
prefix. If "first", only the first tick is
displayed with a prefix. If "last", only the
last tick is displayed with a suffix. If
"none", tick prefixes are hidden.
showticksuffix
Same as `showtickprefix` but for tick suffixes.
spikecolor
Sets the color of the spikes.
spikesides
Sets whether or not spikes extending from the
projection data points to this axis' wall
boundaries are shown on hover.
spikethickness
Sets the thickness (in px) of the spikes.
tick0
Sets the placement of the first tick on this
axis. Use with `dtick`. If the axis `type` is
"log", then you must take the log of your
starting tick (e.g. to set the starting tick to
100, set the `tick0` to 2) except when
`dtick`=*L<f>* (see `dtick` for more info). If
the axis `type` is "date", it should be a date
string, like date data. If the axis `type` is
"category", it should be a number, using the
scale where each category is assigned a serial
number from zero in the order it appears.
tickangle
Sets the angle of the tick labels with respect
to the horizontal. For example, a `tickangle`
of -90 draws the tick labels vertically.
tickcolor
Sets the tick color.
tickfont
Sets the tick font.
tickformat
Sets the tick label formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see: h
ttps://github.com/d3/d3-format/tree/v1.4.5#d3-
format. And for dates see:
https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two
items to d3's date formatter: "%h" for half of
the year as a decimal number as well as "%{n}f"
for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with
tickformat "%H~%M~%S.%2f" would display
"09~15~23.46"
tickformatstops
A tuple of :class:`plotly.graph_objects.layout.
scene.xaxis.Tickformatstop` instances or dicts
with compatible properties
tickformatstopdefaults
When used in a template (as layout.template.lay
out.scene.xaxis.tickformatstopdefaults), sets
the default property values to use for elements
of layout.scene.xaxis.tickformatstops
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto",
the number of ticks is set via `nticks`. If
"linear", the placement of the ticks is
determined by a starting position `tick0` and a
tick step `dtick` ("linear" is the default
value if `tick0` and `dtick` are provided). If
"array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`.
("array" is the default value if `tickvals` is
provided).
tickprefix
Sets a tick label prefix.
ticks
Determines whether ticks are drawn or not. If
"", this axis' ticks are not drawn. If
"outside" ("inside"), this axis' are drawn
outside (inside) the axis lines.
ticksuffix
Sets a tick label suffix.
ticktext
Sets the text displayed at the ticks position
via `tickvals`. Only has an effect if
`tickmode` is set to "array". Used with
`tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud
for `ticktext`.
tickvals
Sets the values at which ticks on this axis
appear. Only has an effect if `tickmode` is set
to "array". Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud
for `tickvals`.
tickwidth
Sets the tick width (in px).
title
:class:`plotly.graph_objects.layout.scene.xaxis
.Title` instance or dict with compatible
properties
titlefont
Deprecated: Please use
layout.scene.xaxis.title.font instead. Sets
this axis' title font. Note that the title's
font used to be customized by the now
deprecated `titlefont` attribute.
type
Sets the axis type. By default, plotly attempts
to determined the axis type by looking into the
data of the traces that referenced the axis in
question.
visible
A single toggle to hide the axis while
preserving interaction like dragging. Default
is true when a cheater plot is present on the
axis, otherwise false
zeroline
Determines whether or not a line is drawn at
along the 0 value of this axis. If True, the
zero line is drawn on top of the grid lines.
zerolinecolor
Sets the line color of the zero line.
zerolinewidth
Sets the width (in px) of the zero line.
Returns
-------
plotly.graph_objs.layout.scene.XAxis
"""
| /usr/src/app/target_test_cases/failed_tests__scene.xaxis.txt | def xaxis(self):
"""
The 'xaxis' property is an instance of XAxis
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.scene.XAxis`
- A dict of string/value properties that will be passed
to the XAxis constructor
Supported dict properties:
autorange
Determines whether or not the range of this
axis is computed in relation to the input data.
See `rangemode` for more info. If `range` is
provided and it has a value for both the lower
and upper bound, `autorange` is set to False.
Using "min" applies autorange only to set the
minimum. Using "max" applies autorange only to
set the maximum. Using *min reversed* applies
autorange only to set the minimum on a reversed
axis. Using *max reversed* applies autorange
only to set the maximum on a reversed axis.
Using "reversed" applies autorange on both ends
and reverses the axis direction.
autorangeoptions
:class:`plotly.graph_objects.layout.scene.xaxis
.Autorangeoptions` instance or dict with
compatible properties
autotypenumbers
Using "strict" a numeric string in trace data
is not converted to a number. Using *convert
types* a numeric string in trace data may be
treated as a number during automatic axis
`type` detection. Defaults to
layout.autotypenumbers.
backgroundcolor
Sets the background color of this axis' wall.
calendar
Sets the calendar system to use for `range` and
`tick0` if this is a date axis. This does not
set the calendar for interpreting data on this
axis, that's specified in the trace or via the
global `layout.calendar`
categoryarray
Sets the order in which categories on this axis
appear. Only has an effect if `categoryorder`
is set to "array". Used with `categoryorder`.
categoryarraysrc
Sets the source reference on Chart Studio Cloud
for `categoryarray`.
categoryorder
Specifies the ordering logic for the case of
categorical variables. By default, plotly uses
"trace", which specifies the order that is
present in the data supplied. Set
`categoryorder` to *category ascending* or
*category descending* if order should be
determined by the alphanumerical order of the
category names. Set `categoryorder` to "array"
to derive the ordering from the attribute
`categoryarray`. If a category is not found in
the `categoryarray` array, the sorting behavior
for that attribute will be identical to the
"trace" mode. The unspecified categories will
follow the categories in `categoryarray`. Set
`categoryorder` to *total ascending* or *total
descending* if order should be determined by
the numerical order of the values. Similarly,
the order can be determined by the min, max,
sum, mean, geometric mean or median of all the
values.
color
Sets default for all colors associated with
this axis all at once: line, font, tick, and
grid colors. Grid color is lightened by
blending this with the plot background
Individual pieces can override this.
dtick
Sets the step in-between ticks on this axis.
Use with `tick0`. Must be a positive number, or
special strings available to "log" and "date"
axes. If the axis `type` is "log", then ticks
are set every 10^(n*dtick) where n is the tick
number. For example, to set a tick mark at 1,
10, 100, 1000, ... set dtick to 1. To set tick
marks at 1, 100, 10000, ... set dtick to 2. To
set tick marks at 1, 5, 25, 125, 625, 3125, ...
set dtick to log_10(5), or 0.69897000433. "log"
has several special values; "L<f>", where `f`
is a positive number, gives ticks linearly
spaced in value (but not position). For example
`tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10
plus small digits between, use "D1" (all
digits) or "D2" (only 2 and 5). `tick0` is
ignored for "D1" and "D2". If the axis `type`
is "date", then you must convert the time to
milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to
86400000.0. "date" also has special values
"M<n>" gives ticks spaced by a number of
months. `n` must be a positive integer. To set
ticks on the 15th of every third month, set
`tick0` to "2000-01-15" and `dtick` to "M3". To
set ticks every 4 years, set `dtick` to "M48"
exponentformat
Determines a formatting rule for the tick
exponents. For example, consider the number
1,000,000,000. If "none", it appears as
1,000,000,000. If "e", 1e+9. If "E", 1E+9. If
"power", 1x10^9 (with 9 in a super script). If
"SI", 1G. If "B", 1B.
gridcolor
Sets the color of the grid lines.
gridwidth
Sets the width (in px) of the grid lines.
hoverformat
Sets the hover text formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see: h
ttps://github.com/d3/d3-format/tree/v1.4.5#d3-
format. And for dates see:
https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two
items to d3's date formatter: "%h" for half of
the year as a decimal number as well as "%{n}f"
for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with
tickformat "%H~%M~%S.%2f" would display
"09~15~23.46"
labelalias
Replacement text for specific tick or hover
labels. For example using {US: 'USA', CA:
'Canada'} changes US to USA and CA to Canada.
The labels we would have shown must match the
keys exactly, after adding any tickprefix or
ticksuffix. For negative numbers the minus sign
symbol used (U+2212) is wider than the regular
ascii dash. That means you need to use −1
instead of -1. labelalias can be used with any
axis type, and both keys (if needed) and values
(if desired) can include html-like tags or
MathJax.
linecolor
Sets the axis line color.
linewidth
Sets the width (in px) of the axis line.
maxallowed
Determines the maximum range of this axis.
minallowed
Determines the minimum range of this axis.
minexponent
Hide SI prefix for 10^n if |n| is below this
number. This only has an effect when
`tickformat` is "SI" or "B".
mirror
Determines if the axis lines or/and ticks are
mirrored to the opposite side of the plotting
area. If True, the axis lines are mirrored. If
"ticks", the axis lines and ticks are mirrored.
If False, mirroring is disable. If "all", axis
lines are mirrored on all shared-axes subplots.
If "allticks", axis lines and ticks are
mirrored on all shared-axes subplots.
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks
will be chosen automatically to be less than or
equal to `nticks`. Has an effect only if
`tickmode` is set to "auto".
range
Sets the range of this axis. If the axis `type`
is "log", then you must take the log of your
desired range (e.g. to set the range from 1 to
100, set the range from 0 to 2). If the axis
`type` is "date", it should be date strings,
like date data, though Date objects and unix
milliseconds will be accepted and converted to
strings. If the axis `type` is "category", it
should be numbers, using the scale where each
category is assigned a serial number from zero
in the order it appears. Leaving either or both
elements `null` impacts the default
`autorange`.
rangemode
If "normal", the range is computed in relation
to the extrema of the input data. If *tozero*`,
the range extends to 0, regardless of the input
data If "nonnegative", the range is non-
negative, regardless of the input data. Applies
only to linear axes.
separatethousands
If "true", even 4-digit integers are separated
showaxeslabels
Sets whether or not this axis is labeled
showbackground
Sets whether or not this axis' wall has a
background color.
showexponent
If "all", all exponents are shown besides their
significands. If "first", only the exponent of
the first tick is shown. If "last", only the
exponent of the last tick is shown. If "none",
no exponents appear.
showgrid
Determines whether or not grid lines are drawn.
If True, the grid lines are drawn at every tick
mark.
showline
Determines whether or not a line bounding this
axis is drawn.
showspikes
Sets whether or not spikes starting from data
points to this axis' wall are shown on hover.
showticklabels
Determines whether or not the tick labels are
drawn.
showtickprefix
If "all", all tick labels are displayed with a
prefix. If "first", only the first tick is
displayed with a prefix. If "last", only the
last tick is displayed with a suffix. If
"none", tick prefixes are hidden.
showticksuffix
Same as `showtickprefix` but for tick suffixes.
spikecolor
Sets the color of the spikes.
spikesides
Sets whether or not spikes extending from the
projection data points to this axis' wall
boundaries are shown on hover.
spikethickness
Sets the thickness (in px) of the spikes.
tick0
Sets the placement of the first tick on this
axis. Use with `dtick`. If the axis `type` is
"log", then you must take the log of your
starting tick (e.g. to set the starting tick to
100, set the `tick0` to 2) except when
`dtick`=*L<f>* (see `dtick` for more info). If
the axis `type` is "date", it should be a date
string, like date data. If the axis `type` is
"category", it should be a number, using the
scale where each category is assigned a serial
number from zero in the order it appears.
tickangle
Sets the angle of the tick labels with respect
to the horizontal. For example, a `tickangle`
of -90 draws the tick labels vertically.
tickcolor
Sets the tick color.
tickfont
Sets the tick font.
tickformat
Sets the tick label formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see: h
ttps://github.com/d3/d3-format/tree/v1.4.5#d3-
format. And for dates see:
https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two
items to d3's date formatter: "%h" for half of
the year as a decimal number as well as "%{n}f"
for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with
tickformat "%H~%M~%S.%2f" would display
"09~15~23.46"
tickformatstops
A tuple of :class:`plotly.graph_objects.layout.
scene.xaxis.Tickformatstop` instances or dicts
with compatible properties
tickformatstopdefaults
When used in a template (as layout.template.lay
out.scene.xaxis.tickformatstopdefaults), sets
the default property values to use for elements
of layout.scene.xaxis.tickformatstops
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto",
the number of ticks is set via `nticks`. If
"linear", the placement of the ticks is
determined by a starting position `tick0` and a
tick step `dtick` ("linear" is the default
value if `tick0` and `dtick` are provided). If
"array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`.
("array" is the default value if `tickvals` is
provided).
tickprefix
Sets a tick label prefix.
ticks
Determines whether ticks are drawn or not. If
"", this axis' ticks are not drawn. If
"outside" ("inside"), this axis' are drawn
outside (inside) the axis lines.
ticksuffix
Sets a tick label suffix.
ticktext
Sets the text displayed at the ticks position
via `tickvals`. Only has an effect if
`tickmode` is set to "array". Used with
`tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud
for `ticktext`.
tickvals
Sets the values at which ticks on this axis
appear. Only has an effect if `tickmode` is set
to "array". Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud
for `tickvals`.
tickwidth
Sets the tick width (in px).
title
:class:`plotly.graph_objects.layout.scene.xaxis
.Title` instance or dict with compatible
properties
titlefont
Deprecated: Please use
layout.scene.xaxis.title.font instead. Sets
this axis' title font. Note that the title's
font used to be customized by the now
deprecated `titlefont` attribute.
type
Sets the axis type. By default, plotly attempts
to determined the axis type by looking into the
data of the traces that referenced the axis in
question.
visible
A single toggle to hide the axis while
preserving interaction like dragging. Default
is true when a cheater plot is present on the
axis, otherwise false
zeroline
Determines whether or not a line is drawn at
along the 0 value of this axis. If True, the
zero line is drawn on top of the grid lines.
zerolinecolor
Sets the line color of the zero line.
zerolinewidth
Sets the width (in px) of the zero line.
Returns
-------
plotly.graph_objs.layout.scene.XAxis
"""
return self["xaxis"]
| _scene.xaxis |
plotly.py | 48 | packages/python/plotly/plotly/graph_objs/layout/_selection.py | def __init__(
self,
arg=None,
line=None,
name=None,
opacity=None,
path=None,
templateitemname=None,
type=None,
x0=None,
x1=None,
xref=None,
y0=None,
y1=None,
yref=None,
**kwargs,
):
"""
Construct a new Selection object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.layout.Selection`
line
:class:`plotly.graph_objects.layout.selection.Line`
instance or dict with compatible properties
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
opacity
Sets the opacity of the selection.
path
For `type` "path" - a valid SVG path similar to
`shapes.path` in data coordinates. Allowed segments
are: M, L and Z.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
type
Specifies the selection type to be drawn. If "rect", a
rectangle is drawn linking (`x0`,`y0`), (`x1`,`y0`),
(`x1`,`y1`) and (`x0`,`y1`). If "path", draw a custom
SVG path using `path`.
x0
Sets the selection's starting x position.
x1
Sets the selection's end x position.
xref
Sets the selection's x coordinate axis. If set to a x
axis id (e.g. "x" or "x2"), the `x` position refers to
a x coordinate. If set to "paper", the `x` position
refers to the distance from the left of the plotting
area in normalized coordinates where 0 (1) corresponds
to the left (right). If set to a x axis ID followed by
"domain" (separated by a space), the position behaves
like for "paper", but refers to the distance in
fractions of the domain length from the left of the
domain of that axis: e.g., *x2 domain* refers to the
domain of the second x axis and a x position of 0.5
refers to the point between the left and the right of
the domain of the second x axis.
y0
Sets the selection's starting y position.
y1
Sets the selection's end y position.
yref
Sets the selection's x coordinate axis. If set to a y
axis id (e.g. "y" or "y2"), the `y` position refers to
a y coordinate. If set to "paper", the `y` position
refers to the distance from the bottom of the plotting
area in normalized coordinates where 0 (1) corresponds
to the bottom (top). If set to a y axis ID followed by
"domain" (separated by a space), the position behaves
like for "paper", but refers to the distance in
fractions of the domain length from the bottom of the
domain of that axis: e.g., *y2 domain* refers to the
domain of the second y axis and a y position of 0.5
refers to the point between the bottom and the top of
the domain of the second y axis.
Returns
-------
Selection
"""
| /usr/src/app/target_test_cases/failed_tests__selection.Selection.__init__.txt | def __init__(
self,
arg=None,
line=None,
name=None,
opacity=None,
path=None,
templateitemname=None,
type=None,
x0=None,
x1=None,
xref=None,
y0=None,
y1=None,
yref=None,
**kwargs,
):
"""
Construct a new Selection object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.layout.Selection`
line
:class:`plotly.graph_objects.layout.selection.Line`
instance or dict with compatible properties
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
opacity
Sets the opacity of the selection.
path
For `type` "path" - a valid SVG path similar to
`shapes.path` in data coordinates. Allowed segments
are: M, L and Z.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
type
Specifies the selection type to be drawn. If "rect", a
rectangle is drawn linking (`x0`,`y0`), (`x1`,`y0`),
(`x1`,`y1`) and (`x0`,`y1`). If "path", draw a custom
SVG path using `path`.
x0
Sets the selection's starting x position.
x1
Sets the selection's end x position.
xref
Sets the selection's x coordinate axis. If set to a x
axis id (e.g. "x" or "x2"), the `x` position refers to
a x coordinate. If set to "paper", the `x` position
refers to the distance from the left of the plotting
area in normalized coordinates where 0 (1) corresponds
to the left (right). If set to a x axis ID followed by
"domain" (separated by a space), the position behaves
like for "paper", but refers to the distance in
fractions of the domain length from the left of the
domain of that axis: e.g., *x2 domain* refers to the
domain of the second x axis and a x position of 0.5
refers to the point between the left and the right of
the domain of the second x axis.
y0
Sets the selection's starting y position.
y1
Sets the selection's end y position.
yref
Sets the selection's x coordinate axis. If set to a y
axis id (e.g. "y" or "y2"), the `y` position refers to
a y coordinate. If set to "paper", the `y` position
refers to the distance from the bottom of the plotting
area in normalized coordinates where 0 (1) corresponds
to the bottom (top). If set to a y axis ID followed by
"domain" (separated by a space), the position behaves
like for "paper", but refers to the distance in
fractions of the domain length from the bottom of the
domain of that axis: e.g., *y2 domain* refers to the
domain of the second y axis and a y position of 0.5
refers to the point between the bottom and the top of
the domain of the second y axis.
Returns
-------
Selection
"""
super(Selection, self).__init__("selections")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.layout.Selection
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.Selection`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("line", None)
_v = line if line is not None else _v
if _v is not None:
self["line"] = _v
_v = arg.pop("name", None)
_v = name if name is not None else _v
if _v is not None:
self["name"] = _v
_v = arg.pop("opacity", None)
_v = opacity if opacity is not None else _v
if _v is not None:
self["opacity"] = _v
_v = arg.pop("path", None)
_v = path if path is not None else _v
if _v is not None:
self["path"] = _v
_v = arg.pop("templateitemname", None)
_v = templateitemname if templateitemname is not None else _v
if _v is not None:
self["templateitemname"] = _v
_v = arg.pop("type", None)
_v = type if type is not None else _v
if _v is not None:
self["type"] = _v
_v = arg.pop("x0", None)
_v = x0 if x0 is not None else _v
if _v is not None:
self["x0"] = _v
_v = arg.pop("x1", None)
_v = x1 if x1 is not None else _v
if _v is not None:
self["x1"] = _v
_v = arg.pop("xref", None)
_v = xref if xref is not None else _v
if _v is not None:
self["xref"] = _v
_v = arg.pop("y0", None)
_v = y0 if y0 is not None else _v
if _v is not None:
self["y0"] = _v
_v = arg.pop("y1", None)
_v = y1 if y1 is not None else _v
if _v is not None:
self["y1"] = _v
_v = arg.pop("yref", None)
_v = yref if yref is not None else _v
if _v is not None:
self["yref"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| _selection.Selection.__init__ |
plotly.py | 49 | packages/python/plotly/plotly/graph_objs/layout/_slider.py | def __init__(
self,
arg=None,
active=None,
activebgcolor=None,
bgcolor=None,
bordercolor=None,
borderwidth=None,
currentvalue=None,
font=None,
len=None,
lenmode=None,
minorticklen=None,
name=None,
pad=None,
steps=None,
stepdefaults=None,
templateitemname=None,
tickcolor=None,
ticklen=None,
tickwidth=None,
transition=None,
visible=None,
x=None,
xanchor=None,
y=None,
yanchor=None,
**kwargs,
):
"""
Construct a new Slider object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.layout.Slider`
active
Determines which button (by index starting from 0) is
considered active.
activebgcolor
Sets the background color of the slider grip while
dragging.
bgcolor
Sets the background color of the slider.
bordercolor
Sets the color of the border enclosing the slider.
borderwidth
Sets the width (in px) of the border enclosing the
slider.
currentvalue
:class:`plotly.graph_objects.layout.slider.Currentvalue
` instance or dict with compatible properties
font
Sets the font of the slider step labels.
len
Sets the length of the slider This measure excludes the
padding of both ends. That is, the slider's length is
this length minus the padding on both ends.
lenmode
Determines whether this slider length is set in units
of plot "fraction" or in *pixels. Use `len` to set the
value.
minorticklen
Sets the length in pixels of minor step tick marks
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
pad
Set the padding of the slider component along each
side.
steps
A tuple of
:class:`plotly.graph_objects.layout.slider.Step`
instances or dicts with compatible properties
stepdefaults
When used in a template (as
layout.template.layout.slider.stepdefaults), sets the
default property values to use for elements of
layout.slider.steps
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
tickcolor
Sets the color of the border enclosing the slider.
ticklen
Sets the length in pixels of step tick marks
tickwidth
Sets the tick width (in px).
transition
:class:`plotly.graph_objects.layout.slider.Transition`
instance or dict with compatible properties
visible
Determines whether or not the slider is visible.
x
Sets the x position (in normalized coordinates) of the
slider.
xanchor
Sets the slider's horizontal position anchor. This
anchor binds the `x` position to the "left", "center"
or "right" of the range selector.
y
Sets the y position (in normalized coordinates) of the
slider.
yanchor
Sets the slider's vertical position anchor This anchor
binds the `y` position to the "top", "middle" or
"bottom" of the range selector.
Returns
-------
Slider
"""
| /usr/src/app/target_test_cases/failed_tests__slider.Slider.__init__.txt | def __init__(
self,
arg=None,
active=None,
activebgcolor=None,
bgcolor=None,
bordercolor=None,
borderwidth=None,
currentvalue=None,
font=None,
len=None,
lenmode=None,
minorticklen=None,
name=None,
pad=None,
steps=None,
stepdefaults=None,
templateitemname=None,
tickcolor=None,
ticklen=None,
tickwidth=None,
transition=None,
visible=None,
x=None,
xanchor=None,
y=None,
yanchor=None,
**kwargs,
):
"""
Construct a new Slider object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.layout.Slider`
active
Determines which button (by index starting from 0) is
considered active.
activebgcolor
Sets the background color of the slider grip while
dragging.
bgcolor
Sets the background color of the slider.
bordercolor
Sets the color of the border enclosing the slider.
borderwidth
Sets the width (in px) of the border enclosing the
slider.
currentvalue
:class:`plotly.graph_objects.layout.slider.Currentvalue
` instance or dict with compatible properties
font
Sets the font of the slider step labels.
len
Sets the length of the slider This measure excludes the
padding of both ends. That is, the slider's length is
this length minus the padding on both ends.
lenmode
Determines whether this slider length is set in units
of plot "fraction" or in *pixels. Use `len` to set the
value.
minorticklen
Sets the length in pixels of minor step tick marks
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
pad
Set the padding of the slider component along each
side.
steps
A tuple of
:class:`plotly.graph_objects.layout.slider.Step`
instances or dicts with compatible properties
stepdefaults
When used in a template (as
layout.template.layout.slider.stepdefaults), sets the
default property values to use for elements of
layout.slider.steps
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
tickcolor
Sets the color of the border enclosing the slider.
ticklen
Sets the length in pixels of step tick marks
tickwidth
Sets the tick width (in px).
transition
:class:`plotly.graph_objects.layout.slider.Transition`
instance or dict with compatible properties
visible
Determines whether or not the slider is visible.
x
Sets the x position (in normalized coordinates) of the
slider.
xanchor
Sets the slider's horizontal position anchor. This
anchor binds the `x` position to the "left", "center"
or "right" of the range selector.
y
Sets the y position (in normalized coordinates) of the
slider.
yanchor
Sets the slider's vertical position anchor This anchor
binds the `y` position to the "top", "middle" or
"bottom" of the range selector.
Returns
-------
Slider
"""
super(Slider, self).__init__("sliders")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.layout.Slider
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.Slider`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("active", None)
_v = active if active is not None else _v
if _v is not None:
self["active"] = _v
_v = arg.pop("activebgcolor", None)
_v = activebgcolor if activebgcolor is not None else _v
if _v is not None:
self["activebgcolor"] = _v
_v = arg.pop("bgcolor", None)
_v = bgcolor if bgcolor is not None else _v
if _v is not None:
self["bgcolor"] = _v
_v = arg.pop("bordercolor", None)
_v = bordercolor if bordercolor is not None else _v
if _v is not None:
self["bordercolor"] = _v
_v = arg.pop("borderwidth", None)
_v = borderwidth if borderwidth is not None else _v
if _v is not None:
self["borderwidth"] = _v
_v = arg.pop("currentvalue", None)
_v = currentvalue if currentvalue is not None else _v
if _v is not None:
self["currentvalue"] = _v
_v = arg.pop("font", None)
_v = font if font is not None else _v
if _v is not None:
self["font"] = _v
_v = arg.pop("len", None)
_v = len if len is not None else _v
if _v is not None:
self["len"] = _v
_v = arg.pop("lenmode", None)
_v = lenmode if lenmode is not None else _v
if _v is not None:
self["lenmode"] = _v
_v = arg.pop("minorticklen", None)
_v = minorticklen if minorticklen is not None else _v
if _v is not None:
self["minorticklen"] = _v
_v = arg.pop("name", None)
_v = name if name is not None else _v
if _v is not None:
self["name"] = _v
_v = arg.pop("pad", None)
_v = pad if pad is not None else _v
if _v is not None:
self["pad"] = _v
_v = arg.pop("steps", None)
_v = steps if steps is not None else _v
if _v is not None:
self["steps"] = _v
_v = arg.pop("stepdefaults", None)
_v = stepdefaults if stepdefaults is not None else _v
if _v is not None:
self["stepdefaults"] = _v
_v = arg.pop("templateitemname", None)
_v = templateitemname if templateitemname is not None else _v
if _v is not None:
self["templateitemname"] = _v
_v = arg.pop("tickcolor", None)
_v = tickcolor if tickcolor is not None else _v
if _v is not None:
self["tickcolor"] = _v
_v = arg.pop("ticklen", None)
_v = ticklen if ticklen is not None else _v
if _v is not None:
self["ticklen"] = _v
_v = arg.pop("tickwidth", None)
_v = tickwidth if tickwidth is not None else _v
if _v is not None:
self["tickwidth"] = _v
_v = arg.pop("transition", None)
_v = transition if transition is not None else _v
if _v is not None:
self["transition"] = _v
_v = arg.pop("visible", None)
_v = visible if visible is not None else _v
if _v is not None:
self["visible"] = _v
_v = arg.pop("x", None)
_v = x if x is not None else _v
if _v is not None:
self["x"] = _v
_v = arg.pop("xanchor", None)
_v = xanchor if xanchor is not None else _v
if _v is not None:
self["xanchor"] = _v
_v = arg.pop("y", None)
_v = y if y is not None else _v
if _v is not None:
self["y"] = _v
_v = arg.pop("yanchor", None)
_v = yanchor if yanchor is not None else _v
if _v is not None:
self["yanchor"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| _slider.Slider.__init__ |
plotly.py | 50 | packages/python/plotly/plotly/graph_objs/_splom.py | def __init__(
self,
arg=None,
customdata=None,
customdatasrc=None,
diagonal=None,
dimensions=None,
dimensiondefaults=None,
hoverinfo=None,
hoverinfosrc=None,
hoverlabel=None,
hovertemplate=None,
hovertemplatesrc=None,
hovertext=None,
hovertextsrc=None,
ids=None,
idssrc=None,
legend=None,
legendgroup=None,
legendgrouptitle=None,
legendrank=None,
legendwidth=None,
marker=None,
meta=None,
metasrc=None,
name=None,
opacity=None,
selected=None,
selectedpoints=None,
showlegend=None,
showlowerhalf=None,
showupperhalf=None,
stream=None,
text=None,
textsrc=None,
uid=None,
uirevision=None,
unselected=None,
visible=None,
xaxes=None,
xhoverformat=None,
yaxes=None,
yhoverformat=None,
**kwargs,
):
"""
Construct a new Splom object
Splom traces generate scatter plot matrix visualizations. Each
splom `dimensions` items correspond to a generated axis. Values
for each of those dimensions are set in `dimensions[i].values`.
Splom traces support all `scattergl` marker style attributes.
Specify `layout.grid` attributes and/or layout x-axis and
y-axis attributes for more control over the axis positioning
and style.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.Splom`
customdata
Assigns extra data each datum. This may be useful when
listening to hover, click and selection events. Note
that, "scatter" traces also appends customdata items in
the markers DOM elements
customdatasrc
Sets the source reference on Chart Studio Cloud for
`customdata`.
diagonal
:class:`plotly.graph_objects.splom.Diagonal` instance
or dict with compatible properties
dimensions
A tuple of
:class:`plotly.graph_objects.splom.Dimension` instances
or dicts with compatible properties
dimensiondefaults
When used in a template (as
layout.template.data.splom.dimensiondefaults), sets the
default property values to use for elements of
splom.dimensions
hoverinfo
Determines which trace information appear on hover. If
`none` or `skip` are set, no information is displayed
upon hovering. But, if `none` is set, click and hover
events are still fired.
hoverinfosrc
Sets the source reference on Chart Studio Cloud for
`hoverinfo`.
hoverlabel
:class:`plotly.graph_objects.splom.Hoverlabel` instance
or dict with compatible properties
hovertemplate
Template string used for rendering the information that
appear on hover box. Note that this will override
`hoverinfo`. Variables are inserted using %{variable},
for example "y: %{y}" as well as %{xother}, {%_xother},
{%_xother_}, {%xother_}. When showing info for several
points, "xother" will be added to those with different
x positions from the first point. An underscore before
or after "(x|y)other" will add a space on that side,
only when this field is shown. Numbers are formatted
using d3-format's syntax %{variable:d3-format}, for
example "Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. The variables available in
`hovertemplate` are the ones emitted as event data
described at this link
https://plotly.com/javascript/plotlyjs-events/#event-
data. Additionally, every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Anything contained in tag `<extra>` is
displayed in the secondary box, for example
"<extra>{fullData.name}</extra>". To hide the secondary
box completely, use an empty tag `<extra></extra>`.
hovertemplatesrc
Sets the source reference on Chart Studio Cloud for
`hovertemplate`.
hovertext
Same as `text`.
hovertextsrc
Sets the source reference on Chart Studio Cloud for
`hovertext`.
ids
Assigns id labels to each datum. These ids for object
constancy of data points during animation. Should be an
array of strings, not numbers or any other type.
idssrc
Sets the source reference on Chart Studio Cloud for
`ids`.
legend
Sets the reference to a legend to show this trace in.
References to these legends are "legend", "legend2",
"legend3", etc. Settings for these legends are set in
the layout, under `layout.legend`, `layout.legend2`,
etc.
legendgroup
Sets the legend group for this trace. Traces and shapes
part of the same legend group hide/show at the same
time when toggling legend items.
legendgrouptitle
:class:`plotly.graph_objects.splom.Legendgrouptitle`
instance or dict with compatible properties
legendrank
Sets the legend rank for this trace. Items and groups
with smaller ranks are presented on top/left side while
with "reversed" `legend.traceorder` they are on
bottom/right side. The default legendrank is 1000, so
that you can use ranks less than 1000 to place certain
items before all unranked items, and ranks greater than
1000 to go after all unranked items. When having
unranked or equal rank items shapes would be displayed
after traces i.e. according to their order in data and
layout.
legendwidth
Sets the width (in px or fraction) of the legend for
this trace.
marker
:class:`plotly.graph_objects.splom.Marker` instance or
dict with compatible properties
meta
Assigns extra meta information associated with this
trace that can be used in various text attributes.
Attributes such as trace `name`, graph, axis and
colorbar `title.text`, annotation `text`
`rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta`
values in an attribute in the same trace, simply use
`%{meta[i]}` where `i` is the index or key of the
`meta` item in question. To access trace `meta` in
layout attributes, use `%{data[n[.meta[i]}` where `i`
is the index or key of the `meta` and `n` is the trace
index.
metasrc
Sets the source reference on Chart Studio Cloud for
`meta`.
name
Sets the trace name. The trace name appears as the
legend item and on hover.
opacity
Sets the opacity of the trace.
selected
:class:`plotly.graph_objects.splom.Selected` instance
or dict with compatible properties
selectedpoints
Array containing integer indices of selected points.
Has an effect only for traces that support selections.
Note that an empty array means an empty selection where
the `unselected` are turned on for all points, whereas,
any other non-array values means no selection all where
the `selected` and `unselected` styles have no effect.
showlegend
Determines whether or not an item corresponding to this
trace is shown in the legend.
showlowerhalf
Determines whether or not subplots on the lower half
from the diagonal are displayed.
showupperhalf
Determines whether or not subplots on the upper half
from the diagonal are displayed.
stream
:class:`plotly.graph_objects.splom.Stream` instance or
dict with compatible properties
text
Sets text elements associated with each (x,y) pair to
appear on hover. If a single string, the same string
appears over all the data points. If an array of
string, the items are mapped in order to the this
trace's (x,y) coordinates.
textsrc
Sets the source reference on Chart Studio Cloud for
`text`.
uid
Assign an id to this trace, Use this to provide object
constancy between traces during animations and
transitions.
uirevision
Controls persistence of some user-driven changes to the
trace: `constraintrange` in `parcoords` traces, as well
as some `editable: true` modifications such as `name`
and `colorbar.title`. Defaults to `layout.uirevision`.
Note that other user-driven trace attribute changes are
controlled by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
unselected
:class:`plotly.graph_objects.splom.Unselected` instance
or dict with compatible properties
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
xaxes
Sets the list of x axes corresponding to dimensions of
this splom trace. By default, a splom will match the
first N xaxes where N is the number of input
dimensions. Note that, in case where `diagonal.visible`
is false and `showupperhalf` or `showlowerhalf` is
false, this splom trace will generate one less x-axis
and one less y-axis.
xhoverformat
Sets the hover text formatting rulefor `x` using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display *09~15~23.46*By default the values are
formatted using `xaxis.hoverformat`.
yaxes
Sets the list of y axes corresponding to dimensions of
this splom trace. By default, a splom will match the
first N yaxes where N is the number of input
dimensions. Note that, in case where `diagonal.visible`
is false and `showupperhalf` or `showlowerhalf` is
false, this splom trace will generate one less x-axis
and one less y-axis.
yhoverformat
Sets the hover text formatting rulefor `y` using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display *09~15~23.46*By default the values are
formatted using `yaxis.hoverformat`.
Returns
-------
Splom
"""
| /usr/src/app/target_test_cases/failed_tests__splom.Splom.__init__.txt | def __init__(
self,
arg=None,
customdata=None,
customdatasrc=None,
diagonal=None,
dimensions=None,
dimensiondefaults=None,
hoverinfo=None,
hoverinfosrc=None,
hoverlabel=None,
hovertemplate=None,
hovertemplatesrc=None,
hovertext=None,
hovertextsrc=None,
ids=None,
idssrc=None,
legend=None,
legendgroup=None,
legendgrouptitle=None,
legendrank=None,
legendwidth=None,
marker=None,
meta=None,
metasrc=None,
name=None,
opacity=None,
selected=None,
selectedpoints=None,
showlegend=None,
showlowerhalf=None,
showupperhalf=None,
stream=None,
text=None,
textsrc=None,
uid=None,
uirevision=None,
unselected=None,
visible=None,
xaxes=None,
xhoverformat=None,
yaxes=None,
yhoverformat=None,
**kwargs,
):
"""
Construct a new Splom object
Splom traces generate scatter plot matrix visualizations. Each
splom `dimensions` items correspond to a generated axis. Values
for each of those dimensions are set in `dimensions[i].values`.
Splom traces support all `scattergl` marker style attributes.
Specify `layout.grid` attributes and/or layout x-axis and
y-axis attributes for more control over the axis positioning
and style.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.Splom`
customdata
Assigns extra data each datum. This may be useful when
listening to hover, click and selection events. Note
that, "scatter" traces also appends customdata items in
the markers DOM elements
customdatasrc
Sets the source reference on Chart Studio Cloud for
`customdata`.
diagonal
:class:`plotly.graph_objects.splom.Diagonal` instance
or dict with compatible properties
dimensions
A tuple of
:class:`plotly.graph_objects.splom.Dimension` instances
or dicts with compatible properties
dimensiondefaults
When used in a template (as
layout.template.data.splom.dimensiondefaults), sets the
default property values to use for elements of
splom.dimensions
hoverinfo
Determines which trace information appear on hover. If
`none` or `skip` are set, no information is displayed
upon hovering. But, if `none` is set, click and hover
events are still fired.
hoverinfosrc
Sets the source reference on Chart Studio Cloud for
`hoverinfo`.
hoverlabel
:class:`plotly.graph_objects.splom.Hoverlabel` instance
or dict with compatible properties
hovertemplate
Template string used for rendering the information that
appear on hover box. Note that this will override
`hoverinfo`. Variables are inserted using %{variable},
for example "y: %{y}" as well as %{xother}, {%_xother},
{%_xother_}, {%xother_}. When showing info for several
points, "xother" will be added to those with different
x positions from the first point. An underscore before
or after "(x|y)other" will add a space on that side,
only when this field is shown. Numbers are formatted
using d3-format's syntax %{variable:d3-format}, for
example "Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. The variables available in
`hovertemplate` are the ones emitted as event data
described at this link
https://plotly.com/javascript/plotlyjs-events/#event-
data. Additionally, every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Anything contained in tag `<extra>` is
displayed in the secondary box, for example
"<extra>{fullData.name}</extra>". To hide the secondary
box completely, use an empty tag `<extra></extra>`.
hovertemplatesrc
Sets the source reference on Chart Studio Cloud for
`hovertemplate`.
hovertext
Same as `text`.
hovertextsrc
Sets the source reference on Chart Studio Cloud for
`hovertext`.
ids
Assigns id labels to each datum. These ids for object
constancy of data points during animation. Should be an
array of strings, not numbers or any other type.
idssrc
Sets the source reference on Chart Studio Cloud for
`ids`.
legend
Sets the reference to a legend to show this trace in.
References to these legends are "legend", "legend2",
"legend3", etc. Settings for these legends are set in
the layout, under `layout.legend`, `layout.legend2`,
etc.
legendgroup
Sets the legend group for this trace. Traces and shapes
part of the same legend group hide/show at the same
time when toggling legend items.
legendgrouptitle
:class:`plotly.graph_objects.splom.Legendgrouptitle`
instance or dict with compatible properties
legendrank
Sets the legend rank for this trace. Items and groups
with smaller ranks are presented on top/left side while
with "reversed" `legend.traceorder` they are on
bottom/right side. The default legendrank is 1000, so
that you can use ranks less than 1000 to place certain
items before all unranked items, and ranks greater than
1000 to go after all unranked items. When having
unranked or equal rank items shapes would be displayed
after traces i.e. according to their order in data and
layout.
legendwidth
Sets the width (in px or fraction) of the legend for
this trace.
marker
:class:`plotly.graph_objects.splom.Marker` instance or
dict with compatible properties
meta
Assigns extra meta information associated with this
trace that can be used in various text attributes.
Attributes such as trace `name`, graph, axis and
colorbar `title.text`, annotation `text`
`rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta`
values in an attribute in the same trace, simply use
`%{meta[i]}` where `i` is the index or key of the
`meta` item in question. To access trace `meta` in
layout attributes, use `%{data[n[.meta[i]}` where `i`
is the index or key of the `meta` and `n` is the trace
index.
metasrc
Sets the source reference on Chart Studio Cloud for
`meta`.
name
Sets the trace name. The trace name appears as the
legend item and on hover.
opacity
Sets the opacity of the trace.
selected
:class:`plotly.graph_objects.splom.Selected` instance
or dict with compatible properties
selectedpoints
Array containing integer indices of selected points.
Has an effect only for traces that support selections.
Note that an empty array means an empty selection where
the `unselected` are turned on for all points, whereas,
any other non-array values means no selection all where
the `selected` and `unselected` styles have no effect.
showlegend
Determines whether or not an item corresponding to this
trace is shown in the legend.
showlowerhalf
Determines whether or not subplots on the lower half
from the diagonal are displayed.
showupperhalf
Determines whether or not subplots on the upper half
from the diagonal are displayed.
stream
:class:`plotly.graph_objects.splom.Stream` instance or
dict with compatible properties
text
Sets text elements associated with each (x,y) pair to
appear on hover. If a single string, the same string
appears over all the data points. If an array of
string, the items are mapped in order to the this
trace's (x,y) coordinates.
textsrc
Sets the source reference on Chart Studio Cloud for
`text`.
uid
Assign an id to this trace, Use this to provide object
constancy between traces during animations and
transitions.
uirevision
Controls persistence of some user-driven changes to the
trace: `constraintrange` in `parcoords` traces, as well
as some `editable: true` modifications such as `name`
and `colorbar.title`. Defaults to `layout.uirevision`.
Note that other user-driven trace attribute changes are
controlled by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
unselected
:class:`plotly.graph_objects.splom.Unselected` instance
or dict with compatible properties
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
xaxes
Sets the list of x axes corresponding to dimensions of
this splom trace. By default, a splom will match the
first N xaxes where N is the number of input
dimensions. Note that, in case where `diagonal.visible`
is false and `showupperhalf` or `showlowerhalf` is
false, this splom trace will generate one less x-axis
and one less y-axis.
xhoverformat
Sets the hover text formatting rulefor `x` using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display *09~15~23.46*By default the values are
formatted using `xaxis.hoverformat`.
yaxes
Sets the list of y axes corresponding to dimensions of
this splom trace. By default, a splom will match the
first N yaxes where N is the number of input
dimensions. Note that, in case where `diagonal.visible`
is false and `showupperhalf` or `showlowerhalf` is
false, this splom trace will generate one less x-axis
and one less y-axis.
yhoverformat
Sets the hover text formatting rulefor `y` using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display *09~15~23.46*By default the values are
formatted using `yaxis.hoverformat`.
Returns
-------
Splom
"""
super(Splom, self).__init__("splom")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.Splom
constructor must be a dict or
an instance of :class:`plotly.graph_objs.Splom`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("customdata", None)
_v = customdata if customdata is not None else _v
if _v is not None:
self["customdata"] = _v
_v = arg.pop("customdatasrc", None)
_v = customdatasrc if customdatasrc is not None else _v
if _v is not None:
self["customdatasrc"] = _v
_v = arg.pop("diagonal", None)
_v = diagonal if diagonal is not None else _v
if _v is not None:
self["diagonal"] = _v
_v = arg.pop("dimensions", None)
_v = dimensions if dimensions is not None else _v
if _v is not None:
self["dimensions"] = _v
_v = arg.pop("dimensiondefaults", None)
_v = dimensiondefaults if dimensiondefaults is not None else _v
if _v is not None:
self["dimensiondefaults"] = _v
_v = arg.pop("hoverinfo", None)
_v = hoverinfo if hoverinfo is not None else _v
if _v is not None:
self["hoverinfo"] = _v
_v = arg.pop("hoverinfosrc", None)
_v = hoverinfosrc if hoverinfosrc is not None else _v
if _v is not None:
self["hoverinfosrc"] = _v
_v = arg.pop("hoverlabel", None)
_v = hoverlabel if hoverlabel is not None else _v
if _v is not None:
self["hoverlabel"] = _v
_v = arg.pop("hovertemplate", None)
_v = hovertemplate if hovertemplate is not None else _v
if _v is not None:
self["hovertemplate"] = _v
_v = arg.pop("hovertemplatesrc", None)
_v = hovertemplatesrc if hovertemplatesrc is not None else _v
if _v is not None:
self["hovertemplatesrc"] = _v
_v = arg.pop("hovertext", None)
_v = hovertext if hovertext is not None else _v
if _v is not None:
self["hovertext"] = _v
_v = arg.pop("hovertextsrc", None)
_v = hovertextsrc if hovertextsrc is not None else _v
if _v is not None:
self["hovertextsrc"] = _v
_v = arg.pop("ids", None)
_v = ids if ids is not None else _v
if _v is not None:
self["ids"] = _v
_v = arg.pop("idssrc", None)
_v = idssrc if idssrc is not None else _v
if _v is not None:
self["idssrc"] = _v
_v = arg.pop("legend", None)
_v = legend if legend is not None else _v
if _v is not None:
self["legend"] = _v
_v = arg.pop("legendgroup", None)
_v = legendgroup if legendgroup is not None else _v
if _v is not None:
self["legendgroup"] = _v
_v = arg.pop("legendgrouptitle", None)
_v = legendgrouptitle if legendgrouptitle is not None else _v
if _v is not None:
self["legendgrouptitle"] = _v
_v = arg.pop("legendrank", None)
_v = legendrank if legendrank is not None else _v
if _v is not None:
self["legendrank"] = _v
_v = arg.pop("legendwidth", None)
_v = legendwidth if legendwidth is not None else _v
if _v is not None:
self["legendwidth"] = _v
_v = arg.pop("marker", None)
_v = marker if marker is not None else _v
if _v is not None:
self["marker"] = _v
_v = arg.pop("meta", None)
_v = meta if meta is not None else _v
if _v is not None:
self["meta"] = _v
_v = arg.pop("metasrc", None)
_v = metasrc if metasrc is not None else _v
if _v is not None:
self["metasrc"] = _v
_v = arg.pop("name", None)
_v = name if name is not None else _v
if _v is not None:
self["name"] = _v
_v = arg.pop("opacity", None)
_v = opacity if opacity is not None else _v
if _v is not None:
self["opacity"] = _v
_v = arg.pop("selected", None)
_v = selected if selected is not None else _v
if _v is not None:
self["selected"] = _v
_v = arg.pop("selectedpoints", None)
_v = selectedpoints if selectedpoints is not None else _v
if _v is not None:
self["selectedpoints"] = _v
_v = arg.pop("showlegend", None)
_v = showlegend if showlegend is not None else _v
if _v is not None:
self["showlegend"] = _v
_v = arg.pop("showlowerhalf", None)
_v = showlowerhalf if showlowerhalf is not None else _v
if _v is not None:
self["showlowerhalf"] = _v
_v = arg.pop("showupperhalf", None)
_v = showupperhalf if showupperhalf is not None else _v
if _v is not None:
self["showupperhalf"] = _v
_v = arg.pop("stream", None)
_v = stream if stream is not None else _v
if _v is not None:
self["stream"] = _v
_v = arg.pop("text", None)
_v = text if text is not None else _v
if _v is not None:
self["text"] = _v
_v = arg.pop("textsrc", None)
_v = textsrc if textsrc is not None else _v
if _v is not None:
self["textsrc"] = _v
_v = arg.pop("uid", None)
_v = uid if uid is not None else _v
if _v is not None:
self["uid"] = _v
_v = arg.pop("uirevision", None)
_v = uirevision if uirevision is not None else _v
if _v is not None:
self["uirevision"] = _v
_v = arg.pop("unselected", None)
_v = unselected if unselected is not None else _v
if _v is not None:
self["unselected"] = _v
_v = arg.pop("visible", None)
_v = visible if visible is not None else _v
if _v is not None:
self["visible"] = _v
_v = arg.pop("xaxes", None)
_v = xaxes if xaxes is not None else _v
if _v is not None:
self["xaxes"] = _v
_v = arg.pop("xhoverformat", None)
_v = xhoverformat if xhoverformat is not None else _v
if _v is not None:
self["xhoverformat"] = _v
_v = arg.pop("yaxes", None)
_v = yaxes if yaxes is not None else _v
if _v is not None:
self["yaxes"] = _v
_v = arg.pop("yhoverformat", None)
_v = yhoverformat if yhoverformat is not None else _v
if _v is not None:
self["yhoverformat"] = _v
# Read-only literals
# ------------------
self._props["type"] = "splom"
arg.pop("type", None)
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| _splom.Splom.__init__ |
plotly.py | 51 | packages/python/plotly/plotly/graph_objs/_splom.py | def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.splom.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Supported dict properties:
angle
Sets the marker angle in respect to `angleref`.
anglesrc
Sets the source reference on Chart Studio Cloud
for `angle`.
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.colorscale`. Has an
effect only if in `marker.color` is set to a
numerical array. In case `colorscale` is
unspecified or `autocolorscale` is true, the
default palette will be chosen according to
whether numbers in the `color` array are all
positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `marker.color`) or the bounds set in
`marker.cmin` and `marker.cmax` Has an effect
only if in `marker.color` is set to a numerical
array. Defaults to `false` when `marker.cmin`
and `marker.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `marker.cmin` and/or `marker.cmax` to
be equidistant to this point. Has an effect
only if in `marker.color` is set to a numerical
array. Value should have the same units as in
`marker.color`. Has no effect when
`marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmax` must be set as well.
color
Sets the marker color. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`marker.cmin` and `marker.cmax` if set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.splom.marker.Color
Bar` instance or dict with compatible
properties
colorscale
Sets the colorscale. Has an effect only if in
`marker.color` is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `marker.cmin` and
`marker.cmax`. Alternatively, `colorscale` may
be a palette name string of the following list:
Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud
for `color`.
line
:class:`plotly.graph_objects.splom.marker.Line`
instance or dict with compatible properties
opacity
Sets the marker opacity.
opacitysrc
Sets the source reference on Chart Studio Cloud
for `opacity`.
reversescale
Reverses the color mapping if true. Has an
effect only if in `marker.color` is set to a
numerical array. If true, `marker.cmin` will
correspond to the last color in the array and
`marker.cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
in `marker.color` is set to a numerical array.
size
Sets the marker size (in px).
sizemin
Has an effect only if `marker.size` is set to a
numerical array. Sets the minimum size (in px)
of the rendered marker points.
sizemode
Has an effect only if `marker.size` is set to a
numerical array. Sets the rule for which the
data in `size` is converted to pixels.
sizeref
Has an effect only if `marker.size` is set to a
numerical array. Sets the scale factor used to
determine the rendered size of marker points.
Use with `sizemin` and `sizemode`.
sizesrc
Sets the source reference on Chart Studio Cloud
for `size`.
symbol
Sets the marker symbol type. Adding 100 is
equivalent to appending "-open" to a symbol
name. Adding 200 is equivalent to appending
"-dot" to a symbol name. Adding 300 is
equivalent to appending "-open-dot" or "dot-
open" to a symbol name.
symbolsrc
Sets the source reference on Chart Studio Cloud
for `symbol`.
Returns
-------
plotly.graph_objs.splom.Marker
"""
| /usr/src/app/target_test_cases/failed_tests__splom.marker.txt | def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.splom.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Supported dict properties:
angle
Sets the marker angle in respect to `angleref`.
anglesrc
Sets the source reference on Chart Studio Cloud
for `angle`.
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.colorscale`. Has an
effect only if in `marker.color` is set to a
numerical array. In case `colorscale` is
unspecified or `autocolorscale` is true, the
default palette will be chosen according to
whether numbers in the `color` array are all
positive, all negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
in `marker.color`) or the bounds set in
`marker.cmin` and `marker.cmax` Has an effect
only if in `marker.color` is set to a numerical
array. Defaults to `false` when `marker.cmin`
and `marker.cmax` are set by the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmin` must be set as well.
cmid
Sets the mid-point of the color domain by
scaling `marker.cmin` and/or `marker.cmax` to
be equidistant to this point. Has an effect
only if in `marker.color` is set to a numerical
array. Value should have the same units as in
`marker.color`. Has no effect when
`marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if in `marker.color` is set to a
numerical array. Value should have the same
units as in `marker.color` and if set,
`marker.cmax` must be set as well.
color
Sets the marker color. It accepts either a
specific color or an array of numbers that are
mapped to the colorscale relative to the max
and min values of the array or relative to
`marker.cmin` and `marker.cmax` if set.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.splom.marker.Color
Bar` instance or dict with compatible
properties
colorscale
Sets the colorscale. Has an effect only if in
`marker.color` is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `marker.cmin` and
`marker.cmax`. Alternatively, `colorscale` may
be a palette name string of the following list:
Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorsrc
Sets the source reference on Chart Studio Cloud
for `color`.
line
:class:`plotly.graph_objects.splom.marker.Line`
instance or dict with compatible properties
opacity
Sets the marker opacity.
opacitysrc
Sets the source reference on Chart Studio Cloud
for `opacity`.
reversescale
Reverses the color mapping if true. Has an
effect only if in `marker.color` is set to a
numerical array. If true, `marker.cmin` will
correspond to the last color in the array and
`marker.cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
in `marker.color` is set to a numerical array.
size
Sets the marker size (in px).
sizemin
Has an effect only if `marker.size` is set to a
numerical array. Sets the minimum size (in px)
of the rendered marker points.
sizemode
Has an effect only if `marker.size` is set to a
numerical array. Sets the rule for which the
data in `size` is converted to pixels.
sizeref
Has an effect only if `marker.size` is set to a
numerical array. Sets the scale factor used to
determine the rendered size of marker points.
Use with `sizemin` and `sizemode`.
sizesrc
Sets the source reference on Chart Studio Cloud
for `size`.
symbol
Sets the marker symbol type. Adding 100 is
equivalent to appending "-open" to a symbol
name. Adding 200 is equivalent to appending
"-dot" to a symbol name. Adding 300 is
equivalent to appending "-open-dot" or "dot-
open" to a symbol name.
symbolsrc
Sets the source reference on Chart Studio Cloud
for `symbol`.
Returns
-------
plotly.graph_objs.splom.Marker
"""
return self["marker"]
| _splom.marker |
plotly.py | 52 | packages/python/plotly/plotly/_subplots.py | def make_subplots(
rows=1,
cols=1,
shared_xaxes=False,
shared_yaxes=False,
start_cell="top-left",
print_grid=False,
horizontal_spacing=None,
vertical_spacing=None,
subplot_titles=None,
column_widths=None,
row_heights=None,
specs=None,
insets=None,
column_titles=None,
row_titles=None,
x_title=None,
y_title=None,
figure=None,
**kwargs,
):
"""
Return an instance of plotly.graph_objs.Figure with predefined subplots
configured in 'layout'.
Parameters
----------
rows: int (default 1)
Number of rows in the subplot grid. Must be greater than zero.
cols: int (default 1)
Number of columns in the subplot grid. Must be greater than zero.
shared_xaxes: boolean or str (default False)
Assign shared (linked) x-axes for 2D cartesian subplots
- True or 'columns': Share axes among subplots in the same column
- 'rows': Share axes among subplots in the same row
- 'all': Share axes across all subplots in the grid.
shared_yaxes: boolean or str (default False)
Assign shared (linked) y-axes for 2D cartesian subplots
- 'columns': Share axes among subplots in the same column
- True or 'rows': Share axes among subplots in the same row
- 'all': Share axes across all subplots in the grid.
start_cell: 'bottom-left' or 'top-left' (default 'top-left')
Choose the starting cell in the subplot grid used to set the
domains_grid of the subplots.
- 'top-left': Subplots are numbered with (1, 1) in the top
left corner
- 'bottom-left': Subplots are numbererd with (1, 1) in the bottom
left corner
print_grid: boolean (default True):
If True, prints a string representation of the plot grid. Grid may
also be printed using the `Figure.print_grid()` method on the
resulting figure.
horizontal_spacing: float (default 0.2 / cols)
Space between subplot columns in normalized plot coordinates. Must be
a float between 0 and 1.
Applies to all columns (use 'specs' subplot-dependents spacing)
vertical_spacing: float (default 0.3 / rows)
Space between subplot rows in normalized plot coordinates. Must be
a float between 0 and 1.
Applies to all rows (use 'specs' subplot-dependents spacing)
subplot_titles: list of str or None (default None)
Title of each subplot as a list in row-major ordering.
Empty strings ("") can be included in the list if no subplot title
is desired in that space so that the titles are properly indexed.
specs: list of lists of dict or None (default None)
Per subplot specifications of subplot type, row/column spanning, and
spacing.
ex1: specs=[[{}, {}], [{'colspan': 2}, None]]
ex2: specs=[[{'rowspan': 2}, {}], [None, {}]]
- Indices of the outer list correspond to subplot grid rows
starting from the top, if start_cell='top-left',
or bottom, if start_cell='bottom-left'.
The number of rows in 'specs' must be equal to 'rows'.
- Indices of the inner lists correspond to subplot grid columns
starting from the left. The number of columns in 'specs'
must be equal to 'cols'.
- Each item in the 'specs' list corresponds to one subplot
in a subplot grid. (N.B. The subplot grid has exactly 'rows'
times 'cols' cells.)
- Use None for a blank a subplot cell (or to move past a col/row span).
- Note that specs[0][0] has the specs of the 'start_cell' subplot.
- Each item in 'specs' is a dictionary.
The available keys are:
* type (string, default 'xy'): Subplot type. One of
- 'xy': 2D Cartesian subplot type for scatter, bar, etc.
- 'scene': 3D Cartesian subplot for scatter3d, cone, etc.
- 'polar': Polar subplot for scatterpolar, barpolar, etc.
- 'ternary': Ternary subplot for scatterternary
- 'map': Map subplot for scattermap, choroplethmap and densitymap
- 'mapbox': Mapbox subplot for scattermapbox, choroplethmapbox and densitymapbox
- 'domain': Subplot type for traces that are individually
positioned. pie, parcoords, parcats, etc.
- trace type: A trace type which will be used to determine
the appropriate subplot type for that trace
* secondary_y (bool, default False): If True, create a secondary
y-axis positioned on the right side of the subplot. Only valid
if type='xy'.
* colspan (int, default 1): number of subplot columns
for this subplot to span.
* rowspan (int, default 1): number of subplot rows
for this subplot to span.
* l (float, default 0.0): padding left of cell
* r (float, default 0.0): padding right of cell
* t (float, default 0.0): padding right of cell
* b (float, default 0.0): padding bottom of cell
- Note: Use 'horizontal_spacing' and 'vertical_spacing' to adjust
the spacing in between the subplots.
insets: list of dict or None (default None):
Inset specifications. Insets are subplots that overlay grid subplots
- Each item in 'insets' is a dictionary.
The available keys are:
* cell (tuple, default=(1,1)): (row, col) index of the
subplot cell to overlay inset axes onto.
* type (string, default 'xy'): Subplot type
* l (float, default=0.0): padding left of inset
in fraction of cell width
* w (float or 'to_end', default='to_end') inset width
in fraction of cell width ('to_end': to cell right edge)
* b (float, default=0.0): padding bottom of inset
in fraction of cell height
* h (float or 'to_end', default='to_end') inset height
in fraction of cell height ('to_end': to cell top edge)
column_widths: list of numbers or None (default None)
list of length `cols` of the relative widths of each column of subplots.
Values are normalized internally and used to distribute overall width
of the figure (excluding padding) among the columns.
For backward compatibility, may also be specified using the
`column_width` keyword argument.
row_heights: list of numbers or None (default None)
list of length `rows` of the relative heights of each row of subplots.
If start_cell='top-left' then row heights are applied top to bottom.
Otherwise, if start_cell='bottom-left' then row heights are applied
bottom to top.
For backward compatibility, may also be specified using the
`row_width` kwarg. If specified as `row_width`, then the width values
are applied from bottom to top regardless of the value of start_cell.
This matches the legacy behavior of the `row_width` argument.
column_titles: list of str or None (default None)
list of length `cols` of titles to place above the top subplot in
each column.
row_titles: list of str or None (default None)
list of length `rows` of titles to place on the right side of each
row of subplots. If start_cell='top-left' then row titles are
applied top to bottom. Otherwise, if start_cell='bottom-left' then
row titles are applied bottom to top.
x_title: str or None (default None)
Title to place below the bottom row of subplots,
centered horizontally
y_title: str or None (default None)
Title to place to the left of the left column of subplots,
centered vertically
figure: go.Figure or None (default None)
If None, a new go.Figure instance will be created and its axes will be
populated with those corresponding to the requested subplot geometry and
this new figure will be returned.
If a go.Figure instance, the axes will be added to the
layout of this figure and this figure will be returned. If the figure
already contains axes, they will be overwritten.
Examples
--------
Example 1:
>>> # Stack two subplots vertically, and add a scatter trace to each
>>> from plotly.subplots import make_subplots
>>> import plotly.graph_objects as go
>>> fig = make_subplots(rows=2)
This is the format of your plot grid:
[ (1,1) xaxis1,yaxis1 ]
[ (2,1) xaxis2,yaxis2 ]
>>> fig.add_scatter(y=[2, 1, 3], row=1, col=1) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_scatter(y=[1, 3, 2], row=2, col=1) # doctest: +ELLIPSIS
Figure(...)
or see Figure.append_trace
Example 2:
>>> # Stack a scatter plot
>>> fig = make_subplots(rows=2, shared_xaxes=True)
This is the format of your plot grid:
[ (1,1) xaxis1,yaxis1 ]
[ (2,1) xaxis2,yaxis2 ]
>>> fig.add_scatter(y=[2, 1, 3], row=1, col=1) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_scatter(y=[1, 3, 2], row=2, col=1) # doctest: +ELLIPSIS
Figure(...)
Example 3:
>>> # irregular subplot layout (more examples below under 'specs')
>>> fig = make_subplots(rows=2, cols=2,
... specs=[[{}, {}],
... [{'colspan': 2}, None]])
This is the format of your plot grid:
[ (1,1) xaxis1,yaxis1 ] [ (1,2) xaxis2,yaxis2 ]
[ (2,1) xaxis3,yaxis3 - ]
>>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=1, col=1) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=1, col=2) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=2, col=1) # doctest: +ELLIPSIS
Figure(...)
Example 4:
>>> # insets
>>> fig = make_subplots(insets=[{'cell': (1,1), 'l': 0.7, 'b': 0.3}])
This is the format of your plot grid:
[ (1,1) xaxis1,yaxis1 ]
With insets:
[ xaxis2,yaxis2 ] over [ (1,1) xaxis1,yaxis1 ]
>>> fig.add_scatter(x=[1,2,3], y=[2,1,1]) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_scatter(x=[1,2,3], y=[2,1,2], xaxis='x2', yaxis='y2') # doctest: +ELLIPSIS
Figure(...)
Example 5:
>>> # include subplot titles
>>> fig = make_subplots(rows=2, subplot_titles=('Plot 1','Plot 2'))
This is the format of your plot grid:
[ (1,1) x1,y1 ]
[ (2,1) x2,y2 ]
>>> fig.add_scatter(x=[1,2,3], y=[2,1,2], row=1, col=1) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_bar(x=[1,2,3], y=[2,1,2], row=2, col=1) # doctest: +ELLIPSIS
Figure(...)
Example 6:
Subplot with mixed subplot types
>>> fig = make_subplots(rows=2, cols=2,
... specs=[[{'type': 'xy'}, {'type': 'polar'}],
... [{'type': 'scene'}, {'type': 'ternary'}]])
>>> fig.add_traces(
... [go.Scatter(y=[2, 3, 1]),
... go.Scatterpolar(r=[1, 3, 2], theta=[0, 45, 90]),
... go.Scatter3d(x=[1, 2, 1], y=[2, 3, 1], z=[0, 3, 5]),
... go.Scatterternary(a=[0.1, 0.2, 0.1],
... b=[0.2, 0.3, 0.1],
... c=[0.7, 0.5, 0.8])],
... rows=[1, 1, 2, 2],
... cols=[1, 2, 1, 2]) # doctest: +ELLIPSIS
Figure(...)
"""
| /usr/src/app/target_test_cases/failed_tests__subplots.make_subplots.txt | def make_subplots(
rows=1,
cols=1,
shared_xaxes=False,
shared_yaxes=False,
start_cell="top-left",
print_grid=False,
horizontal_spacing=None,
vertical_spacing=None,
subplot_titles=None,
column_widths=None,
row_heights=None,
specs=None,
insets=None,
column_titles=None,
row_titles=None,
x_title=None,
y_title=None,
figure=None,
**kwargs,
):
"""
Return an instance of plotly.graph_objs.Figure with predefined subplots
configured in 'layout'.
Parameters
----------
rows: int (default 1)
Number of rows in the subplot grid. Must be greater than zero.
cols: int (default 1)
Number of columns in the subplot grid. Must be greater than zero.
shared_xaxes: boolean or str (default False)
Assign shared (linked) x-axes for 2D cartesian subplots
- True or 'columns': Share axes among subplots in the same column
- 'rows': Share axes among subplots in the same row
- 'all': Share axes across all subplots in the grid.
shared_yaxes: boolean or str (default False)
Assign shared (linked) y-axes for 2D cartesian subplots
- 'columns': Share axes among subplots in the same column
- True or 'rows': Share axes among subplots in the same row
- 'all': Share axes across all subplots in the grid.
start_cell: 'bottom-left' or 'top-left' (default 'top-left')
Choose the starting cell in the subplot grid used to set the
domains_grid of the subplots.
- 'top-left': Subplots are numbered with (1, 1) in the top
left corner
- 'bottom-left': Subplots are numbererd with (1, 1) in the bottom
left corner
print_grid: boolean (default True):
If True, prints a string representation of the plot grid. Grid may
also be printed using the `Figure.print_grid()` method on the
resulting figure.
horizontal_spacing: float (default 0.2 / cols)
Space between subplot columns in normalized plot coordinates. Must be
a float between 0 and 1.
Applies to all columns (use 'specs' subplot-dependents spacing)
vertical_spacing: float (default 0.3 / rows)
Space between subplot rows in normalized plot coordinates. Must be
a float between 0 and 1.
Applies to all rows (use 'specs' subplot-dependents spacing)
subplot_titles: list of str or None (default None)
Title of each subplot as a list in row-major ordering.
Empty strings ("") can be included in the list if no subplot title
is desired in that space so that the titles are properly indexed.
specs: list of lists of dict or None (default None)
Per subplot specifications of subplot type, row/column spanning, and
spacing.
ex1: specs=[[{}, {}], [{'colspan': 2}, None]]
ex2: specs=[[{'rowspan': 2}, {}], [None, {}]]
- Indices of the outer list correspond to subplot grid rows
starting from the top, if start_cell='top-left',
or bottom, if start_cell='bottom-left'.
The number of rows in 'specs' must be equal to 'rows'.
- Indices of the inner lists correspond to subplot grid columns
starting from the left. The number of columns in 'specs'
must be equal to 'cols'.
- Each item in the 'specs' list corresponds to one subplot
in a subplot grid. (N.B. The subplot grid has exactly 'rows'
times 'cols' cells.)
- Use None for a blank a subplot cell (or to move past a col/row span).
- Note that specs[0][0] has the specs of the 'start_cell' subplot.
- Each item in 'specs' is a dictionary.
The available keys are:
* type (string, default 'xy'): Subplot type. One of
- 'xy': 2D Cartesian subplot type for scatter, bar, etc.
- 'scene': 3D Cartesian subplot for scatter3d, cone, etc.
- 'polar': Polar subplot for scatterpolar, barpolar, etc.
- 'ternary': Ternary subplot for scatterternary
- 'map': Map subplot for scattermap, choroplethmap and densitymap
- 'mapbox': Mapbox subplot for scattermapbox, choroplethmapbox and densitymapbox
- 'domain': Subplot type for traces that are individually
positioned. pie, parcoords, parcats, etc.
- trace type: A trace type which will be used to determine
the appropriate subplot type for that trace
* secondary_y (bool, default False): If True, create a secondary
y-axis positioned on the right side of the subplot. Only valid
if type='xy'.
* colspan (int, default 1): number of subplot columns
for this subplot to span.
* rowspan (int, default 1): number of subplot rows
for this subplot to span.
* l (float, default 0.0): padding left of cell
* r (float, default 0.0): padding right of cell
* t (float, default 0.0): padding right of cell
* b (float, default 0.0): padding bottom of cell
- Note: Use 'horizontal_spacing' and 'vertical_spacing' to adjust
the spacing in between the subplots.
insets: list of dict or None (default None):
Inset specifications. Insets are subplots that overlay grid subplots
- Each item in 'insets' is a dictionary.
The available keys are:
* cell (tuple, default=(1,1)): (row, col) index of the
subplot cell to overlay inset axes onto.
* type (string, default 'xy'): Subplot type
* l (float, default=0.0): padding left of inset
in fraction of cell width
* w (float or 'to_end', default='to_end') inset width
in fraction of cell width ('to_end': to cell right edge)
* b (float, default=0.0): padding bottom of inset
in fraction of cell height
* h (float or 'to_end', default='to_end') inset height
in fraction of cell height ('to_end': to cell top edge)
column_widths: list of numbers or None (default None)
list of length `cols` of the relative widths of each column of subplots.
Values are normalized internally and used to distribute overall width
of the figure (excluding padding) among the columns.
For backward compatibility, may also be specified using the
`column_width` keyword argument.
row_heights: list of numbers or None (default None)
list of length `rows` of the relative heights of each row of subplots.
If start_cell='top-left' then row heights are applied top to bottom.
Otherwise, if start_cell='bottom-left' then row heights are applied
bottom to top.
For backward compatibility, may also be specified using the
`row_width` kwarg. If specified as `row_width`, then the width values
are applied from bottom to top regardless of the value of start_cell.
This matches the legacy behavior of the `row_width` argument.
column_titles: list of str or None (default None)
list of length `cols` of titles to place above the top subplot in
each column.
row_titles: list of str or None (default None)
list of length `rows` of titles to place on the right side of each
row of subplots. If start_cell='top-left' then row titles are
applied top to bottom. Otherwise, if start_cell='bottom-left' then
row titles are applied bottom to top.
x_title: str or None (default None)
Title to place below the bottom row of subplots,
centered horizontally
y_title: str or None (default None)
Title to place to the left of the left column of subplots,
centered vertically
figure: go.Figure or None (default None)
If None, a new go.Figure instance will be created and its axes will be
populated with those corresponding to the requested subplot geometry and
this new figure will be returned.
If a go.Figure instance, the axes will be added to the
layout of this figure and this figure will be returned. If the figure
already contains axes, they will be overwritten.
Examples
--------
Example 1:
>>> # Stack two subplots vertically, and add a scatter trace to each
>>> from plotly.subplots import make_subplots
>>> import plotly.graph_objects as go
>>> fig = make_subplots(rows=2)
This is the format of your plot grid:
[ (1,1) xaxis1,yaxis1 ]
[ (2,1) xaxis2,yaxis2 ]
>>> fig.add_scatter(y=[2, 1, 3], row=1, col=1) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_scatter(y=[1, 3, 2], row=2, col=1) # doctest: +ELLIPSIS
Figure(...)
or see Figure.append_trace
Example 2:
>>> # Stack a scatter plot
>>> fig = make_subplots(rows=2, shared_xaxes=True)
This is the format of your plot grid:
[ (1,1) xaxis1,yaxis1 ]
[ (2,1) xaxis2,yaxis2 ]
>>> fig.add_scatter(y=[2, 1, 3], row=1, col=1) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_scatter(y=[1, 3, 2], row=2, col=1) # doctest: +ELLIPSIS
Figure(...)
Example 3:
>>> # irregular subplot layout (more examples below under 'specs')
>>> fig = make_subplots(rows=2, cols=2,
... specs=[[{}, {}],
... [{'colspan': 2}, None]])
This is the format of your plot grid:
[ (1,1) xaxis1,yaxis1 ] [ (1,2) xaxis2,yaxis2 ]
[ (2,1) xaxis3,yaxis3 - ]
>>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=1, col=1) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=1, col=2) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=2, col=1) # doctest: +ELLIPSIS
Figure(...)
Example 4:
>>> # insets
>>> fig = make_subplots(insets=[{'cell': (1,1), 'l': 0.7, 'b': 0.3}])
This is the format of your plot grid:
[ (1,1) xaxis1,yaxis1 ]
With insets:
[ xaxis2,yaxis2 ] over [ (1,1) xaxis1,yaxis1 ]
>>> fig.add_scatter(x=[1,2,3], y=[2,1,1]) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_scatter(x=[1,2,3], y=[2,1,2], xaxis='x2', yaxis='y2') # doctest: +ELLIPSIS
Figure(...)
Example 5:
>>> # include subplot titles
>>> fig = make_subplots(rows=2, subplot_titles=('Plot 1','Plot 2'))
This is the format of your plot grid:
[ (1,1) x1,y1 ]
[ (2,1) x2,y2 ]
>>> fig.add_scatter(x=[1,2,3], y=[2,1,2], row=1, col=1) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_bar(x=[1,2,3], y=[2,1,2], row=2, col=1) # doctest: +ELLIPSIS
Figure(...)
Example 6:
Subplot with mixed subplot types
>>> fig = make_subplots(rows=2, cols=2,
... specs=[[{'type': 'xy'}, {'type': 'polar'}],
... [{'type': 'scene'}, {'type': 'ternary'}]])
>>> fig.add_traces(
... [go.Scatter(y=[2, 3, 1]),
... go.Scatterpolar(r=[1, 3, 2], theta=[0, 45, 90]),
... go.Scatter3d(x=[1, 2, 1], y=[2, 3, 1], z=[0, 3, 5]),
... go.Scatterternary(a=[0.1, 0.2, 0.1],
... b=[0.2, 0.3, 0.1],
... c=[0.7, 0.5, 0.8])],
... rows=[1, 1, 2, 2],
... cols=[1, 2, 1, 2]) # doctest: +ELLIPSIS
Figure(...)
"""
import plotly.graph_objs as go
# Handle backward compatibility
# -----------------------------
use_legacy_row_heights_order = "row_width" in kwargs
row_heights = kwargs.pop("row_width", row_heights)
column_widths = kwargs.pop("column_width", column_widths)
if kwargs:
raise TypeError(
"make_subplots() got unexpected keyword argument(s): {}".format(
list(kwargs)
)
)
# Validate coerce inputs
# ----------------------
# ### rows ###
if not isinstance(rows, int) or rows <= 0:
raise ValueError(
"""
The 'rows' argument to make_subplots must be an int greater than 0.
Received value of type {typ}: {val}""".format(
typ=type(rows), val=repr(rows)
)
)
# ### cols ###
if not isinstance(cols, int) or cols <= 0:
raise ValueError(
"""
The 'cols' argument to make_subplots must be an int greater than 0.
Received value of type {typ}: {val}""".format(
typ=type(cols), val=repr(cols)
)
)
# ### start_cell ###
if start_cell == "bottom-left":
col_dir = 1
row_dir = 1
elif start_cell == "top-left":
col_dir = 1
row_dir = -1
else:
raise ValueError(
"""
The 'start_cell` argument to make_subplots must be one of \
['bottom-left', 'top-left']
Received value of type {typ}: {val}""".format(
typ=type(start_cell), val=repr(start_cell)
)
)
# ### Helper to validate coerce elements of lists of dictionaries ###
def _check_keys_and_fill(name, arg, defaults):
def _checks(item, defaults):
if item is None:
return
if not isinstance(item, dict):
raise ValueError(
"""
Elements of the '{name}' argument to make_subplots must be dictionaries \
or None.
Received value of type {typ}: {val}""".format(
name=name, typ=type(item), val=repr(item)
)
)
for k in item:
if k not in defaults:
raise ValueError(
"""
Invalid key specified in an element of the '{name}' argument to \
make_subplots: {k}
Valid keys include: {valid_keys}""".format(
k=repr(k), name=name, valid_keys=repr(list(defaults))
)
)
for k, v in defaults.items():
item.setdefault(k, v)
for arg_i in arg:
if isinstance(arg_i, (list, tuple)):
# 2D list
for arg_ii in arg_i:
_checks(arg_ii, defaults)
elif isinstance(arg_i, dict):
# 1D list
_checks(arg_i, defaults)
# ### specs ###
if specs is None:
specs = [[{} for c in range(cols)] for r in range(rows)]
elif not (
isinstance(specs, (list, tuple))
and specs
and all(isinstance(row, (list, tuple)) for row in specs)
and len(specs) == rows
and all(len(row) == cols for row in specs)
and all(all(v is None or isinstance(v, dict) for v in row) for row in specs)
):
raise ValueError(
"""
The 'specs' argument to make_subplots must be a 2D list of dictionaries with \
dimensions ({rows} x {cols}).
Received value of type {typ}: {val}""".format(
rows=rows, cols=cols, typ=type(specs), val=repr(specs)
)
)
for row in specs:
for spec in row:
# For backward compatibility,
# convert is_3d flag to type='scene' kwarg
if spec and spec.pop("is_3d", None):
spec["type"] = "scene"
spec_defaults = dict(
type="xy", secondary_y=False, colspan=1, rowspan=1, l=0.0, r=0.0, b=0.0, t=0.0
)
_check_keys_and_fill("specs", specs, spec_defaults)
# Validate secondary_y
has_secondary_y = False
for row in specs:
for spec in row:
if spec is not None:
has_secondary_y = has_secondary_y or spec["secondary_y"]
if spec and spec["type"] != "xy" and spec["secondary_y"]:
raise ValueError(
"""
The 'secondary_y' spec property is not supported for subplot of type '{s_typ}'
'secondary_y' is only supported for subplots of type 'xy'
""".format(
s_typ=spec["type"]
)
)
# ### insets ###
if insets is None or insets is False:
insets = []
elif not (
isinstance(insets, (list, tuple)) and all(isinstance(v, dict) for v in insets)
):
raise ValueError(
"""
The 'insets' argument to make_subplots must be a list of dictionaries.
Received value of type {typ}: {val}""".format(
typ=type(insets), val=repr(insets)
)
)
if insets:
for inset in insets:
if inset and inset.pop("is_3d", None):
inset["type"] = "scene"
inset_defaults = dict(
cell=(1, 1), type="xy", l=0.0, w="to_end", b=0.0, h="to_end"
)
_check_keys_and_fill("insets", insets, inset_defaults)
# ### shared_xaxes / shared_yaxes
valid_shared_vals = [None, True, False, "rows", "columns", "all"]
shared_err_msg = """
The {arg} argument to make_subplots must be one of: {valid_vals}
Received value of type {typ}: {val}"""
if shared_xaxes not in valid_shared_vals:
val = shared_xaxes
raise ValueError(
shared_err_msg.format(
arg="shared_xaxes",
valid_vals=valid_shared_vals,
typ=type(val),
val=repr(val),
)
)
if shared_yaxes not in valid_shared_vals:
val = shared_yaxes
raise ValueError(
shared_err_msg.format(
arg="shared_yaxes",
valid_vals=valid_shared_vals,
typ=type(val),
val=repr(val),
)
)
def _check_hv_spacing(dimsize, spacing, name, dimvarname, dimname):
if spacing < 0 or spacing > 1:
raise ValueError("%s spacing must be between 0 and 1." % (name,))
if dimsize <= 1:
return
max_spacing = 1.0 / float(dimsize - 1)
if spacing > max_spacing:
raise ValueError(
"""{name} spacing cannot be greater than (1 / ({dimvarname} - 1)) = {max_spacing:f}.
The resulting plot would have {dimsize} {dimname} ({dimvarname}={dimsize}).""".format(
dimvarname=dimvarname,
name=name,
dimname=dimname,
max_spacing=max_spacing,
dimsize=dimsize,
)
)
# ### horizontal_spacing ###
if horizontal_spacing is None:
if has_secondary_y:
horizontal_spacing = 0.4 / cols
else:
horizontal_spacing = 0.2 / cols
# check horizontal_spacing can be satisfied:
_check_hv_spacing(cols, horizontal_spacing, "Horizontal", "cols", "columns")
# ### vertical_spacing ###
if vertical_spacing is None:
if subplot_titles is not None:
vertical_spacing = 0.5 / rows
else:
vertical_spacing = 0.3 / rows
# check vertical_spacing can be satisfied:
_check_hv_spacing(rows, vertical_spacing, "Vertical", "rows", "rows")
# ### subplot titles ###
if subplot_titles is None:
subplot_titles = [""] * rows * cols
# ### column_widths ###
if has_secondary_y:
# Add room for secondary y-axis title
max_width = 0.94
elif row_titles:
# Add a little breathing room between row labels and legend
max_width = 0.98
else:
max_width = 1.0
if column_widths is None:
widths = [(max_width - horizontal_spacing * (cols - 1)) / cols] * cols
elif isinstance(column_widths, (list, tuple)) and len(column_widths) == cols:
cum_sum = float(sum(column_widths))
widths = []
for w in column_widths:
widths.append((max_width - horizontal_spacing * (cols - 1)) * (w / cum_sum))
else:
raise ValueError(
"""
The 'column_widths' argument to make_subplots must be a list of numbers of \
length {cols}.
Received value of type {typ}: {val}""".format(
cols=cols, typ=type(column_widths), val=repr(column_widths)
)
)
# ### row_heights ###
if row_heights is None:
heights = [(1.0 - vertical_spacing * (rows - 1)) / rows] * rows
elif isinstance(row_heights, (list, tuple)) and len(row_heights) == rows:
cum_sum = float(sum(row_heights))
heights = []
for h in row_heights:
heights.append((1.0 - vertical_spacing * (rows - 1)) * (h / cum_sum))
if row_dir < 0 and not use_legacy_row_heights_order:
heights = list(reversed(heights))
else:
raise ValueError(
"""
The 'row_heights' argument to make_subplots must be a list of numbers of \
length {rows}.
Received value of type {typ}: {val}""".format(
rows=rows, typ=type(row_heights), val=repr(row_heights)
)
)
# ### column_titles / row_titles ###
if column_titles and not isinstance(column_titles, (list, tuple)):
raise ValueError(
"""
The column_titles argument to make_subplots must be a list or tuple
Received value of type {typ}: {val}""".format(
typ=type(column_titles), val=repr(column_titles)
)
)
if row_titles and not isinstance(row_titles, (list, tuple)):
raise ValueError(
"""
The row_titles argument to make_subplots must be a list or tuple
Received value of type {typ}: {val}""".format(
typ=type(row_titles), val=repr(row_titles)
)
)
# Init layout
# -----------
layout = go.Layout()
# Build grid reference
# --------------------
# Built row/col sequence using 'row_dir' and 'col_dir'
col_seq = range(cols)[::col_dir]
row_seq = range(rows)[::row_dir]
# Build 2D array of tuples of the start x and start y coordinate of each
# subplot
grid = [
[
(
(sum(widths[:c]) + c * horizontal_spacing),
(sum(heights[:r]) + r * vertical_spacing),
)
for c in col_seq
]
for r in row_seq
]
domains_grid = [[None for _ in range(cols)] for _ in range(rows)]
# Initialize subplot reference lists for the grid and insets
grid_ref = [[None for c in range(cols)] for r in range(rows)]
list_of_domains = [] # added for subplot titles
max_subplot_ids = _get_initial_max_subplot_ids()
# Loop through specs -- (r, c) <-> (row, col)
for r, spec_row in enumerate(specs):
for c, spec in enumerate(spec_row):
if spec is None: # skip over None cells
continue
# ### Compute x and y domain for subplot ###
c_spanned = c + spec["colspan"] - 1 # get spanned c
r_spanned = r + spec["rowspan"] - 1 # get spanned r
# Throw exception if 'colspan' | 'rowspan' is too large for grid
if c_spanned >= cols:
raise Exception(
"Some 'colspan' value is too large for " "this subplot grid."
)
if r_spanned >= rows:
raise Exception(
"Some 'rowspan' value is too large for " "this subplot grid."
)
# Get x domain using grid and colspan
x_s = grid[r][c][0] + spec["l"]
x_e = grid[r][c_spanned][0] + widths[c_spanned] - spec["r"]
x_domain = [x_s, x_e]
# Get y domain (dep. on row_dir) using grid & r_spanned
if row_dir > 0:
y_s = grid[r][c][1] + spec["b"]
y_e = grid[r_spanned][c][1] + heights[r_spanned] - spec["t"]
else:
y_s = grid[r_spanned][c][1] + spec["b"]
y_e = grid[r][c][1] + heights[-1 - r] - spec["t"]
if y_s < 0.0:
# round for values very close to one
# handles some floating point errors
if y_s > -0.01:
y_s = 0.0
else:
raise Exception(
"A combination of the 'b' values, heights, and "
"number of subplots too large for this subplot grid."
)
if y_s > 1.0:
# round for values very close to one
# handles some floating point errors
if y_s < 1.01:
y_s = 1.0
else:
raise Exception(
"A combination of the 'b' values, heights, and "
"number of subplots too large for this subplot grid."
)
if y_e < 0.0:
if y_e > -0.01:
y_e = 0.0
else:
raise Exception(
"A combination of the 't' values, heights, and "
"number of subplots too large for this subplot grid."
)
if y_e > 1.0:
if y_e < 1.01:
y_e = 1.0
else:
raise Exception(
"A combination of the 't' values, heights, and "
"number of subplots too large for this subplot grid."
)
y_domain = [y_s, y_e]
list_of_domains.append(x_domain)
list_of_domains.append(y_domain)
domains_grid[r][c] = [x_domain, y_domain]
# ### construct subplot container ###
subplot_type = spec["type"]
secondary_y = spec["secondary_y"]
subplot_refs = _init_subplot(
layout, subplot_type, secondary_y, x_domain, y_domain, max_subplot_ids
)
grid_ref[r][c] = subplot_refs
_configure_shared_axes(layout, grid_ref, specs, "x", shared_xaxes, row_dir)
_configure_shared_axes(layout, grid_ref, specs, "y", shared_yaxes, row_dir)
# Build inset reference
# ---------------------
# Loop through insets
insets_ref = [None for inset in range(len(insets))] if insets else None
if insets:
for i_inset, inset in enumerate(insets):
r = inset["cell"][0] - 1
c = inset["cell"][1] - 1
# Throw exception if r | c is out of range
if not (0 <= r < rows):
raise Exception(
"Some 'cell' row value is out of range. "
"Note: the starting cell is (1, 1)"
)
if not (0 <= c < cols):
raise Exception(
"Some 'cell' col value is out of range. "
"Note: the starting cell is (1, 1)"
)
# Get inset x domain using grid
x_s = grid[r][c][0] + inset["l"] * widths[c]
if inset["w"] == "to_end":
x_e = grid[r][c][0] + widths[c]
else:
x_e = x_s + inset["w"] * widths[c]
x_domain = [x_s, x_e]
# Get inset y domain using grid
y_s = grid[r][c][1] + inset["b"] * heights[-1 - r]
if inset["h"] == "to_end":
y_e = grid[r][c][1] + heights[-1 - r]
else:
y_e = y_s + inset["h"] * heights[-1 - r]
y_domain = [y_s, y_e]
list_of_domains.append(x_domain)
list_of_domains.append(y_domain)
subplot_type = inset["type"]
subplot_refs = _init_subplot(
layout, subplot_type, False, x_domain, y_domain, max_subplot_ids
)
insets_ref[i_inset] = subplot_refs
# Build grid_str
# This is the message printed when print_grid=True
grid_str = _build_grid_str(specs, grid_ref, insets, insets_ref, row_seq)
# Add subplot titles
plot_title_annotations = _build_subplot_title_annotations(
subplot_titles, list_of_domains
)
layout["annotations"] = plot_title_annotations
# Add column titles
if column_titles:
domains_list = []
if row_dir > 0:
for c in range(cols):
domain_pair = domains_grid[-1][c]
if domain_pair:
domains_list.extend(domain_pair)
else:
for c in range(cols):
domain_pair = domains_grid[0][c]
if domain_pair:
domains_list.extend(domain_pair)
# Add subplot titles
column_title_annotations = _build_subplot_title_annotations(
column_titles, domains_list
)
layout["annotations"] += tuple(column_title_annotations)
if row_titles:
domains_list = []
for r in range(rows):
domain_pair = domains_grid[r][-1]
if domain_pair:
domains_list.extend(domain_pair)
# Add subplot titles
column_title_annotations = _build_subplot_title_annotations(
row_titles, domains_list, title_edge="right"
)
layout["annotations"] += tuple(column_title_annotations)
if x_title:
domains_list = [(0, max_width), (0, 1)]
# Add subplot titles
column_title_annotations = _build_subplot_title_annotations(
[x_title], domains_list, title_edge="bottom", offset=30
)
layout["annotations"] += tuple(column_title_annotations)
if y_title:
domains_list = [(0, 1), (0, 1)]
# Add subplot titles
column_title_annotations = _build_subplot_title_annotations(
[y_title], domains_list, title_edge="left", offset=40
)
layout["annotations"] += tuple(column_title_annotations)
# Handle displaying grid information
if print_grid:
print(grid_str)
# Build resulting figure
if figure is None:
figure = go.Figure()
figure.update_layout(layout)
# Attach subplot grid info to the figure
figure.__dict__["_grid_ref"] = grid_ref
figure.__dict__["_grid_str"] = grid_str
return figure
| _subplots.make_subplots |
plotly.py | 53 | packages/python/plotly/plotly/graph_objs/_sunburst.py | def __init__(
self,
arg=None,
branchvalues=None,
count=None,
customdata=None,
customdatasrc=None,
domain=None,
hoverinfo=None,
hoverinfosrc=None,
hoverlabel=None,
hovertemplate=None,
hovertemplatesrc=None,
hovertext=None,
hovertextsrc=None,
ids=None,
idssrc=None,
insidetextfont=None,
insidetextorientation=None,
labels=None,
labelssrc=None,
leaf=None,
legend=None,
legendgrouptitle=None,
legendrank=None,
legendwidth=None,
level=None,
marker=None,
maxdepth=None,
meta=None,
metasrc=None,
name=None,
opacity=None,
outsidetextfont=None,
parents=None,
parentssrc=None,
root=None,
rotation=None,
sort=None,
stream=None,
text=None,
textfont=None,
textinfo=None,
textsrc=None,
texttemplate=None,
texttemplatesrc=None,
uid=None,
uirevision=None,
values=None,
valuessrc=None,
visible=None,
**kwargs,
):
"""
Construct a new Sunburst object
Visualize hierarchal data spanning outward radially from root
to leaves. The sunburst sectors are determined by the entries
in "labels" or "ids" and in "parents".
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.Sunburst`
branchvalues
Determines how the items in `values` are summed. When
set to "total", items in `values` are taken to be value
of all its descendants. When set to "remainder", items
in `values` corresponding to the root and the branches
sectors are taken to be the extra part not part of the
sum of the values at their leaves.
count
Determines default for `values` when it is not
provided, by inferring a 1 for each of the "leaves"
and/or "branches", otherwise 0.
customdata
Assigns extra data each datum. This may be useful when
listening to hover, click and selection events. Note
that, "scatter" traces also appends customdata items in
the markers DOM elements
customdatasrc
Sets the source reference on Chart Studio Cloud for
`customdata`.
domain
:class:`plotly.graph_objects.sunburst.Domain` instance
or dict with compatible properties
hoverinfo
Determines which trace information appear on hover. If
`none` or `skip` are set, no information is displayed
upon hovering. But, if `none` is set, click and hover
events are still fired.
hoverinfosrc
Sets the source reference on Chart Studio Cloud for
`hoverinfo`.
hoverlabel
:class:`plotly.graph_objects.sunburst.Hoverlabel`
instance or dict with compatible properties
hovertemplate
Template string used for rendering the information that
appear on hover box. Note that this will override
`hoverinfo`. Variables are inserted using %{variable},
for example "y: %{y}" as well as %{xother}, {%_xother},
{%_xother_}, {%xother_}. When showing info for several
points, "xother" will be added to those with different
x positions from the first point. An underscore before
or after "(x|y)other" will add a space on that side,
only when this field is shown. Numbers are formatted
using d3-format's syntax %{variable:d3-format}, for
example "Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. The variables available in
`hovertemplate` are the ones emitted as event data
described at this link
https://plotly.com/javascript/plotlyjs-events/#event-
data. Additionally, every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Finally, the template string has access
to variables `currentPath`, `root`, `entry`,
`percentRoot`, `percentEntry` and `percentParent`.
Anything contained in tag `<extra>` is displayed in the
secondary box, for example
"<extra>{fullData.name}</extra>". To hide the secondary
box completely, use an empty tag `<extra></extra>`.
hovertemplatesrc
Sets the source reference on Chart Studio Cloud for
`hovertemplate`.
hovertext
Sets hover text elements associated with each sector.
If a single string, the same string appears for all
data points. If an array of string, the items are
mapped in order of this trace's sectors. To be seen,
trace `hoverinfo` must contain a "text" flag.
hovertextsrc
Sets the source reference on Chart Studio Cloud for
`hovertext`.
ids
Assigns id labels to each datum. These ids for object
constancy of data points during animation. Should be an
array of strings, not numbers or any other type.
idssrc
Sets the source reference on Chart Studio Cloud for
`ids`.
insidetextfont
Sets the font used for `textinfo` lying inside the
sector.
insidetextorientation
Controls the orientation of the text inside chart
sectors. When set to "auto", text may be oriented in
any direction in order to be as big as possible in the
middle of a sector. The "horizontal" option orients
text to be parallel with the bottom of the chart, and
may make text smaller in order to achieve that goal.
The "radial" option orients text along the radius of
the sector. The "tangential" option orients text
perpendicular to the radius of the sector.
labels
Sets the labels of each of the sectors.
labelssrc
Sets the source reference on Chart Studio Cloud for
`labels`.
leaf
:class:`plotly.graph_objects.sunburst.Leaf` instance or
dict with compatible properties
legend
Sets the reference to a legend to show this trace in.
References to these legends are "legend", "legend2",
"legend3", etc. Settings for these legends are set in
the layout, under `layout.legend`, `layout.legend2`,
etc.
legendgrouptitle
:class:`plotly.graph_objects.sunburst.Legendgrouptitle`
instance or dict with compatible properties
legendrank
Sets the legend rank for this trace. Items and groups
with smaller ranks are presented on top/left side while
with "reversed" `legend.traceorder` they are on
bottom/right side. The default legendrank is 1000, so
that you can use ranks less than 1000 to place certain
items before all unranked items, and ranks greater than
1000 to go after all unranked items. When having
unranked or equal rank items shapes would be displayed
after traces i.e. according to their order in data and
layout.
legendwidth
Sets the width (in px or fraction) of the legend for
this trace.
level
Sets the level from which this trace hierarchy is
rendered. Set `level` to `''` to start from the root
node in the hierarchy. Must be an "id" if `ids` is
filled in, otherwise plotly attempts to find a matching
item in `labels`.
marker
:class:`plotly.graph_objects.sunburst.Marker` instance
or dict with compatible properties
maxdepth
Sets the number of rendered sectors from any given
`level`. Set `maxdepth` to "-1" to render all the
levels in the hierarchy.
meta
Assigns extra meta information associated with this
trace that can be used in various text attributes.
Attributes such as trace `name`, graph, axis and
colorbar `title.text`, annotation `text`
`rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta`
values in an attribute in the same trace, simply use
`%{meta[i]}` where `i` is the index or key of the
`meta` item in question. To access trace `meta` in
layout attributes, use `%{data[n[.meta[i]}` where `i`
is the index or key of the `meta` and `n` is the trace
index.
metasrc
Sets the source reference on Chart Studio Cloud for
`meta`.
name
Sets the trace name. The trace name appears as the
legend item and on hover.
opacity
Sets the opacity of the trace.
outsidetextfont
Sets the font used for `textinfo` lying outside the
sector. This option refers to the root of the hierarchy
presented at the center of a sunburst graph. Please
note that if a hierarchy has multiple root nodes, this
option won't have any effect and `insidetextfont` would
be used.
parents
Sets the parent sectors for each of the sectors. Empty
string items '' are understood to reference the root
node in the hierarchy. If `ids` is filled, `parents`
items are understood to be "ids" themselves. When `ids`
is not set, plotly attempts to find matching items in
`labels`, but beware they must be unique.
parentssrc
Sets the source reference on Chart Studio Cloud for
`parents`.
root
:class:`plotly.graph_objects.sunburst.Root` instance or
dict with compatible properties
rotation
Rotates the whole diagram counterclockwise by some
angle. By default the first slice starts at 3 o'clock.
sort
Determines whether or not the sectors are reordered
from largest to smallest.
stream
:class:`plotly.graph_objects.sunburst.Stream` instance
or dict with compatible properties
text
Sets text elements associated with each sector. If
trace `textinfo` contains a "text" flag, these elements
will be seen on the chart. If trace `hoverinfo`
contains a "text" flag and "hovertext" is not set,
these elements will be seen in the hover labels.
textfont
Sets the font used for `textinfo`.
textinfo
Determines which trace information appear on the graph.
textsrc
Sets the source reference on Chart Studio Cloud for
`text`.
texttemplate
Template string used for rendering the information text
that appear on points. Note that this will override
`textinfo`. Variables are inserted using %{variable},
for example "y: %{y}". Numbers are formatted using
d3-format's syntax %{variable:d3-format}, for example
"Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. Every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Finally, the template string has access
to variables `currentPath`, `root`, `entry`,
`percentRoot`, `percentEntry`, `percentParent`, `label`
and `value`.
texttemplatesrc
Sets the source reference on Chart Studio Cloud for
`texttemplate`.
uid
Assign an id to this trace, Use this to provide object
constancy between traces during animations and
transitions.
uirevision
Controls persistence of some user-driven changes to the
trace: `constraintrange` in `parcoords` traces, as well
as some `editable: true` modifications such as `name`
and `colorbar.title`. Defaults to `layout.uirevision`.
Note that other user-driven trace attribute changes are
controlled by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
values
Sets the values associated with each of the sectors.
Use with `branchvalues` to determine how the values are
summed.
valuessrc
Sets the source reference on Chart Studio Cloud for
`values`.
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
Returns
-------
Sunburst
"""
| /usr/src/app/target_test_cases/failed_tests__sunburst.Sunburst.__init__.txt | def __init__(
self,
arg=None,
branchvalues=None,
count=None,
customdata=None,
customdatasrc=None,
domain=None,
hoverinfo=None,
hoverinfosrc=None,
hoverlabel=None,
hovertemplate=None,
hovertemplatesrc=None,
hovertext=None,
hovertextsrc=None,
ids=None,
idssrc=None,
insidetextfont=None,
insidetextorientation=None,
labels=None,
labelssrc=None,
leaf=None,
legend=None,
legendgrouptitle=None,
legendrank=None,
legendwidth=None,
level=None,
marker=None,
maxdepth=None,
meta=None,
metasrc=None,
name=None,
opacity=None,
outsidetextfont=None,
parents=None,
parentssrc=None,
root=None,
rotation=None,
sort=None,
stream=None,
text=None,
textfont=None,
textinfo=None,
textsrc=None,
texttemplate=None,
texttemplatesrc=None,
uid=None,
uirevision=None,
values=None,
valuessrc=None,
visible=None,
**kwargs,
):
"""
Construct a new Sunburst object
Visualize hierarchal data spanning outward radially from root
to leaves. The sunburst sectors are determined by the entries
in "labels" or "ids" and in "parents".
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.Sunburst`
branchvalues
Determines how the items in `values` are summed. When
set to "total", items in `values` are taken to be value
of all its descendants. When set to "remainder", items
in `values` corresponding to the root and the branches
sectors are taken to be the extra part not part of the
sum of the values at their leaves.
count
Determines default for `values` when it is not
provided, by inferring a 1 for each of the "leaves"
and/or "branches", otherwise 0.
customdata
Assigns extra data each datum. This may be useful when
listening to hover, click and selection events. Note
that, "scatter" traces also appends customdata items in
the markers DOM elements
customdatasrc
Sets the source reference on Chart Studio Cloud for
`customdata`.
domain
:class:`plotly.graph_objects.sunburst.Domain` instance
or dict with compatible properties
hoverinfo
Determines which trace information appear on hover. If
`none` or `skip` are set, no information is displayed
upon hovering. But, if `none` is set, click and hover
events are still fired.
hoverinfosrc
Sets the source reference on Chart Studio Cloud for
`hoverinfo`.
hoverlabel
:class:`plotly.graph_objects.sunburst.Hoverlabel`
instance or dict with compatible properties
hovertemplate
Template string used for rendering the information that
appear on hover box. Note that this will override
`hoverinfo`. Variables are inserted using %{variable},
for example "y: %{y}" as well as %{xother}, {%_xother},
{%_xother_}, {%xother_}. When showing info for several
points, "xother" will be added to those with different
x positions from the first point. An underscore before
or after "(x|y)other" will add a space on that side,
only when this field is shown. Numbers are formatted
using d3-format's syntax %{variable:d3-format}, for
example "Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. The variables available in
`hovertemplate` are the ones emitted as event data
described at this link
https://plotly.com/javascript/plotlyjs-events/#event-
data. Additionally, every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Finally, the template string has access
to variables `currentPath`, `root`, `entry`,
`percentRoot`, `percentEntry` and `percentParent`.
Anything contained in tag `<extra>` is displayed in the
secondary box, for example
"<extra>{fullData.name}</extra>". To hide the secondary
box completely, use an empty tag `<extra></extra>`.
hovertemplatesrc
Sets the source reference on Chart Studio Cloud for
`hovertemplate`.
hovertext
Sets hover text elements associated with each sector.
If a single string, the same string appears for all
data points. If an array of string, the items are
mapped in order of this trace's sectors. To be seen,
trace `hoverinfo` must contain a "text" flag.
hovertextsrc
Sets the source reference on Chart Studio Cloud for
`hovertext`.
ids
Assigns id labels to each datum. These ids for object
constancy of data points during animation. Should be an
array of strings, not numbers or any other type.
idssrc
Sets the source reference on Chart Studio Cloud for
`ids`.
insidetextfont
Sets the font used for `textinfo` lying inside the
sector.
insidetextorientation
Controls the orientation of the text inside chart
sectors. When set to "auto", text may be oriented in
any direction in order to be as big as possible in the
middle of a sector. The "horizontal" option orients
text to be parallel with the bottom of the chart, and
may make text smaller in order to achieve that goal.
The "radial" option orients text along the radius of
the sector. The "tangential" option orients text
perpendicular to the radius of the sector.
labels
Sets the labels of each of the sectors.
labelssrc
Sets the source reference on Chart Studio Cloud for
`labels`.
leaf
:class:`plotly.graph_objects.sunburst.Leaf` instance or
dict with compatible properties
legend
Sets the reference to a legend to show this trace in.
References to these legends are "legend", "legend2",
"legend3", etc. Settings for these legends are set in
the layout, under `layout.legend`, `layout.legend2`,
etc.
legendgrouptitle
:class:`plotly.graph_objects.sunburst.Legendgrouptitle`
instance or dict with compatible properties
legendrank
Sets the legend rank for this trace. Items and groups
with smaller ranks are presented on top/left side while
with "reversed" `legend.traceorder` they are on
bottom/right side. The default legendrank is 1000, so
that you can use ranks less than 1000 to place certain
items before all unranked items, and ranks greater than
1000 to go after all unranked items. When having
unranked or equal rank items shapes would be displayed
after traces i.e. according to their order in data and
layout.
legendwidth
Sets the width (in px or fraction) of the legend for
this trace.
level
Sets the level from which this trace hierarchy is
rendered. Set `level` to `''` to start from the root
node in the hierarchy. Must be an "id" if `ids` is
filled in, otherwise plotly attempts to find a matching
item in `labels`.
marker
:class:`plotly.graph_objects.sunburst.Marker` instance
or dict with compatible properties
maxdepth
Sets the number of rendered sectors from any given
`level`. Set `maxdepth` to "-1" to render all the
levels in the hierarchy.
meta
Assigns extra meta information associated with this
trace that can be used in various text attributes.
Attributes such as trace `name`, graph, axis and
colorbar `title.text`, annotation `text`
`rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta`
values in an attribute in the same trace, simply use
`%{meta[i]}` where `i` is the index or key of the
`meta` item in question. To access trace `meta` in
layout attributes, use `%{data[n[.meta[i]}` where `i`
is the index or key of the `meta` and `n` is the trace
index.
metasrc
Sets the source reference on Chart Studio Cloud for
`meta`.
name
Sets the trace name. The trace name appears as the
legend item and on hover.
opacity
Sets the opacity of the trace.
outsidetextfont
Sets the font used for `textinfo` lying outside the
sector. This option refers to the root of the hierarchy
presented at the center of a sunburst graph. Please
note that if a hierarchy has multiple root nodes, this
option won't have any effect and `insidetextfont` would
be used.
parents
Sets the parent sectors for each of the sectors. Empty
string items '' are understood to reference the root
node in the hierarchy. If `ids` is filled, `parents`
items are understood to be "ids" themselves. When `ids`
is not set, plotly attempts to find matching items in
`labels`, but beware they must be unique.
parentssrc
Sets the source reference on Chart Studio Cloud for
`parents`.
root
:class:`plotly.graph_objects.sunburst.Root` instance or
dict with compatible properties
rotation
Rotates the whole diagram counterclockwise by some
angle. By default the first slice starts at 3 o'clock.
sort
Determines whether or not the sectors are reordered
from largest to smallest.
stream
:class:`plotly.graph_objects.sunburst.Stream` instance
or dict with compatible properties
text
Sets text elements associated with each sector. If
trace `textinfo` contains a "text" flag, these elements
will be seen on the chart. If trace `hoverinfo`
contains a "text" flag and "hovertext" is not set,
these elements will be seen in the hover labels.
textfont
Sets the font used for `textinfo`.
textinfo
Determines which trace information appear on the graph.
textsrc
Sets the source reference on Chart Studio Cloud for
`text`.
texttemplate
Template string used for rendering the information text
that appear on points. Note that this will override
`textinfo`. Variables are inserted using %{variable},
for example "y: %{y}". Numbers are formatted using
d3-format's syntax %{variable:d3-format}, for example
"Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. Every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Finally, the template string has access
to variables `currentPath`, `root`, `entry`,
`percentRoot`, `percentEntry`, `percentParent`, `label`
and `value`.
texttemplatesrc
Sets the source reference on Chart Studio Cloud for
`texttemplate`.
uid
Assign an id to this trace, Use this to provide object
constancy between traces during animations and
transitions.
uirevision
Controls persistence of some user-driven changes to the
trace: `constraintrange` in `parcoords` traces, as well
as some `editable: true` modifications such as `name`
and `colorbar.title`. Defaults to `layout.uirevision`.
Note that other user-driven trace attribute changes are
controlled by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
values
Sets the values associated with each of the sectors.
Use with `branchvalues` to determine how the values are
summed.
valuessrc
Sets the source reference on Chart Studio Cloud for
`values`.
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
Returns
-------
Sunburst
"""
super(Sunburst, self).__init__("sunburst")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.Sunburst
constructor must be a dict or
an instance of :class:`plotly.graph_objs.Sunburst`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("branchvalues", None)
_v = branchvalues if branchvalues is not None else _v
if _v is not None:
self["branchvalues"] = _v
_v = arg.pop("count", None)
_v = count if count is not None else _v
if _v is not None:
self["count"] = _v
_v = arg.pop("customdata", None)
_v = customdata if customdata is not None else _v
if _v is not None:
self["customdata"] = _v
_v = arg.pop("customdatasrc", None)
_v = customdatasrc if customdatasrc is not None else _v
if _v is not None:
self["customdatasrc"] = _v
_v = arg.pop("domain", None)
_v = domain if domain is not None else _v
if _v is not None:
self["domain"] = _v
_v = arg.pop("hoverinfo", None)
_v = hoverinfo if hoverinfo is not None else _v
if _v is not None:
self["hoverinfo"] = _v
_v = arg.pop("hoverinfosrc", None)
_v = hoverinfosrc if hoverinfosrc is not None else _v
if _v is not None:
self["hoverinfosrc"] = _v
_v = arg.pop("hoverlabel", None)
_v = hoverlabel if hoverlabel is not None else _v
if _v is not None:
self["hoverlabel"] = _v
_v = arg.pop("hovertemplate", None)
_v = hovertemplate if hovertemplate is not None else _v
if _v is not None:
self["hovertemplate"] = _v
_v = arg.pop("hovertemplatesrc", None)
_v = hovertemplatesrc if hovertemplatesrc is not None else _v
if _v is not None:
self["hovertemplatesrc"] = _v
_v = arg.pop("hovertext", None)
_v = hovertext if hovertext is not None else _v
if _v is not None:
self["hovertext"] = _v
_v = arg.pop("hovertextsrc", None)
_v = hovertextsrc if hovertextsrc is not None else _v
if _v is not None:
self["hovertextsrc"] = _v
_v = arg.pop("ids", None)
_v = ids if ids is not None else _v
if _v is not None:
self["ids"] = _v
_v = arg.pop("idssrc", None)
_v = idssrc if idssrc is not None else _v
if _v is not None:
self["idssrc"] = _v
_v = arg.pop("insidetextfont", None)
_v = insidetextfont if insidetextfont is not None else _v
if _v is not None:
self["insidetextfont"] = _v
_v = arg.pop("insidetextorientation", None)
_v = insidetextorientation if insidetextorientation is not None else _v
if _v is not None:
self["insidetextorientation"] = _v
_v = arg.pop("labels", None)
_v = labels if labels is not None else _v
if _v is not None:
self["labels"] = _v
_v = arg.pop("labelssrc", None)
_v = labelssrc if labelssrc is not None else _v
if _v is not None:
self["labelssrc"] = _v
_v = arg.pop("leaf", None)
_v = leaf if leaf is not None else _v
if _v is not None:
self["leaf"] = _v
_v = arg.pop("legend", None)
_v = legend if legend is not None else _v
if _v is not None:
self["legend"] = _v
_v = arg.pop("legendgrouptitle", None)
_v = legendgrouptitle if legendgrouptitle is not None else _v
if _v is not None:
self["legendgrouptitle"] = _v
_v = arg.pop("legendrank", None)
_v = legendrank if legendrank is not None else _v
if _v is not None:
self["legendrank"] = _v
_v = arg.pop("legendwidth", None)
_v = legendwidth if legendwidth is not None else _v
if _v is not None:
self["legendwidth"] = _v
_v = arg.pop("level", None)
_v = level if level is not None else _v
if _v is not None:
self["level"] = _v
_v = arg.pop("marker", None)
_v = marker if marker is not None else _v
if _v is not None:
self["marker"] = _v
_v = arg.pop("maxdepth", None)
_v = maxdepth if maxdepth is not None else _v
if _v is not None:
self["maxdepth"] = _v
_v = arg.pop("meta", None)
_v = meta if meta is not None else _v
if _v is not None:
self["meta"] = _v
_v = arg.pop("metasrc", None)
_v = metasrc if metasrc is not None else _v
if _v is not None:
self["metasrc"] = _v
_v = arg.pop("name", None)
_v = name if name is not None else _v
if _v is not None:
self["name"] = _v
_v = arg.pop("opacity", None)
_v = opacity if opacity is not None else _v
if _v is not None:
self["opacity"] = _v
_v = arg.pop("outsidetextfont", None)
_v = outsidetextfont if outsidetextfont is not None else _v
if _v is not None:
self["outsidetextfont"] = _v
_v = arg.pop("parents", None)
_v = parents if parents is not None else _v
if _v is not None:
self["parents"] = _v
_v = arg.pop("parentssrc", None)
_v = parentssrc if parentssrc is not None else _v
if _v is not None:
self["parentssrc"] = _v
_v = arg.pop("root", None)
_v = root if root is not None else _v
if _v is not None:
self["root"] = _v
_v = arg.pop("rotation", None)
_v = rotation if rotation is not None else _v
if _v is not None:
self["rotation"] = _v
_v = arg.pop("sort", None)
_v = sort if sort is not None else _v
if _v is not None:
self["sort"] = _v
_v = arg.pop("stream", None)
_v = stream if stream is not None else _v
if _v is not None:
self["stream"] = _v
_v = arg.pop("text", None)
_v = text if text is not None else _v
if _v is not None:
self["text"] = _v
_v = arg.pop("textfont", None)
_v = textfont if textfont is not None else _v
if _v is not None:
self["textfont"] = _v
_v = arg.pop("textinfo", None)
_v = textinfo if textinfo is not None else _v
if _v is not None:
self["textinfo"] = _v
_v = arg.pop("textsrc", None)
_v = textsrc if textsrc is not None else _v
if _v is not None:
self["textsrc"] = _v
_v = arg.pop("texttemplate", None)
_v = texttemplate if texttemplate is not None else _v
if _v is not None:
self["texttemplate"] = _v
_v = arg.pop("texttemplatesrc", None)
_v = texttemplatesrc if texttemplatesrc is not None else _v
if _v is not None:
self["texttemplatesrc"] = _v
_v = arg.pop("uid", None)
_v = uid if uid is not None else _v
if _v is not None:
self["uid"] = _v
_v = arg.pop("uirevision", None)
_v = uirevision if uirevision is not None else _v
if _v is not None:
self["uirevision"] = _v
_v = arg.pop("values", None)
_v = values if values is not None else _v
if _v is not None:
self["values"] = _v
_v = arg.pop("valuessrc", None)
_v = valuessrc if valuessrc is not None else _v
if _v is not None:
self["valuessrc"] = _v
_v = arg.pop("visible", None)
_v = visible if visible is not None else _v
if _v is not None:
self["visible"] = _v
# Read-only literals
# ------------------
self._props["type"] = "sunburst"
arg.pop("type", None)
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| _sunburst.Sunburst.__init__ |
plotly.py | 54 | packages/python/plotly/plotly/graph_objs/_sunburst.py | def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.sunburst.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Supported dict properties:
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.colorscale`. Has an
effect only if colors is set to a numerical
array. In case `colorscale` is unspecified or
`autocolorscale` is true, the default palette
will be chosen according to whether numbers in
the `color` array are all positive, all
negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
colors) or the bounds set in `marker.cmin` and
`marker.cmax` Has an effect only if colors is
set to a numerical array. Defaults to `false`
when `marker.cmin` and `marker.cmax` are set by
the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if colors is set to a numerical
array. Value should have the same units as
colors and if set, `marker.cmin` must be set as
well.
cmid
Sets the mid-point of the color domain by
scaling `marker.cmin` and/or `marker.cmax` to
be equidistant to this point. Has an effect
only if colors is set to a numerical array.
Value should have the same units as colors. Has
no effect when `marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if colors is set to a numerical
array. Value should have the same units as
colors and if set, `marker.cmax` must be set as
well.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.sunburst.marker.Co
lorBar` instance or dict with compatible
properties
colors
Sets the color of each sector of this trace. If
not specified, the default trace color set is
used to pick the sector colors.
colorscale
Sets the colorscale. Has an effect only if
colors is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `marker.cmin` and
`marker.cmax`. Alternatively, `colorscale` may
be a palette name string of the following list:
Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorssrc
Sets the source reference on Chart Studio Cloud
for `colors`.
line
:class:`plotly.graph_objects.sunburst.marker.Li
ne` instance or dict with compatible properties
pattern
Sets the pattern within the marker.
reversescale
Reverses the color mapping if true. Has an
effect only if colors is set to a numerical
array. If true, `marker.cmin` will correspond
to the last color in the array and
`marker.cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
colors is set to a numerical array.
Returns
-------
plotly.graph_objs.sunburst.Marker
"""
| /usr/src/app/target_test_cases/failed_tests__sunburst.marker.txt | def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.sunburst.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Supported dict properties:
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.colorscale`. Has an
effect only if colors is set to a numerical
array. In case `colorscale` is unspecified or
`autocolorscale` is true, the default palette
will be chosen according to whether numbers in
the `color` array are all positive, all
negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
colors) or the bounds set in `marker.cmin` and
`marker.cmax` Has an effect only if colors is
set to a numerical array. Defaults to `false`
when `marker.cmin` and `marker.cmax` are set by
the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if colors is set to a numerical
array. Value should have the same units as
colors and if set, `marker.cmin` must be set as
well.
cmid
Sets the mid-point of the color domain by
scaling `marker.cmin` and/or `marker.cmax` to
be equidistant to this point. Has an effect
only if colors is set to a numerical array.
Value should have the same units as colors. Has
no effect when `marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if colors is set to a numerical
array. Value should have the same units as
colors and if set, `marker.cmax` must be set as
well.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.sunburst.marker.Co
lorBar` instance or dict with compatible
properties
colors
Sets the color of each sector of this trace. If
not specified, the default trace color set is
used to pick the sector colors.
colorscale
Sets the colorscale. Has an effect only if
colors is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `marker.cmin` and
`marker.cmax`. Alternatively, `colorscale` may
be a palette name string of the following list:
Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorssrc
Sets the source reference on Chart Studio Cloud
for `colors`.
line
:class:`plotly.graph_objects.sunburst.marker.Li
ne` instance or dict with compatible properties
pattern
Sets the pattern within the marker.
reversescale
Reverses the color mapping if true. Has an
effect only if colors is set to a numerical
array. If true, `marker.cmin` will correspond
to the last color in the array and
`marker.cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
colors is set to a numerical array.
Returns
-------
plotly.graph_objs.sunburst.Marker
"""
return self["marker"]
| _sunburst.marker |
plotly.py | 55 | packages/python/plotly/plotly/graph_objs/layout/_template.py | def data(self):
"""
The 'data' property is an instance of Data
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.template.Data`
- A dict of string/value properties that will be passed
to the Data constructor
Supported dict properties:
barpolar
A tuple of
:class:`plotly.graph_objects.Barpolar`
instances or dicts with compatible properties
bar
A tuple of :class:`plotly.graph_objects.Bar`
instances or dicts with compatible properties
box
A tuple of :class:`plotly.graph_objects.Box`
instances or dicts with compatible properties
candlestick
A tuple of
:class:`plotly.graph_objects.Candlestick`
instances or dicts with compatible properties
carpet
A tuple of :class:`plotly.graph_objects.Carpet`
instances or dicts with compatible properties
choroplethmapbox
A tuple of
:class:`plotly.graph_objects.Choroplethmapbox`
instances or dicts with compatible properties
choroplethmap
A tuple of
:class:`plotly.graph_objects.Choroplethmap`
instances or dicts with compatible properties
choropleth
A tuple of
:class:`plotly.graph_objects.Choropleth`
instances or dicts with compatible properties
cone
A tuple of :class:`plotly.graph_objects.Cone`
instances or dicts with compatible properties
contourcarpet
A tuple of
:class:`plotly.graph_objects.Contourcarpet`
instances or dicts with compatible properties
contour
A tuple of
:class:`plotly.graph_objects.Contour` instances
or dicts with compatible properties
densitymapbox
A tuple of
:class:`plotly.graph_objects.Densitymapbox`
instances or dicts with compatible properties
densitymap
A tuple of
:class:`plotly.graph_objects.Densitymap`
instances or dicts with compatible properties
funnelarea
A tuple of
:class:`plotly.graph_objects.Funnelarea`
instances or dicts with compatible properties
funnel
A tuple of :class:`plotly.graph_objects.Funnel`
instances or dicts with compatible properties
heatmapgl
A tuple of
:class:`plotly.graph_objects.Heatmapgl`
instances or dicts with compatible properties
heatmap
A tuple of
:class:`plotly.graph_objects.Heatmap` instances
or dicts with compatible properties
histogram2dcontour
A tuple of :class:`plotly.graph_objects.Histogr
am2dContour` instances or dicts with compatible
properties
histogram2d
A tuple of
:class:`plotly.graph_objects.Histogram2d`
instances or dicts with compatible properties
histogram
A tuple of
:class:`plotly.graph_objects.Histogram`
instances or dicts with compatible properties
icicle
A tuple of :class:`plotly.graph_objects.Icicle`
instances or dicts with compatible properties
image
A tuple of :class:`plotly.graph_objects.Image`
instances or dicts with compatible properties
indicator
A tuple of
:class:`plotly.graph_objects.Indicator`
instances or dicts with compatible properties
isosurface
A tuple of
:class:`plotly.graph_objects.Isosurface`
instances or dicts with compatible properties
mesh3d
A tuple of :class:`plotly.graph_objects.Mesh3d`
instances or dicts with compatible properties
ohlc
A tuple of :class:`plotly.graph_objects.Ohlc`
instances or dicts with compatible properties
parcats
A tuple of
:class:`plotly.graph_objects.Parcats` instances
or dicts with compatible properties
parcoords
A tuple of
:class:`plotly.graph_objects.Parcoords`
instances or dicts with compatible properties
pie
A tuple of :class:`plotly.graph_objects.Pie`
instances or dicts with compatible properties
pointcloud
A tuple of
:class:`plotly.graph_objects.Pointcloud`
instances or dicts with compatible properties
sankey
A tuple of :class:`plotly.graph_objects.Sankey`
instances or dicts with compatible properties
scatter3d
A tuple of
:class:`plotly.graph_objects.Scatter3d`
instances or dicts with compatible properties
scattercarpet
A tuple of
:class:`plotly.graph_objects.Scattercarpet`
instances or dicts with compatible properties
scattergeo
A tuple of
:class:`plotly.graph_objects.Scattergeo`
instances or dicts with compatible properties
scattergl
A tuple of
:class:`plotly.graph_objects.Scattergl`
instances or dicts with compatible properties
scattermapbox
A tuple of
:class:`plotly.graph_objects.Scattermapbox`
instances or dicts with compatible properties
scattermap
A tuple of
:class:`plotly.graph_objects.Scattermap`
instances or dicts with compatible properties
scatterpolargl
A tuple of
:class:`plotly.graph_objects.Scatterpolargl`
instances or dicts with compatible properties
scatterpolar
A tuple of
:class:`plotly.graph_objects.Scatterpolar`
instances or dicts with compatible properties
scatter
A tuple of
:class:`plotly.graph_objects.Scatter` instances
or dicts with compatible properties
scattersmith
A tuple of
:class:`plotly.graph_objects.Scattersmith`
instances or dicts with compatible properties
scatterternary
A tuple of
:class:`plotly.graph_objects.Scatterternary`
instances or dicts with compatible properties
splom
A tuple of :class:`plotly.graph_objects.Splom`
instances or dicts with compatible properties
streamtube
A tuple of
:class:`plotly.graph_objects.Streamtube`
instances or dicts with compatible properties
sunburst
A tuple of
:class:`plotly.graph_objects.Sunburst`
instances or dicts with compatible properties
surface
A tuple of
:class:`plotly.graph_objects.Surface` instances
or dicts with compatible properties
table
A tuple of :class:`plotly.graph_objects.Table`
instances or dicts with compatible properties
treemap
A tuple of
:class:`plotly.graph_objects.Treemap` instances
or dicts with compatible properties
violin
A tuple of :class:`plotly.graph_objects.Violin`
instances or dicts with compatible properties
volume
A tuple of :class:`plotly.graph_objects.Volume`
instances or dicts with compatible properties
waterfall
A tuple of
:class:`plotly.graph_objects.Waterfall`
instances or dicts with compatible properties
Returns
-------
plotly.graph_objs.layout.template.Data
"""
| /usr/src/app/target_test_cases/failed_tests__template.data.txt | def data(self):
"""
The 'data' property is an instance of Data
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.template.Data`
- A dict of string/value properties that will be passed
to the Data constructor
Supported dict properties:
barpolar
A tuple of
:class:`plotly.graph_objects.Barpolar`
instances or dicts with compatible properties
bar
A tuple of :class:`plotly.graph_objects.Bar`
instances or dicts with compatible properties
box
A tuple of :class:`plotly.graph_objects.Box`
instances or dicts with compatible properties
candlestick
A tuple of
:class:`plotly.graph_objects.Candlestick`
instances or dicts with compatible properties
carpet
A tuple of :class:`plotly.graph_objects.Carpet`
instances or dicts with compatible properties
choroplethmapbox
A tuple of
:class:`plotly.graph_objects.Choroplethmapbox`
instances or dicts with compatible properties
choroplethmap
A tuple of
:class:`plotly.graph_objects.Choroplethmap`
instances or dicts with compatible properties
choropleth
A tuple of
:class:`plotly.graph_objects.Choropleth`
instances or dicts with compatible properties
cone
A tuple of :class:`plotly.graph_objects.Cone`
instances or dicts with compatible properties
contourcarpet
A tuple of
:class:`plotly.graph_objects.Contourcarpet`
instances or dicts with compatible properties
contour
A tuple of
:class:`plotly.graph_objects.Contour` instances
or dicts with compatible properties
densitymapbox
A tuple of
:class:`plotly.graph_objects.Densitymapbox`
instances or dicts with compatible properties
densitymap
A tuple of
:class:`plotly.graph_objects.Densitymap`
instances or dicts with compatible properties
funnelarea
A tuple of
:class:`plotly.graph_objects.Funnelarea`
instances or dicts with compatible properties
funnel
A tuple of :class:`plotly.graph_objects.Funnel`
instances or dicts with compatible properties
heatmapgl
A tuple of
:class:`plotly.graph_objects.Heatmapgl`
instances or dicts with compatible properties
heatmap
A tuple of
:class:`plotly.graph_objects.Heatmap` instances
or dicts with compatible properties
histogram2dcontour
A tuple of :class:`plotly.graph_objects.Histogr
am2dContour` instances or dicts with compatible
properties
histogram2d
A tuple of
:class:`plotly.graph_objects.Histogram2d`
instances or dicts with compatible properties
histogram
A tuple of
:class:`plotly.graph_objects.Histogram`
instances or dicts with compatible properties
icicle
A tuple of :class:`plotly.graph_objects.Icicle`
instances or dicts with compatible properties
image
A tuple of :class:`plotly.graph_objects.Image`
instances or dicts with compatible properties
indicator
A tuple of
:class:`plotly.graph_objects.Indicator`
instances or dicts with compatible properties
isosurface
A tuple of
:class:`plotly.graph_objects.Isosurface`
instances or dicts with compatible properties
mesh3d
A tuple of :class:`plotly.graph_objects.Mesh3d`
instances or dicts with compatible properties
ohlc
A tuple of :class:`plotly.graph_objects.Ohlc`
instances or dicts with compatible properties
parcats
A tuple of
:class:`plotly.graph_objects.Parcats` instances
or dicts with compatible properties
parcoords
A tuple of
:class:`plotly.graph_objects.Parcoords`
instances or dicts with compatible properties
pie
A tuple of :class:`plotly.graph_objects.Pie`
instances or dicts with compatible properties
pointcloud
A tuple of
:class:`plotly.graph_objects.Pointcloud`
instances or dicts with compatible properties
sankey
A tuple of :class:`plotly.graph_objects.Sankey`
instances or dicts with compatible properties
scatter3d
A tuple of
:class:`plotly.graph_objects.Scatter3d`
instances or dicts with compatible properties
scattercarpet
A tuple of
:class:`plotly.graph_objects.Scattercarpet`
instances or dicts with compatible properties
scattergeo
A tuple of
:class:`plotly.graph_objects.Scattergeo`
instances or dicts with compatible properties
scattergl
A tuple of
:class:`plotly.graph_objects.Scattergl`
instances or dicts with compatible properties
scattermapbox
A tuple of
:class:`plotly.graph_objects.Scattermapbox`
instances or dicts with compatible properties
scattermap
A tuple of
:class:`plotly.graph_objects.Scattermap`
instances or dicts with compatible properties
scatterpolargl
A tuple of
:class:`plotly.graph_objects.Scatterpolargl`
instances or dicts with compatible properties
scatterpolar
A tuple of
:class:`plotly.graph_objects.Scatterpolar`
instances or dicts with compatible properties
scatter
A tuple of
:class:`plotly.graph_objects.Scatter` instances
or dicts with compatible properties
scattersmith
A tuple of
:class:`plotly.graph_objects.Scattersmith`
instances or dicts with compatible properties
scatterternary
A tuple of
:class:`plotly.graph_objects.Scatterternary`
instances or dicts with compatible properties
splom
A tuple of :class:`plotly.graph_objects.Splom`
instances or dicts with compatible properties
streamtube
A tuple of
:class:`plotly.graph_objects.Streamtube`
instances or dicts with compatible properties
sunburst
A tuple of
:class:`plotly.graph_objects.Sunburst`
instances or dicts with compatible properties
surface
A tuple of
:class:`plotly.graph_objects.Surface` instances
or dicts with compatible properties
table
A tuple of :class:`plotly.graph_objects.Table`
instances or dicts with compatible properties
treemap
A tuple of
:class:`plotly.graph_objects.Treemap` instances
or dicts with compatible properties
violin
A tuple of :class:`plotly.graph_objects.Violin`
instances or dicts with compatible properties
volume
A tuple of :class:`plotly.graph_objects.Volume`
instances or dicts with compatible properties
waterfall
A tuple of
:class:`plotly.graph_objects.Waterfall`
instances or dicts with compatible properties
Returns
-------
plotly.graph_objs.layout.template.Data
"""
return self["data"]
| _template.data |
plotly.py | 56 | packages/python/plotly/plotly/io/_templates.py | def to_templated(fig, skip=("title", "text")):
"""
Return a copy of a figure where all styling properties have been moved
into the figure's template. The template property of the resulting figure
may then be used to set the default styling of other figures.
Parameters
----------
fig
Figure object or dict representing a figure
skip
A collection of names of properties to skip when moving properties to
the template. Defaults to ('title', 'text') so that the text
of figure titles, axis titles, and annotations does not become part of
the template
Examples
--------
Imports
>>> import plotly.graph_objs as go
>>> import plotly.io as pio
Construct a figure with large courier text
>>> fig = go.Figure(layout={'title': 'Figure Title',
... 'font': {'size': 20, 'family': 'Courier'},
... 'template':"none"})
>>> fig # doctest: +NORMALIZE_WHITESPACE
Figure({
'data': [],
'layout': {'font': {'family': 'Courier', 'size': 20},
'template': '...', 'title': {'text': 'Figure Title'}}
})
Convert to a figure with a template. Note how the 'font' properties have
been moved into the template property.
>>> templated_fig = pio.to_templated(fig)
>>> templated_fig.layout.template
layout.Template({
'layout': {'font': {'family': 'Courier', 'size': 20}}
})
>>> templated_fig
Figure({
'data': [], 'layout': {'template': '...', 'title': {'text': 'Figure Title'}}
})
Next create a new figure with this template
>>> fig2 = go.Figure(layout={
... 'title': 'Figure 2 Title',
... 'template': templated_fig.layout.template})
>>> fig2.layout.template
layout.Template({
'layout': {'font': {'family': 'Courier', 'size': 20}}
})
The default font in fig2 will now be size 20 Courier.
Next, register as a named template...
>>> pio.templates['large_courier'] = templated_fig.layout.template
and specify this template by name when constructing a figure.
>>> go.Figure(layout={
... 'title': 'Figure 3 Title',
... 'template': 'large_courier'}) # doctest: +ELLIPSIS
Figure(...)
Finally, set this as the default template to be applied to all new figures
>>> pio.templates.default = 'large_courier'
>>> fig = go.Figure(layout={'title': 'Figure 4 Title'})
>>> fig.layout.template
layout.Template({
'layout': {'font': {'family': 'Courier', 'size': 20}}
})
Returns
-------
go.Figure
"""
| /usr/src/app/target_test_cases/failed_tests__templates.to_templated.txt | def to_templated(fig, skip=("title", "text")):
"""
Return a copy of a figure where all styling properties have been moved
into the figure's template. The template property of the resulting figure
may then be used to set the default styling of other figures.
Parameters
----------
fig
Figure object or dict representing a figure
skip
A collection of names of properties to skip when moving properties to
the template. Defaults to ('title', 'text') so that the text
of figure titles, axis titles, and annotations does not become part of
the template
Examples
--------
Imports
>>> import plotly.graph_objs as go
>>> import plotly.io as pio
Construct a figure with large courier text
>>> fig = go.Figure(layout={'title': 'Figure Title',
... 'font': {'size': 20, 'family': 'Courier'},
... 'template':"none"})
>>> fig # doctest: +NORMALIZE_WHITESPACE
Figure({
'data': [],
'layout': {'font': {'family': 'Courier', 'size': 20},
'template': '...', 'title': {'text': 'Figure Title'}}
})
Convert to a figure with a template. Note how the 'font' properties have
been moved into the template property.
>>> templated_fig = pio.to_templated(fig)
>>> templated_fig.layout.template
layout.Template({
'layout': {'font': {'family': 'Courier', 'size': 20}}
})
>>> templated_fig
Figure({
'data': [], 'layout': {'template': '...', 'title': {'text': 'Figure Title'}}
})
Next create a new figure with this template
>>> fig2 = go.Figure(layout={
... 'title': 'Figure 2 Title',
... 'template': templated_fig.layout.template})
>>> fig2.layout.template
layout.Template({
'layout': {'font': {'family': 'Courier', 'size': 20}}
})
The default font in fig2 will now be size 20 Courier.
Next, register as a named template...
>>> pio.templates['large_courier'] = templated_fig.layout.template
and specify this template by name when constructing a figure.
>>> go.Figure(layout={
... 'title': 'Figure 3 Title',
... 'template': 'large_courier'}) # doctest: +ELLIPSIS
Figure(...)
Finally, set this as the default template to be applied to all new figures
>>> pio.templates.default = 'large_courier'
>>> fig = go.Figure(layout={'title': 'Figure 4 Title'})
>>> fig.layout.template
layout.Template({
'layout': {'font': {'family': 'Courier', 'size': 20}}
})
Returns
-------
go.Figure
"""
# process fig
from plotly.basedatatypes import BaseFigure
from plotly.graph_objs import Figure
if not isinstance(fig, BaseFigure):
fig = Figure(fig)
# Process skip
if not skip:
skip = set()
else:
skip = set(skip)
# Always skip uids
skip.add("uid")
# Initialize templated figure with deep copy of input figure
templated_fig = copy.deepcopy(fig)
# Handle layout
walk_push_to_template(
templated_fig.layout, templated_fig.layout.template.layout, skip=skip
)
# Handle traces
trace_type_indexes = {}
for trace in list(templated_fig.data):
template_index = trace_type_indexes.get(trace.type, 0)
# Extend template traces if necessary
template_traces = list(templated_fig.layout.template.data[trace.type])
while len(template_traces) <= template_index:
# Append empty trace
template_traces.append(trace.__class__())
# Get corresponding template trace
template_trace = template_traces[template_index]
# Perform push properties to template
walk_push_to_template(trace, template_trace, skip=skip)
# Update template traces in templated_fig
templated_fig.layout.template.data[trace.type] = template_traces
# Update trace_type_indexes
trace_type_indexes[trace.type] = template_index + 1
# Remove useless trace arrays
any_non_empty = False
for trace_type in templated_fig.layout.template.data:
traces = templated_fig.layout.template.data[trace_type]
is_empty = [trace.to_plotly_json() == {"type": trace_type} for trace in traces]
if all(is_empty):
templated_fig.layout.template.data[trace_type] = None
else:
any_non_empty = True
# Check if we can remove the data altogether key
if not any_non_empty:
templated_fig.layout.template.data = None
return templated_fig
| _templates.to_templated |
plotly.py | 57 | packages/python/plotly/plotly/graph_objs/layout/_ternary.py | def aaxis(self):
"""
The 'aaxis' property is an instance of Aaxis
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.ternary.Aaxis`
- A dict of string/value properties that will be passed
to the Aaxis constructor
Supported dict properties:
color
Sets default for all colors associated with
this axis all at once: line, font, tick, and
grid colors. Grid color is lightened by
blending this with the plot background
Individual pieces can override this.
dtick
Sets the step in-between ticks on this axis.
Use with `tick0`. Must be a positive number, or
special strings available to "log" and "date"
axes. If the axis `type` is "log", then ticks
are set every 10^(n*dtick) where n is the tick
number. For example, to set a tick mark at 1,
10, 100, 1000, ... set dtick to 1. To set tick
marks at 1, 100, 10000, ... set dtick to 2. To
set tick marks at 1, 5, 25, 125, 625, 3125, ...
set dtick to log_10(5), or 0.69897000433. "log"
has several special values; "L<f>", where `f`
is a positive number, gives ticks linearly
spaced in value (but not position). For example
`tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10
plus small digits between, use "D1" (all
digits) or "D2" (only 2 and 5). `tick0` is
ignored for "D1" and "D2". If the axis `type`
is "date", then you must convert the time to
milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to
86400000.0. "date" also has special values
"M<n>" gives ticks spaced by a number of
months. `n` must be a positive integer. To set
ticks on the 15th of every third month, set
`tick0` to "2000-01-15" and `dtick` to "M3". To
set ticks every 4 years, set `dtick` to "M48"
exponentformat
Determines a formatting rule for the tick
exponents. For example, consider the number
1,000,000,000. If "none", it appears as
1,000,000,000. If "e", 1e+9. If "E", 1E+9. If
"power", 1x10^9 (with 9 in a super script). If
"SI", 1G. If "B", 1B.
gridcolor
Sets the color of the grid lines.
griddash
Sets the dash style of lines. Set to a dash
type string ("solid", "dot", "dash",
"longdash", "dashdot", or "longdashdot") or a
dash length list in px (eg "5px,10px,2px,2px").
gridwidth
Sets the width (in px) of the grid lines.
hoverformat
Sets the hover text formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see: h
ttps://github.com/d3/d3-format/tree/v1.4.5#d3-
format. And for dates see:
https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two
items to d3's date formatter: "%h" for half of
the year as a decimal number as well as "%{n}f"
for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with
tickformat "%H~%M~%S.%2f" would display
"09~15~23.46"
labelalias
Replacement text for specific tick or hover
labels. For example using {US: 'USA', CA:
'Canada'} changes US to USA and CA to Canada.
The labels we would have shown must match the
keys exactly, after adding any tickprefix or
ticksuffix. For negative numbers the minus sign
symbol used (U+2212) is wider than the regular
ascii dash. That means you need to use −1
instead of -1. labelalias can be used with any
axis type, and both keys (if needed) and values
(if desired) can include html-like tags or
MathJax.
layer
Sets the layer on which this axis is displayed.
If *above traces*, this axis is displayed above
all the subplot's traces If *below traces*,
this axis is displayed below all the subplot's
traces, but above the grid lines. Useful when
used together with scatter-like traces with
`cliponaxis` set to False to show markers
and/or text nodes above this axis.
linecolor
Sets the axis line color.
linewidth
Sets the width (in px) of the axis line.
min
The minimum value visible on this axis. The
maximum is determined by the sum minus the
minimum values of the other two axes. The full
view corresponds to all the minima set to zero.
minexponent
Hide SI prefix for 10^n if |n| is below this
number. This only has an effect when
`tickformat` is "SI" or "B".
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks
will be chosen automatically to be less than or
equal to `nticks`. Has an effect only if
`tickmode` is set to "auto".
separatethousands
If "true", even 4-digit integers are separated
showexponent
If "all", all exponents are shown besides their
significands. If "first", only the exponent of
the first tick is shown. If "last", only the
exponent of the last tick is shown. If "none",
no exponents appear.
showgrid
Determines whether or not grid lines are drawn.
If True, the grid lines are drawn at every tick
mark.
showline
Determines whether or not a line bounding this
axis is drawn.
showticklabels
Determines whether or not the tick labels are
drawn.
showtickprefix
If "all", all tick labels are displayed with a
prefix. If "first", only the first tick is
displayed with a prefix. If "last", only the
last tick is displayed with a suffix. If
"none", tick prefixes are hidden.
showticksuffix
Same as `showtickprefix` but for tick suffixes.
tick0
Sets the placement of the first tick on this
axis. Use with `dtick`. If the axis `type` is
"log", then you must take the log of your
starting tick (e.g. to set the starting tick to
100, set the `tick0` to 2) except when
`dtick`=*L<f>* (see `dtick` for more info). If
the axis `type` is "date", it should be a date
string, like date data. If the axis `type` is
"category", it should be a number, using the
scale where each category is assigned a serial
number from zero in the order it appears.
tickangle
Sets the angle of the tick labels with respect
to the horizontal. For example, a `tickangle`
of -90 draws the tick labels vertically.
tickcolor
Sets the tick color.
tickfont
Sets the tick font.
tickformat
Sets the tick label formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see: h
ttps://github.com/d3/d3-format/tree/v1.4.5#d3-
format. And for dates see:
https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two
items to d3's date formatter: "%h" for half of
the year as a decimal number as well as "%{n}f"
for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with
tickformat "%H~%M~%S.%2f" would display
"09~15~23.46"
tickformatstops
A tuple of :class:`plotly.graph_objects.layout.
ternary.aaxis.Tickformatstop` instances or
dicts with compatible properties
tickformatstopdefaults
When used in a template (as layout.template.lay
out.ternary.aaxis.tickformatstopdefaults), sets
the default property values to use for elements
of layout.ternary.aaxis.tickformatstops
ticklabelstep
Sets the spacing between tick labels as
compared to the spacing between ticks. A value
of 1 (default) means each tick gets a label. A
value of 2 means shows every 2nd label. A
larger value n means only every nth tick is
labeled. `tick0` determines which labels are
shown. Not implemented for axes with `type`
"log" or "multicategory", or when `tickmode` is
"array".
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto",
the number of ticks is set via `nticks`. If
"linear", the placement of the ticks is
determined by a starting position `tick0` and a
tick step `dtick` ("linear" is the default
value if `tick0` and `dtick` are provided). If
"array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`.
("array" is the default value if `tickvals` is
provided).
tickprefix
Sets a tick label prefix.
ticks
Determines whether ticks are drawn or not. If
"", this axis' ticks are not drawn. If
"outside" ("inside"), this axis' are drawn
outside (inside) the axis lines.
ticksuffix
Sets a tick label suffix.
ticktext
Sets the text displayed at the ticks position
via `tickvals`. Only has an effect if
`tickmode` is set to "array". Used with
`tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud
for `ticktext`.
tickvals
Sets the values at which ticks on this axis
appear. Only has an effect if `tickmode` is set
to "array". Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud
for `tickvals`.
tickwidth
Sets the tick width (in px).
title
:class:`plotly.graph_objects.layout.ternary.aax
is.Title` instance or dict with compatible
properties
titlefont
Deprecated: Please use
layout.ternary.aaxis.title.font instead. Sets
this axis' title font. Note that the title's
font used to be customized by the now
deprecated `titlefont` attribute.
uirevision
Controls persistence of user-driven changes in
axis `min`, and `title` if in `editable: true`
configuration. Defaults to
`ternary<N>.uirevision`.
Returns
-------
plotly.graph_objs.layout.ternary.Aaxis
"""
| /usr/src/app/target_test_cases/failed_tests__ternary.aaxis.txt | def aaxis(self):
"""
The 'aaxis' property is an instance of Aaxis
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.ternary.Aaxis`
- A dict of string/value properties that will be passed
to the Aaxis constructor
Supported dict properties:
color
Sets default for all colors associated with
this axis all at once: line, font, tick, and
grid colors. Grid color is lightened by
blending this with the plot background
Individual pieces can override this.
dtick
Sets the step in-between ticks on this axis.
Use with `tick0`. Must be a positive number, or
special strings available to "log" and "date"
axes. If the axis `type` is "log", then ticks
are set every 10^(n*dtick) where n is the tick
number. For example, to set a tick mark at 1,
10, 100, 1000, ... set dtick to 1. To set tick
marks at 1, 100, 10000, ... set dtick to 2. To
set tick marks at 1, 5, 25, 125, 625, 3125, ...
set dtick to log_10(5), or 0.69897000433. "log"
has several special values; "L<f>", where `f`
is a positive number, gives ticks linearly
spaced in value (but not position). For example
`tick0` = 0.1, `dtick` = "L0.5" will put ticks
at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10
plus small digits between, use "D1" (all
digits) or "D2" (only 2 and 5). `tick0` is
ignored for "D1" and "D2". If the axis `type`
is "date", then you must convert the time to
milliseconds. For example, to set the interval
between ticks to one day, set `dtick` to
86400000.0. "date" also has special values
"M<n>" gives ticks spaced by a number of
months. `n` must be a positive integer. To set
ticks on the 15th of every third month, set
`tick0` to "2000-01-15" and `dtick` to "M3". To
set ticks every 4 years, set `dtick` to "M48"
exponentformat
Determines a formatting rule for the tick
exponents. For example, consider the number
1,000,000,000. If "none", it appears as
1,000,000,000. If "e", 1e+9. If "E", 1E+9. If
"power", 1x10^9 (with 9 in a super script). If
"SI", 1G. If "B", 1B.
gridcolor
Sets the color of the grid lines.
griddash
Sets the dash style of lines. Set to a dash
type string ("solid", "dot", "dash",
"longdash", "dashdot", or "longdashdot") or a
dash length list in px (eg "5px,10px,2px,2px").
gridwidth
Sets the width (in px) of the grid lines.
hoverformat
Sets the hover text formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see: h
ttps://github.com/d3/d3-format/tree/v1.4.5#d3-
format. And for dates see:
https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two
items to d3's date formatter: "%h" for half of
the year as a decimal number as well as "%{n}f"
for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with
tickformat "%H~%M~%S.%2f" would display
"09~15~23.46"
labelalias
Replacement text for specific tick or hover
labels. For example using {US: 'USA', CA:
'Canada'} changes US to USA and CA to Canada.
The labels we would have shown must match the
keys exactly, after adding any tickprefix or
ticksuffix. For negative numbers the minus sign
symbol used (U+2212) is wider than the regular
ascii dash. That means you need to use −1
instead of -1. labelalias can be used with any
axis type, and both keys (if needed) and values
(if desired) can include html-like tags or
MathJax.
layer
Sets the layer on which this axis is displayed.
If *above traces*, this axis is displayed above
all the subplot's traces If *below traces*,
this axis is displayed below all the subplot's
traces, but above the grid lines. Useful when
used together with scatter-like traces with
`cliponaxis` set to False to show markers
and/or text nodes above this axis.
linecolor
Sets the axis line color.
linewidth
Sets the width (in px) of the axis line.
min
The minimum value visible on this axis. The
maximum is determined by the sum minus the
minimum values of the other two axes. The full
view corresponds to all the minima set to zero.
minexponent
Hide SI prefix for 10^n if |n| is below this
number. This only has an effect when
`tickformat` is "SI" or "B".
nticks
Specifies the maximum number of ticks for the
particular axis. The actual number of ticks
will be chosen automatically to be less than or
equal to `nticks`. Has an effect only if
`tickmode` is set to "auto".
separatethousands
If "true", even 4-digit integers are separated
showexponent
If "all", all exponents are shown besides their
significands. If "first", only the exponent of
the first tick is shown. If "last", only the
exponent of the last tick is shown. If "none",
no exponents appear.
showgrid
Determines whether or not grid lines are drawn.
If True, the grid lines are drawn at every tick
mark.
showline
Determines whether or not a line bounding this
axis is drawn.
showticklabels
Determines whether or not the tick labels are
drawn.
showtickprefix
If "all", all tick labels are displayed with a
prefix. If "first", only the first tick is
displayed with a prefix. If "last", only the
last tick is displayed with a suffix. If
"none", tick prefixes are hidden.
showticksuffix
Same as `showtickprefix` but for tick suffixes.
tick0
Sets the placement of the first tick on this
axis. Use with `dtick`. If the axis `type` is
"log", then you must take the log of your
starting tick (e.g. to set the starting tick to
100, set the `tick0` to 2) except when
`dtick`=*L<f>* (see `dtick` for more info). If
the axis `type` is "date", it should be a date
string, like date data. If the axis `type` is
"category", it should be a number, using the
scale where each category is assigned a serial
number from zero in the order it appears.
tickangle
Sets the angle of the tick labels with respect
to the horizontal. For example, a `tickangle`
of -90 draws the tick labels vertically.
tickcolor
Sets the tick color.
tickfont
Sets the tick font.
tickformat
Sets the tick label formatting rule using d3
formatting mini-languages which are very
similar to those in Python. For numbers, see: h
ttps://github.com/d3/d3-format/tree/v1.4.5#d3-
format. And for dates see:
https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two
items to d3's date formatter: "%h" for half of
the year as a decimal number as well as "%{n}f"
for fractional seconds with n digits. For
example, *2016-10-13 09:15:23.456* with
tickformat "%H~%M~%S.%2f" would display
"09~15~23.46"
tickformatstops
A tuple of :class:`plotly.graph_objects.layout.
ternary.aaxis.Tickformatstop` instances or
dicts with compatible properties
tickformatstopdefaults
When used in a template (as layout.template.lay
out.ternary.aaxis.tickformatstopdefaults), sets
the default property values to use for elements
of layout.ternary.aaxis.tickformatstops
ticklabelstep
Sets the spacing between tick labels as
compared to the spacing between ticks. A value
of 1 (default) means each tick gets a label. A
value of 2 means shows every 2nd label. A
larger value n means only every nth tick is
labeled. `tick0` determines which labels are
shown. Not implemented for axes with `type`
"log" or "multicategory", or when `tickmode` is
"array".
ticklen
Sets the tick length (in px).
tickmode
Sets the tick mode for this axis. If "auto",
the number of ticks is set via `nticks`. If
"linear", the placement of the ticks is
determined by a starting position `tick0` and a
tick step `dtick` ("linear" is the default
value if `tick0` and `dtick` are provided). If
"array", the placement of the ticks is set via
`tickvals` and the tick text is `ticktext`.
("array" is the default value if `tickvals` is
provided).
tickprefix
Sets a tick label prefix.
ticks
Determines whether ticks are drawn or not. If
"", this axis' ticks are not drawn. If
"outside" ("inside"), this axis' are drawn
outside (inside) the axis lines.
ticksuffix
Sets a tick label suffix.
ticktext
Sets the text displayed at the ticks position
via `tickvals`. Only has an effect if
`tickmode` is set to "array". Used with
`tickvals`.
ticktextsrc
Sets the source reference on Chart Studio Cloud
for `ticktext`.
tickvals
Sets the values at which ticks on this axis
appear. Only has an effect if `tickmode` is set
to "array". Used with `ticktext`.
tickvalssrc
Sets the source reference on Chart Studio Cloud
for `tickvals`.
tickwidth
Sets the tick width (in px).
title
:class:`plotly.graph_objects.layout.ternary.aax
is.Title` instance or dict with compatible
properties
titlefont
Deprecated: Please use
layout.ternary.aaxis.title.font instead. Sets
this axis' title font. Note that the title's
font used to be customized by the now
deprecated `titlefont` attribute.
uirevision
Controls persistence of user-driven changes in
axis `min`, and `title` if in `editable: true`
configuration. Defaults to
`ternary<N>.uirevision`.
Returns
-------
plotly.graph_objs.layout.ternary.Aaxis
"""
return self["aaxis"]
| _ternary.aaxis |
plotly.py | 58 | packages/python/plotly/plotly/graph_objs/scatter/_textfont.py | def __init__(
self,
arg=None,
color=None,
colorsrc=None,
family=None,
familysrc=None,
lineposition=None,
linepositionsrc=None,
shadow=None,
shadowsrc=None,
size=None,
sizesrc=None,
style=None,
stylesrc=None,
textcase=None,
textcasesrc=None,
variant=None,
variantsrc=None,
weight=None,
weightsrc=None,
**kwargs,
):
"""
Construct a new Textfont object
Sets the text font.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatter.Textfont`
color
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans", "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
familysrc
Sets the source reference on Chart Studio Cloud for
`family`.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
linepositionsrc
Sets the source reference on Chart Studio Cloud for
`lineposition`.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
shadowsrc
Sets the source reference on Chart Studio Cloud for
`shadow`.
size
sizesrc
Sets the source reference on Chart Studio Cloud for
`size`.
style
Sets whether a font should be styled with a normal or
italic face from its family.
stylesrc
Sets the source reference on Chart Studio Cloud for
`style`.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
textcasesrc
Sets the source reference on Chart Studio Cloud for
`textcase`.
variant
Sets the variant of the font.
variantsrc
Sets the source reference on Chart Studio Cloud for
`variant`.
weight
Sets the weight (or boldness) of the font.
weightsrc
Sets the source reference on Chart Studio Cloud for
`weight`.
Returns
-------
Textfont
"""
| /usr/src/app/target_test_cases/failed_tests__textfont.Textfont.__init__.txt | def __init__(
self,
arg=None,
color=None,
colorsrc=None,
family=None,
familysrc=None,
lineposition=None,
linepositionsrc=None,
shadow=None,
shadowsrc=None,
size=None,
sizesrc=None,
style=None,
stylesrc=None,
textcase=None,
textcasesrc=None,
variant=None,
variantsrc=None,
weight=None,
weightsrc=None,
**kwargs,
):
"""
Construct a new Textfont object
Sets the text font.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatter.Textfont`
color
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
family
HTML font family - the typeface that will be applied by
the web browser. The web browser will only be able to
apply a font if it is available on the system which it
operates. Provide multiple font families, separated by
commas, to indicate the preference in which to apply
fonts if they aren't available on the system. The Chart
Studio Cloud (at https://chart-studio.plotly.com or on-
premise) generates images on a server, where only a
select number of fonts are installed and supported.
These include "Arial", "Balto", "Courier New", "Droid
Sans", "Droid Serif", "Droid Sans Mono", "Gravitas
One", "Old Standard TT", "Open Sans", "Overpass", "PT
Sans Narrow", "Raleway", "Times New Roman".
familysrc
Sets the source reference on Chart Studio Cloud for
`family`.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
linepositionsrc
Sets the source reference on Chart Studio Cloud for
`lineposition`.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
shadowsrc
Sets the source reference on Chart Studio Cloud for
`shadow`.
size
sizesrc
Sets the source reference on Chart Studio Cloud for
`size`.
style
Sets whether a font should be styled with a normal or
italic face from its family.
stylesrc
Sets the source reference on Chart Studio Cloud for
`style`.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
textcasesrc
Sets the source reference on Chart Studio Cloud for
`textcase`.
variant
Sets the variant of the font.
variantsrc
Sets the source reference on Chart Studio Cloud for
`variant`.
weight
Sets the weight (or boldness) of the font.
weightsrc
Sets the source reference on Chart Studio Cloud for
`weight`.
Returns
-------
Textfont
"""
super(Textfont, self).__init__("textfont")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.scatter.Textfont
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scatter.Textfont`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("color", None)
_v = color if color is not None else _v
if _v is not None:
self["color"] = _v
_v = arg.pop("colorsrc", None)
_v = colorsrc if colorsrc is not None else _v
if _v is not None:
self["colorsrc"] = _v
_v = arg.pop("family", None)
_v = family if family is not None else _v
if _v is not None:
self["family"] = _v
_v = arg.pop("familysrc", None)
_v = familysrc if familysrc is not None else _v
if _v is not None:
self["familysrc"] = _v
_v = arg.pop("lineposition", None)
_v = lineposition if lineposition is not None else _v
if _v is not None:
self["lineposition"] = _v
_v = arg.pop("linepositionsrc", None)
_v = linepositionsrc if linepositionsrc is not None else _v
if _v is not None:
self["linepositionsrc"] = _v
_v = arg.pop("shadow", None)
_v = shadow if shadow is not None else _v
if _v is not None:
self["shadow"] = _v
_v = arg.pop("shadowsrc", None)
_v = shadowsrc if shadowsrc is not None else _v
if _v is not None:
self["shadowsrc"] = _v
_v = arg.pop("size", None)
_v = size if size is not None else _v
if _v is not None:
self["size"] = _v
_v = arg.pop("sizesrc", None)
_v = sizesrc if sizesrc is not None else _v
if _v is not None:
self["sizesrc"] = _v
_v = arg.pop("style", None)
_v = style if style is not None else _v
if _v is not None:
self["style"] = _v
_v = arg.pop("stylesrc", None)
_v = stylesrc if stylesrc is not None else _v
if _v is not None:
self["stylesrc"] = _v
_v = arg.pop("textcase", None)
_v = textcase if textcase is not None else _v
if _v is not None:
self["textcase"] = _v
_v = arg.pop("textcasesrc", None)
_v = textcasesrc if textcasesrc is not None else _v
if _v is not None:
self["textcasesrc"] = _v
_v = arg.pop("variant", None)
_v = variant if variant is not None else _v
if _v is not None:
self["variant"] = _v
_v = arg.pop("variantsrc", None)
_v = variantsrc if variantsrc is not None else _v
if _v is not None:
self["variantsrc"] = _v
_v = arg.pop("weight", None)
_v = weight if weight is not None else _v
if _v is not None:
self["weight"] = _v
_v = arg.pop("weightsrc", None)
_v = weightsrc if weightsrc is not None else _v
if _v is not None:
self["weightsrc"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| _textfont.Textfont.__init__ |
plotly.py | 59 | packages/python/plotly/plotly/graph_objs/_treemap.py | def __init__(
self,
arg=None,
branchvalues=None,
count=None,
customdata=None,
customdatasrc=None,
domain=None,
hoverinfo=None,
hoverinfosrc=None,
hoverlabel=None,
hovertemplate=None,
hovertemplatesrc=None,
hovertext=None,
hovertextsrc=None,
ids=None,
idssrc=None,
insidetextfont=None,
labels=None,
labelssrc=None,
legend=None,
legendgrouptitle=None,
legendrank=None,
legendwidth=None,
level=None,
marker=None,
maxdepth=None,
meta=None,
metasrc=None,
name=None,
opacity=None,
outsidetextfont=None,
parents=None,
parentssrc=None,
pathbar=None,
root=None,
sort=None,
stream=None,
text=None,
textfont=None,
textinfo=None,
textposition=None,
textsrc=None,
texttemplate=None,
texttemplatesrc=None,
tiling=None,
uid=None,
uirevision=None,
values=None,
valuessrc=None,
visible=None,
**kwargs,
):
"""
Construct a new Treemap object
Visualize hierarchal data from leaves (and/or outer branches)
towards root with rectangles. The treemap sectors are
determined by the entries in "labels" or "ids" and in
"parents".
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.Treemap`
branchvalues
Determines how the items in `values` are summed. When
set to "total", items in `values` are taken to be value
of all its descendants. When set to "remainder", items
in `values` corresponding to the root and the branches
sectors are taken to be the extra part not part of the
sum of the values at their leaves.
count
Determines default for `values` when it is not
provided, by inferring a 1 for each of the "leaves"
and/or "branches", otherwise 0.
customdata
Assigns extra data each datum. This may be useful when
listening to hover, click and selection events. Note
that, "scatter" traces also appends customdata items in
the markers DOM elements
customdatasrc
Sets the source reference on Chart Studio Cloud for
`customdata`.
domain
:class:`plotly.graph_objects.treemap.Domain` instance
or dict with compatible properties
hoverinfo
Determines which trace information appear on hover. If
`none` or `skip` are set, no information is displayed
upon hovering. But, if `none` is set, click and hover
events are still fired.
hoverinfosrc
Sets the source reference on Chart Studio Cloud for
`hoverinfo`.
hoverlabel
:class:`plotly.graph_objects.treemap.Hoverlabel`
instance or dict with compatible properties
hovertemplate
Template string used for rendering the information that
appear on hover box. Note that this will override
`hoverinfo`. Variables are inserted using %{variable},
for example "y: %{y}" as well as %{xother}, {%_xother},
{%_xother_}, {%xother_}. When showing info for several
points, "xother" will be added to those with different
x positions from the first point. An underscore before
or after "(x|y)other" will add a space on that side,
only when this field is shown. Numbers are formatted
using d3-format's syntax %{variable:d3-format}, for
example "Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. The variables available in
`hovertemplate` are the ones emitted as event data
described at this link
https://plotly.com/javascript/plotlyjs-events/#event-
data. Additionally, every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Finally, the template string has access
to variables `currentPath`, `root`, `entry`,
`percentRoot`, `percentEntry` and `percentParent`.
Anything contained in tag `<extra>` is displayed in the
secondary box, for example
"<extra>{fullData.name}</extra>". To hide the secondary
box completely, use an empty tag `<extra></extra>`.
hovertemplatesrc
Sets the source reference on Chart Studio Cloud for
`hovertemplate`.
hovertext
Sets hover text elements associated with each sector.
If a single string, the same string appears for all
data points. If an array of string, the items are
mapped in order of this trace's sectors. To be seen,
trace `hoverinfo` must contain a "text" flag.
hovertextsrc
Sets the source reference on Chart Studio Cloud for
`hovertext`.
ids
Assigns id labels to each datum. These ids for object
constancy of data points during animation. Should be an
array of strings, not numbers or any other type.
idssrc
Sets the source reference on Chart Studio Cloud for
`ids`.
insidetextfont
Sets the font used for `textinfo` lying inside the
sector.
labels
Sets the labels of each of the sectors.
labelssrc
Sets the source reference on Chart Studio Cloud for
`labels`.
legend
Sets the reference to a legend to show this trace in.
References to these legends are "legend", "legend2",
"legend3", etc. Settings for these legends are set in
the layout, under `layout.legend`, `layout.legend2`,
etc.
legendgrouptitle
:class:`plotly.graph_objects.treemap.Legendgrouptitle`
instance or dict with compatible properties
legendrank
Sets the legend rank for this trace. Items and groups
with smaller ranks are presented on top/left side while
with "reversed" `legend.traceorder` they are on
bottom/right side. The default legendrank is 1000, so
that you can use ranks less than 1000 to place certain
items before all unranked items, and ranks greater than
1000 to go after all unranked items. When having
unranked or equal rank items shapes would be displayed
after traces i.e. according to their order in data and
layout.
legendwidth
Sets the width (in px or fraction) of the legend for
this trace.
level
Sets the level from which this trace hierarchy is
rendered. Set `level` to `''` to start from the root
node in the hierarchy. Must be an "id" if `ids` is
filled in, otherwise plotly attempts to find a matching
item in `labels`.
marker
:class:`plotly.graph_objects.treemap.Marker` instance
or dict with compatible properties
maxdepth
Sets the number of rendered sectors from any given
`level`. Set `maxdepth` to "-1" to render all the
levels in the hierarchy.
meta
Assigns extra meta information associated with this
trace that can be used in various text attributes.
Attributes such as trace `name`, graph, axis and
colorbar `title.text`, annotation `text`
`rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta`
values in an attribute in the same trace, simply use
`%{meta[i]}` where `i` is the index or key of the
`meta` item in question. To access trace `meta` in
layout attributes, use `%{data[n[.meta[i]}` where `i`
is the index or key of the `meta` and `n` is the trace
index.
metasrc
Sets the source reference on Chart Studio Cloud for
`meta`.
name
Sets the trace name. The trace name appears as the
legend item and on hover.
opacity
Sets the opacity of the trace.
outsidetextfont
Sets the font used for `textinfo` lying outside the
sector. This option refers to the root of the hierarchy
presented on top left corner of a treemap graph. Please
note that if a hierarchy has multiple root nodes, this
option won't have any effect and `insidetextfont` would
be used.
parents
Sets the parent sectors for each of the sectors. Empty
string items '' are understood to reference the root
node in the hierarchy. If `ids` is filled, `parents`
items are understood to be "ids" themselves. When `ids`
is not set, plotly attempts to find matching items in
`labels`, but beware they must be unique.
parentssrc
Sets the source reference on Chart Studio Cloud for
`parents`.
pathbar
:class:`plotly.graph_objects.treemap.Pathbar` instance
or dict with compatible properties
root
:class:`plotly.graph_objects.treemap.Root` instance or
dict with compatible properties
sort
Determines whether or not the sectors are reordered
from largest to smallest.
stream
:class:`plotly.graph_objects.treemap.Stream` instance
or dict with compatible properties
text
Sets text elements associated with each sector. If
trace `textinfo` contains a "text" flag, these elements
will be seen on the chart. If trace `hoverinfo`
contains a "text" flag and "hovertext" is not set,
these elements will be seen in the hover labels.
textfont
Sets the font used for `textinfo`.
textinfo
Determines which trace information appear on the graph.
textposition
Sets the positions of the `text` elements.
textsrc
Sets the source reference on Chart Studio Cloud for
`text`.
texttemplate
Template string used for rendering the information text
that appear on points. Note that this will override
`textinfo`. Variables are inserted using %{variable},
for example "y: %{y}". Numbers are formatted using
d3-format's syntax %{variable:d3-format}, for example
"Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. Every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Finally, the template string has access
to variables `currentPath`, `root`, `entry`,
`percentRoot`, `percentEntry`, `percentParent`, `label`
and `value`.
texttemplatesrc
Sets the source reference on Chart Studio Cloud for
`texttemplate`.
tiling
:class:`plotly.graph_objects.treemap.Tiling` instance
or dict with compatible properties
uid
Assign an id to this trace, Use this to provide object
constancy between traces during animations and
transitions.
uirevision
Controls persistence of some user-driven changes to the
trace: `constraintrange` in `parcoords` traces, as well
as some `editable: true` modifications such as `name`
and `colorbar.title`. Defaults to `layout.uirevision`.
Note that other user-driven trace attribute changes are
controlled by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
values
Sets the values associated with each of the sectors.
Use with `branchvalues` to determine how the values are
summed.
valuessrc
Sets the source reference on Chart Studio Cloud for
`values`.
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
Returns
-------
Treemap
"""
| /usr/src/app/target_test_cases/failed_tests__treemap.Treemap.__init__.txt | def __init__(
self,
arg=None,
branchvalues=None,
count=None,
customdata=None,
customdatasrc=None,
domain=None,
hoverinfo=None,
hoverinfosrc=None,
hoverlabel=None,
hovertemplate=None,
hovertemplatesrc=None,
hovertext=None,
hovertextsrc=None,
ids=None,
idssrc=None,
insidetextfont=None,
labels=None,
labelssrc=None,
legend=None,
legendgrouptitle=None,
legendrank=None,
legendwidth=None,
level=None,
marker=None,
maxdepth=None,
meta=None,
metasrc=None,
name=None,
opacity=None,
outsidetextfont=None,
parents=None,
parentssrc=None,
pathbar=None,
root=None,
sort=None,
stream=None,
text=None,
textfont=None,
textinfo=None,
textposition=None,
textsrc=None,
texttemplate=None,
texttemplatesrc=None,
tiling=None,
uid=None,
uirevision=None,
values=None,
valuessrc=None,
visible=None,
**kwargs,
):
"""
Construct a new Treemap object
Visualize hierarchal data from leaves (and/or outer branches)
towards root with rectangles. The treemap sectors are
determined by the entries in "labels" or "ids" and in
"parents".
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.Treemap`
branchvalues
Determines how the items in `values` are summed. When
set to "total", items in `values` are taken to be value
of all its descendants. When set to "remainder", items
in `values` corresponding to the root and the branches
sectors are taken to be the extra part not part of the
sum of the values at their leaves.
count
Determines default for `values` when it is not
provided, by inferring a 1 for each of the "leaves"
and/or "branches", otherwise 0.
customdata
Assigns extra data each datum. This may be useful when
listening to hover, click and selection events. Note
that, "scatter" traces also appends customdata items in
the markers DOM elements
customdatasrc
Sets the source reference on Chart Studio Cloud for
`customdata`.
domain
:class:`plotly.graph_objects.treemap.Domain` instance
or dict with compatible properties
hoverinfo
Determines which trace information appear on hover. If
`none` or `skip` are set, no information is displayed
upon hovering. But, if `none` is set, click and hover
events are still fired.
hoverinfosrc
Sets the source reference on Chart Studio Cloud for
`hoverinfo`.
hoverlabel
:class:`plotly.graph_objects.treemap.Hoverlabel`
instance or dict with compatible properties
hovertemplate
Template string used for rendering the information that
appear on hover box. Note that this will override
`hoverinfo`. Variables are inserted using %{variable},
for example "y: %{y}" as well as %{xother}, {%_xother},
{%_xother_}, {%xother_}. When showing info for several
points, "xother" will be added to those with different
x positions from the first point. An underscore before
or after "(x|y)other" will add a space on that side,
only when this field is shown. Numbers are formatted
using d3-format's syntax %{variable:d3-format}, for
example "Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. The variables available in
`hovertemplate` are the ones emitted as event data
described at this link
https://plotly.com/javascript/plotlyjs-events/#event-
data. Additionally, every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Finally, the template string has access
to variables `currentPath`, `root`, `entry`,
`percentRoot`, `percentEntry` and `percentParent`.
Anything contained in tag `<extra>` is displayed in the
secondary box, for example
"<extra>{fullData.name}</extra>". To hide the secondary
box completely, use an empty tag `<extra></extra>`.
hovertemplatesrc
Sets the source reference on Chart Studio Cloud for
`hovertemplate`.
hovertext
Sets hover text elements associated with each sector.
If a single string, the same string appears for all
data points. If an array of string, the items are
mapped in order of this trace's sectors. To be seen,
trace `hoverinfo` must contain a "text" flag.
hovertextsrc
Sets the source reference on Chart Studio Cloud for
`hovertext`.
ids
Assigns id labels to each datum. These ids for object
constancy of data points during animation. Should be an
array of strings, not numbers or any other type.
idssrc
Sets the source reference on Chart Studio Cloud for
`ids`.
insidetextfont
Sets the font used for `textinfo` lying inside the
sector.
labels
Sets the labels of each of the sectors.
labelssrc
Sets the source reference on Chart Studio Cloud for
`labels`.
legend
Sets the reference to a legend to show this trace in.
References to these legends are "legend", "legend2",
"legend3", etc. Settings for these legends are set in
the layout, under `layout.legend`, `layout.legend2`,
etc.
legendgrouptitle
:class:`plotly.graph_objects.treemap.Legendgrouptitle`
instance or dict with compatible properties
legendrank
Sets the legend rank for this trace. Items and groups
with smaller ranks are presented on top/left side while
with "reversed" `legend.traceorder` they are on
bottom/right side. The default legendrank is 1000, so
that you can use ranks less than 1000 to place certain
items before all unranked items, and ranks greater than
1000 to go after all unranked items. When having
unranked or equal rank items shapes would be displayed
after traces i.e. according to their order in data and
layout.
legendwidth
Sets the width (in px or fraction) of the legend for
this trace.
level
Sets the level from which this trace hierarchy is
rendered. Set `level` to `''` to start from the root
node in the hierarchy. Must be an "id" if `ids` is
filled in, otherwise plotly attempts to find a matching
item in `labels`.
marker
:class:`plotly.graph_objects.treemap.Marker` instance
or dict with compatible properties
maxdepth
Sets the number of rendered sectors from any given
`level`. Set `maxdepth` to "-1" to render all the
levels in the hierarchy.
meta
Assigns extra meta information associated with this
trace that can be used in various text attributes.
Attributes such as trace `name`, graph, axis and
colorbar `title.text`, annotation `text`
`rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta`
values in an attribute in the same trace, simply use
`%{meta[i]}` where `i` is the index or key of the
`meta` item in question. To access trace `meta` in
layout attributes, use `%{data[n[.meta[i]}` where `i`
is the index or key of the `meta` and `n` is the trace
index.
metasrc
Sets the source reference on Chart Studio Cloud for
`meta`.
name
Sets the trace name. The trace name appears as the
legend item and on hover.
opacity
Sets the opacity of the trace.
outsidetextfont
Sets the font used for `textinfo` lying outside the
sector. This option refers to the root of the hierarchy
presented on top left corner of a treemap graph. Please
note that if a hierarchy has multiple root nodes, this
option won't have any effect and `insidetextfont` would
be used.
parents
Sets the parent sectors for each of the sectors. Empty
string items '' are understood to reference the root
node in the hierarchy. If `ids` is filled, `parents`
items are understood to be "ids" themselves. When `ids`
is not set, plotly attempts to find matching items in
`labels`, but beware they must be unique.
parentssrc
Sets the source reference on Chart Studio Cloud for
`parents`.
pathbar
:class:`plotly.graph_objects.treemap.Pathbar` instance
or dict with compatible properties
root
:class:`plotly.graph_objects.treemap.Root` instance or
dict with compatible properties
sort
Determines whether or not the sectors are reordered
from largest to smallest.
stream
:class:`plotly.graph_objects.treemap.Stream` instance
or dict with compatible properties
text
Sets text elements associated with each sector. If
trace `textinfo` contains a "text" flag, these elements
will be seen on the chart. If trace `hoverinfo`
contains a "text" flag and "hovertext" is not set,
these elements will be seen in the hover labels.
textfont
Sets the font used for `textinfo`.
textinfo
Determines which trace information appear on the graph.
textposition
Sets the positions of the `text` elements.
textsrc
Sets the source reference on Chart Studio Cloud for
`text`.
texttemplate
Template string used for rendering the information text
that appear on points. Note that this will override
`textinfo`. Variables are inserted using %{variable},
for example "y: %{y}". Numbers are formatted using
d3-format's syntax %{variable:d3-format}, for example
"Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. Every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Finally, the template string has access
to variables `currentPath`, `root`, `entry`,
`percentRoot`, `percentEntry`, `percentParent`, `label`
and `value`.
texttemplatesrc
Sets the source reference on Chart Studio Cloud for
`texttemplate`.
tiling
:class:`plotly.graph_objects.treemap.Tiling` instance
or dict with compatible properties
uid
Assign an id to this trace, Use this to provide object
constancy between traces during animations and
transitions.
uirevision
Controls persistence of some user-driven changes to the
trace: `constraintrange` in `parcoords` traces, as well
as some `editable: true` modifications such as `name`
and `colorbar.title`. Defaults to `layout.uirevision`.
Note that other user-driven trace attribute changes are
controlled by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
values
Sets the values associated with each of the sectors.
Use with `branchvalues` to determine how the values are
summed.
valuessrc
Sets the source reference on Chart Studio Cloud for
`values`.
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
Returns
-------
Treemap
"""
super(Treemap, self).__init__("treemap")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.Treemap
constructor must be a dict or
an instance of :class:`plotly.graph_objs.Treemap`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("branchvalues", None)
_v = branchvalues if branchvalues is not None else _v
if _v is not None:
self["branchvalues"] = _v
_v = arg.pop("count", None)
_v = count if count is not None else _v
if _v is not None:
self["count"] = _v
_v = arg.pop("customdata", None)
_v = customdata if customdata is not None else _v
if _v is not None:
self["customdata"] = _v
_v = arg.pop("customdatasrc", None)
_v = customdatasrc if customdatasrc is not None else _v
if _v is not None:
self["customdatasrc"] = _v
_v = arg.pop("domain", None)
_v = domain if domain is not None else _v
if _v is not None:
self["domain"] = _v
_v = arg.pop("hoverinfo", None)
_v = hoverinfo if hoverinfo is not None else _v
if _v is not None:
self["hoverinfo"] = _v
_v = arg.pop("hoverinfosrc", None)
_v = hoverinfosrc if hoverinfosrc is not None else _v
if _v is not None:
self["hoverinfosrc"] = _v
_v = arg.pop("hoverlabel", None)
_v = hoverlabel if hoverlabel is not None else _v
if _v is not None:
self["hoverlabel"] = _v
_v = arg.pop("hovertemplate", None)
_v = hovertemplate if hovertemplate is not None else _v
if _v is not None:
self["hovertemplate"] = _v
_v = arg.pop("hovertemplatesrc", None)
_v = hovertemplatesrc if hovertemplatesrc is not None else _v
if _v is not None:
self["hovertemplatesrc"] = _v
_v = arg.pop("hovertext", None)
_v = hovertext if hovertext is not None else _v
if _v is not None:
self["hovertext"] = _v
_v = arg.pop("hovertextsrc", None)
_v = hovertextsrc if hovertextsrc is not None else _v
if _v is not None:
self["hovertextsrc"] = _v
_v = arg.pop("ids", None)
_v = ids if ids is not None else _v
if _v is not None:
self["ids"] = _v
_v = arg.pop("idssrc", None)
_v = idssrc if idssrc is not None else _v
if _v is not None:
self["idssrc"] = _v
_v = arg.pop("insidetextfont", None)
_v = insidetextfont if insidetextfont is not None else _v
if _v is not None:
self["insidetextfont"] = _v
_v = arg.pop("labels", None)
_v = labels if labels is not None else _v
if _v is not None:
self["labels"] = _v
_v = arg.pop("labelssrc", None)
_v = labelssrc if labelssrc is not None else _v
if _v is not None:
self["labelssrc"] = _v
_v = arg.pop("legend", None)
_v = legend if legend is not None else _v
if _v is not None:
self["legend"] = _v
_v = arg.pop("legendgrouptitle", None)
_v = legendgrouptitle if legendgrouptitle is not None else _v
if _v is not None:
self["legendgrouptitle"] = _v
_v = arg.pop("legendrank", None)
_v = legendrank if legendrank is not None else _v
if _v is not None:
self["legendrank"] = _v
_v = arg.pop("legendwidth", None)
_v = legendwidth if legendwidth is not None else _v
if _v is not None:
self["legendwidth"] = _v
_v = arg.pop("level", None)
_v = level if level is not None else _v
if _v is not None:
self["level"] = _v
_v = arg.pop("marker", None)
_v = marker if marker is not None else _v
if _v is not None:
self["marker"] = _v
_v = arg.pop("maxdepth", None)
_v = maxdepth if maxdepth is not None else _v
if _v is not None:
self["maxdepth"] = _v
_v = arg.pop("meta", None)
_v = meta if meta is not None else _v
if _v is not None:
self["meta"] = _v
_v = arg.pop("metasrc", None)
_v = metasrc if metasrc is not None else _v
if _v is not None:
self["metasrc"] = _v
_v = arg.pop("name", None)
_v = name if name is not None else _v
if _v is not None:
self["name"] = _v
_v = arg.pop("opacity", None)
_v = opacity if opacity is not None else _v
if _v is not None:
self["opacity"] = _v
_v = arg.pop("outsidetextfont", None)
_v = outsidetextfont if outsidetextfont is not None else _v
if _v is not None:
self["outsidetextfont"] = _v
_v = arg.pop("parents", None)
_v = parents if parents is not None else _v
if _v is not None:
self["parents"] = _v
_v = arg.pop("parentssrc", None)
_v = parentssrc if parentssrc is not None else _v
if _v is not None:
self["parentssrc"] = _v
_v = arg.pop("pathbar", None)
_v = pathbar if pathbar is not None else _v
if _v is not None:
self["pathbar"] = _v
_v = arg.pop("root", None)
_v = root if root is not None else _v
if _v is not None:
self["root"] = _v
_v = arg.pop("sort", None)
_v = sort if sort is not None else _v
if _v is not None:
self["sort"] = _v
_v = arg.pop("stream", None)
_v = stream if stream is not None else _v
if _v is not None:
self["stream"] = _v
_v = arg.pop("text", None)
_v = text if text is not None else _v
if _v is not None:
self["text"] = _v
_v = arg.pop("textfont", None)
_v = textfont if textfont is not None else _v
if _v is not None:
self["textfont"] = _v
_v = arg.pop("textinfo", None)
_v = textinfo if textinfo is not None else _v
if _v is not None:
self["textinfo"] = _v
_v = arg.pop("textposition", None)
_v = textposition if textposition is not None else _v
if _v is not None:
self["textposition"] = _v
_v = arg.pop("textsrc", None)
_v = textsrc if textsrc is not None else _v
if _v is not None:
self["textsrc"] = _v
_v = arg.pop("texttemplate", None)
_v = texttemplate if texttemplate is not None else _v
if _v is not None:
self["texttemplate"] = _v
_v = arg.pop("texttemplatesrc", None)
_v = texttemplatesrc if texttemplatesrc is not None else _v
if _v is not None:
self["texttemplatesrc"] = _v
_v = arg.pop("tiling", None)
_v = tiling if tiling is not None else _v
if _v is not None:
self["tiling"] = _v
_v = arg.pop("uid", None)
_v = uid if uid is not None else _v
if _v is not None:
self["uid"] = _v
_v = arg.pop("uirevision", None)
_v = uirevision if uirevision is not None else _v
if _v is not None:
self["uirevision"] = _v
_v = arg.pop("values", None)
_v = values if values is not None else _v
if _v is not None:
self["values"] = _v
_v = arg.pop("valuessrc", None)
_v = valuessrc if valuessrc is not None else _v
if _v is not None:
self["valuessrc"] = _v
_v = arg.pop("visible", None)
_v = visible if visible is not None else _v
if _v is not None:
self["visible"] = _v
# Read-only literals
# ------------------
self._props["type"] = "treemap"
arg.pop("type", None)
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| _treemap.Treemap.__init__ |
plotly.py | 60 | packages/python/plotly/plotly/graph_objs/_treemap.py | def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.treemap.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Supported dict properties:
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.colorscale`. Has an
effect only if colors is set to a numerical
array. In case `colorscale` is unspecified or
`autocolorscale` is true, the default palette
will be chosen according to whether numbers in
the `color` array are all positive, all
negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
colors) or the bounds set in `marker.cmin` and
`marker.cmax` Has an effect only if colors is
set to a numerical array. Defaults to `false`
when `marker.cmin` and `marker.cmax` are set by
the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if colors is set to a numerical
array. Value should have the same units as
colors and if set, `marker.cmin` must be set as
well.
cmid
Sets the mid-point of the color domain by
scaling `marker.cmin` and/or `marker.cmax` to
be equidistant to this point. Has an effect
only if colors is set to a numerical array.
Value should have the same units as colors. Has
no effect when `marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if colors is set to a numerical
array. Value should have the same units as
colors and if set, `marker.cmax` must be set as
well.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.treemap.marker.Col
orBar` instance or dict with compatible
properties
colors
Sets the color of each sector of this trace. If
not specified, the default trace color set is
used to pick the sector colors.
colorscale
Sets the colorscale. Has an effect only if
colors is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `marker.cmin` and
`marker.cmax`. Alternatively, `colorscale` may
be a palette name string of the following list:
Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorssrc
Sets the source reference on Chart Studio Cloud
for `colors`.
cornerradius
Sets the maximum rounding of corners (in px).
depthfade
Determines if the sector colors are faded
towards the background from the leaves up to
the headers. This option is unavailable when a
`colorscale` is present, defaults to false when
`marker.colors` is set, but otherwise defaults
to true. When set to "reversed", the fading
direction is inverted, that is the top elements
within hierarchy are drawn with fully saturated
colors while the leaves are faded towards the
background color.
line
:class:`plotly.graph_objects.treemap.marker.Lin
e` instance or dict with compatible properties
pad
:class:`plotly.graph_objects.treemap.marker.Pad
` instance or dict with compatible properties
pattern
Sets the pattern within the marker.
reversescale
Reverses the color mapping if true. Has an
effect only if colors is set to a numerical
array. If true, `marker.cmin` will correspond
to the last color in the array and
`marker.cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
colors is set to a numerical array.
Returns
-------
plotly.graph_objs.treemap.Marker
"""
| /usr/src/app/target_test_cases/failed_tests__treemap.marker.txt | def marker(self):
"""
The 'marker' property is an instance of Marker
that may be specified as:
- An instance of :class:`plotly.graph_objs.treemap.Marker`
- A dict of string/value properties that will be passed
to the Marker constructor
Supported dict properties:
autocolorscale
Determines whether the colorscale is a default
palette (`autocolorscale: true`) or the palette
determined by `marker.colorscale`. Has an
effect only if colors is set to a numerical
array. In case `colorscale` is unspecified or
`autocolorscale` is true, the default palette
will be chosen according to whether numbers in
the `color` array are all positive, all
negative or mixed.
cauto
Determines whether or not the color domain is
computed with respect to the input data (here
colors) or the bounds set in `marker.cmin` and
`marker.cmax` Has an effect only if colors is
set to a numerical array. Defaults to `false`
when `marker.cmin` and `marker.cmax` are set by
the user.
cmax
Sets the upper bound of the color domain. Has
an effect only if colors is set to a numerical
array. Value should have the same units as
colors and if set, `marker.cmin` must be set as
well.
cmid
Sets the mid-point of the color domain by
scaling `marker.cmin` and/or `marker.cmax` to
be equidistant to this point. Has an effect
only if colors is set to a numerical array.
Value should have the same units as colors. Has
no effect when `marker.cauto` is `false`.
cmin
Sets the lower bound of the color domain. Has
an effect only if colors is set to a numerical
array. Value should have the same units as
colors and if set, `marker.cmax` must be set as
well.
coloraxis
Sets a reference to a shared color axis.
References to these shared color axes are
"coloraxis", "coloraxis2", "coloraxis3", etc.
Settings for these shared color axes are set in
the layout, under `layout.coloraxis`,
`layout.coloraxis2`, etc. Note that multiple
color scales can be linked to the same color
axis.
colorbar
:class:`plotly.graph_objects.treemap.marker.Col
orBar` instance or dict with compatible
properties
colors
Sets the color of each sector of this trace. If
not specified, the default trace color set is
used to pick the sector colors.
colorscale
Sets the colorscale. Has an effect only if
colors is set to a numerical array. The
colorscale must be an array containing arrays
mapping a normalized value to an rgb, rgba,
hex, hsl, hsv, or named color string. At
minimum, a mapping for the lowest (0) and
highest (1) values are required. For example,
`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.
To control the bounds of the colorscale in
color space, use `marker.cmin` and
`marker.cmax`. Alternatively, `colorscale` may
be a palette name string of the following list:
Blackbody,Bluered,Blues,Cividis,Earth,Electric,
Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,Rd
Bu,Reds,Viridis,YlGnBu,YlOrRd.
colorssrc
Sets the source reference on Chart Studio Cloud
for `colors`.
cornerradius
Sets the maximum rounding of corners (in px).
depthfade
Determines if the sector colors are faded
towards the background from the leaves up to
the headers. This option is unavailable when a
`colorscale` is present, defaults to false when
`marker.colors` is set, but otherwise defaults
to true. When set to "reversed", the fading
direction is inverted, that is the top elements
within hierarchy are drawn with fully saturated
colors while the leaves are faded towards the
background color.
line
:class:`plotly.graph_objects.treemap.marker.Lin
e` instance or dict with compatible properties
pad
:class:`plotly.graph_objects.treemap.marker.Pad
` instance or dict with compatible properties
pattern
Sets the pattern within the marker.
reversescale
Reverses the color mapping if true. Has an
effect only if colors is set to a numerical
array. If true, `marker.cmin` will correspond
to the last color in the array and
`marker.cmax` will correspond to the first
color.
showscale
Determines whether or not a colorbar is
displayed for this trace. Has an effect only if
colors is set to a numerical array.
Returns
-------
plotly.graph_objs.treemap.Marker
"""
return self["marker"]
| _treemap.marker |
plotly.py | 61 | packages/python/plotly/plotly/figure_factory/_trisurf.py | def create_trisurf(
x,
y,
z,
simplices,
colormap=None,
show_colorbar=True,
scale=None,
color_func=None,
title="Trisurf Plot",
plot_edges=True,
showbackground=True,
backgroundcolor="rgb(230, 230, 230)",
gridcolor="rgb(255, 255, 255)",
zerolinecolor="rgb(255, 255, 255)",
edges_color="rgb(50, 50, 50)",
height=800,
width=800,
aspectratio=None,
):
"""
Returns figure for a triangulated surface plot
:param (array) x: data values of x in a 1D array
:param (array) y: data values of y in a 1D array
:param (array) z: data values of z in a 1D array
:param (array) simplices: an array of shape (ntri, 3) where ntri is
the number of triangles in the triangularization. Each row of the
array contains the indicies of the verticies of each triangle
:param (str|tuple|list) colormap: either a plotly scale name, an rgb
or hex color, a color tuple or a list of colors. An rgb color is
of the form 'rgb(x, y, z)' where x, y, z belong to the interval
[0, 255] and a color tuple is a tuple of the form (a, b, c) where
a, b and c belong to [0, 1]. If colormap is a list, it must
contain the valid color types aforementioned as its members
:param (bool) show_colorbar: determines if colorbar is visible
:param (list|array) scale: sets the scale values to be used if a non-
linearly interpolated colormap is desired. If left as None, a
linear interpolation between the colors will be excecuted
:param (function|list) color_func: The parameter that determines the
coloring of the surface. Takes either a function with 3 arguments
x, y, z or a list/array of color values the same length as
simplices. If None, coloring will only depend on the z axis
:param (str) title: title of the plot
:param (bool) plot_edges: determines if the triangles on the trisurf
are visible
:param (bool) showbackground: makes background in plot visible
:param (str) backgroundcolor: color of background. Takes a string of
the form 'rgb(x,y,z)' x,y,z are between 0 and 255 inclusive
:param (str) gridcolor: color of the gridlines besides the axes. Takes
a string of the form 'rgb(x,y,z)' x,y,z are between 0 and 255
inclusive
:param (str) zerolinecolor: color of the axes. Takes a string of the
form 'rgb(x,y,z)' x,y,z are between 0 and 255 inclusive
:param (str) edges_color: color of the edges, if plot_edges is True
:param (int|float) height: the height of the plot (in pixels)
:param (int|float) width: the width of the plot (in pixels)
:param (dict) aspectratio: a dictionary of the aspect ratio values for
the x, y and z axes. 'x', 'y' and 'z' take (int|float) values
Example 1: Sphere
>>> # Necessary Imports for Trisurf
>>> import numpy as np
>>> from scipy.spatial import Delaunay
>>> from plotly.figure_factory import create_trisurf
>>> from plotly.graph_objs import graph_objs
>>> # Make data for plot
>>> u = np.linspace(0, 2*np.pi, 20)
>>> v = np.linspace(0, np.pi, 20)
>>> u,v = np.meshgrid(u,v)
>>> u = u.flatten()
>>> v = v.flatten()
>>> x = np.sin(v)*np.cos(u)
>>> y = np.sin(v)*np.sin(u)
>>> z = np.cos(v)
>>> points2D = np.vstack([u,v]).T
>>> tri = Delaunay(points2D)
>>> simplices = tri.simplices
>>> # Create a figure
>>> fig1 = create_trisurf(x=x, y=y, z=z, colormap="Rainbow",
... simplices=simplices)
Example 2: Torus
>>> # Necessary Imports for Trisurf
>>> import numpy as np
>>> from scipy.spatial import Delaunay
>>> from plotly.figure_factory import create_trisurf
>>> from plotly.graph_objs import graph_objs
>>> # Make data for plot
>>> u = np.linspace(0, 2*np.pi, 20)
>>> v = np.linspace(0, 2*np.pi, 20)
>>> u,v = np.meshgrid(u,v)
>>> u = u.flatten()
>>> v = v.flatten()
>>> x = (3 + (np.cos(v)))*np.cos(u)
>>> y = (3 + (np.cos(v)))*np.sin(u)
>>> z = np.sin(v)
>>> points2D = np.vstack([u,v]).T
>>> tri = Delaunay(points2D)
>>> simplices = tri.simplices
>>> # Create a figure
>>> fig1 = create_trisurf(x=x, y=y, z=z, colormap="Viridis",
... simplices=simplices)
Example 3: Mobius Band
>>> # Necessary Imports for Trisurf
>>> import numpy as np
>>> from scipy.spatial import Delaunay
>>> from plotly.figure_factory import create_trisurf
>>> from plotly.graph_objs import graph_objs
>>> # Make data for plot
>>> u = np.linspace(0, 2*np.pi, 24)
>>> v = np.linspace(-1, 1, 8)
>>> u,v = np.meshgrid(u,v)
>>> u = u.flatten()
>>> v = v.flatten()
>>> tp = 1 + 0.5*v*np.cos(u/2.)
>>> x = tp*np.cos(u)
>>> y = tp*np.sin(u)
>>> z = 0.5*v*np.sin(u/2.)
>>> points2D = np.vstack([u,v]).T
>>> tri = Delaunay(points2D)
>>> simplices = tri.simplices
>>> # Create a figure
>>> fig1 = create_trisurf(x=x, y=y, z=z, colormap=[(0.2, 0.4, 0.6), (1, 1, 1)],
... simplices=simplices)
Example 4: Using a Custom Colormap Function with Light Cone
>>> # Necessary Imports for Trisurf
>>> import numpy as np
>>> from scipy.spatial import Delaunay
>>> from plotly.figure_factory import create_trisurf
>>> from plotly.graph_objs import graph_objs
>>> # Make data for plot
>>> u=np.linspace(-np.pi, np.pi, 30)
>>> v=np.linspace(-np.pi, np.pi, 30)
>>> u,v=np.meshgrid(u,v)
>>> u=u.flatten()
>>> v=v.flatten()
>>> x = u
>>> y = u*np.cos(v)
>>> z = u*np.sin(v)
>>> points2D = np.vstack([u,v]).T
>>> tri = Delaunay(points2D)
>>> simplices = tri.simplices
>>> # Define distance function
>>> def dist_origin(x, y, z):
... return np.sqrt((1.0 * x)**2 + (1.0 * y)**2 + (1.0 * z)**2)
>>> # Create a figure
>>> fig1 = create_trisurf(x=x, y=y, z=z,
... colormap=['#FFFFFF', '#E4FFFE',
... '#A4F6F9', '#FF99FE',
... '#BA52ED'],
... scale=[0, 0.6, 0.71, 0.89, 1],
... simplices=simplices,
... color_func=dist_origin)
Example 5: Enter color_func as a list of colors
>>> # Necessary Imports for Trisurf
>>> import numpy as np
>>> from scipy.spatial import Delaunay
>>> import random
>>> from plotly.figure_factory import create_trisurf
>>> from plotly.graph_objs import graph_objs
>>> # Make data for plot
>>> u=np.linspace(-np.pi, np.pi, 30)
>>> v=np.linspace(-np.pi, np.pi, 30)
>>> u,v=np.meshgrid(u,v)
>>> u=u.flatten()
>>> v=v.flatten()
>>> x = u
>>> y = u*np.cos(v)
>>> z = u*np.sin(v)
>>> points2D = np.vstack([u,v]).T
>>> tri = Delaunay(points2D)
>>> simplices = tri.simplices
>>> colors = []
>>> color_choices = ['rgb(0, 0, 0)', '#6c4774', '#d6c7dd']
>>> for index in range(len(simplices)):
... colors.append(random.choice(color_choices))
>>> fig = create_trisurf(
... x, y, z, simplices,
... color_func=colors,
... show_colorbar=True,
... edges_color='rgb(2, 85, 180)',
... title=' Modern Art'
... )
"""
| /usr/src/app/target_test_cases/failed_tests__trisurf.create_trisurf.txt | def create_trisurf(
x,
y,
z,
simplices,
colormap=None,
show_colorbar=True,
scale=None,
color_func=None,
title="Trisurf Plot",
plot_edges=True,
showbackground=True,
backgroundcolor="rgb(230, 230, 230)",
gridcolor="rgb(255, 255, 255)",
zerolinecolor="rgb(255, 255, 255)",
edges_color="rgb(50, 50, 50)",
height=800,
width=800,
aspectratio=None,
):
"""
Returns figure for a triangulated surface plot
:param (array) x: data values of x in a 1D array
:param (array) y: data values of y in a 1D array
:param (array) z: data values of z in a 1D array
:param (array) simplices: an array of shape (ntri, 3) where ntri is
the number of triangles in the triangularization. Each row of the
array contains the indicies of the verticies of each triangle
:param (str|tuple|list) colormap: either a plotly scale name, an rgb
or hex color, a color tuple or a list of colors. An rgb color is
of the form 'rgb(x, y, z)' where x, y, z belong to the interval
[0, 255] and a color tuple is a tuple of the form (a, b, c) where
a, b and c belong to [0, 1]. If colormap is a list, it must
contain the valid color types aforementioned as its members
:param (bool) show_colorbar: determines if colorbar is visible
:param (list|array) scale: sets the scale values to be used if a non-
linearly interpolated colormap is desired. If left as None, a
linear interpolation between the colors will be excecuted
:param (function|list) color_func: The parameter that determines the
coloring of the surface. Takes either a function with 3 arguments
x, y, z or a list/array of color values the same length as
simplices. If None, coloring will only depend on the z axis
:param (str) title: title of the plot
:param (bool) plot_edges: determines if the triangles on the trisurf
are visible
:param (bool) showbackground: makes background in plot visible
:param (str) backgroundcolor: color of background. Takes a string of
the form 'rgb(x,y,z)' x,y,z are between 0 and 255 inclusive
:param (str) gridcolor: color of the gridlines besides the axes. Takes
a string of the form 'rgb(x,y,z)' x,y,z are between 0 and 255
inclusive
:param (str) zerolinecolor: color of the axes. Takes a string of the
form 'rgb(x,y,z)' x,y,z are between 0 and 255 inclusive
:param (str) edges_color: color of the edges, if plot_edges is True
:param (int|float) height: the height of the plot (in pixels)
:param (int|float) width: the width of the plot (in pixels)
:param (dict) aspectratio: a dictionary of the aspect ratio values for
the x, y and z axes. 'x', 'y' and 'z' take (int|float) values
Example 1: Sphere
>>> # Necessary Imports for Trisurf
>>> import numpy as np
>>> from scipy.spatial import Delaunay
>>> from plotly.figure_factory import create_trisurf
>>> from plotly.graph_objs import graph_objs
>>> # Make data for plot
>>> u = np.linspace(0, 2*np.pi, 20)
>>> v = np.linspace(0, np.pi, 20)
>>> u,v = np.meshgrid(u,v)
>>> u = u.flatten()
>>> v = v.flatten()
>>> x = np.sin(v)*np.cos(u)
>>> y = np.sin(v)*np.sin(u)
>>> z = np.cos(v)
>>> points2D = np.vstack([u,v]).T
>>> tri = Delaunay(points2D)
>>> simplices = tri.simplices
>>> # Create a figure
>>> fig1 = create_trisurf(x=x, y=y, z=z, colormap="Rainbow",
... simplices=simplices)
Example 2: Torus
>>> # Necessary Imports for Trisurf
>>> import numpy as np
>>> from scipy.spatial import Delaunay
>>> from plotly.figure_factory import create_trisurf
>>> from plotly.graph_objs import graph_objs
>>> # Make data for plot
>>> u = np.linspace(0, 2*np.pi, 20)
>>> v = np.linspace(0, 2*np.pi, 20)
>>> u,v = np.meshgrid(u,v)
>>> u = u.flatten()
>>> v = v.flatten()
>>> x = (3 + (np.cos(v)))*np.cos(u)
>>> y = (3 + (np.cos(v)))*np.sin(u)
>>> z = np.sin(v)
>>> points2D = np.vstack([u,v]).T
>>> tri = Delaunay(points2D)
>>> simplices = tri.simplices
>>> # Create a figure
>>> fig1 = create_trisurf(x=x, y=y, z=z, colormap="Viridis",
... simplices=simplices)
Example 3: Mobius Band
>>> # Necessary Imports for Trisurf
>>> import numpy as np
>>> from scipy.spatial import Delaunay
>>> from plotly.figure_factory import create_trisurf
>>> from plotly.graph_objs import graph_objs
>>> # Make data for plot
>>> u = np.linspace(0, 2*np.pi, 24)
>>> v = np.linspace(-1, 1, 8)
>>> u,v = np.meshgrid(u,v)
>>> u = u.flatten()
>>> v = v.flatten()
>>> tp = 1 + 0.5*v*np.cos(u/2.)
>>> x = tp*np.cos(u)
>>> y = tp*np.sin(u)
>>> z = 0.5*v*np.sin(u/2.)
>>> points2D = np.vstack([u,v]).T
>>> tri = Delaunay(points2D)
>>> simplices = tri.simplices
>>> # Create a figure
>>> fig1 = create_trisurf(x=x, y=y, z=z, colormap=[(0.2, 0.4, 0.6), (1, 1, 1)],
... simplices=simplices)
Example 4: Using a Custom Colormap Function with Light Cone
>>> # Necessary Imports for Trisurf
>>> import numpy as np
>>> from scipy.spatial import Delaunay
>>> from plotly.figure_factory import create_trisurf
>>> from plotly.graph_objs import graph_objs
>>> # Make data for plot
>>> u=np.linspace(-np.pi, np.pi, 30)
>>> v=np.linspace(-np.pi, np.pi, 30)
>>> u,v=np.meshgrid(u,v)
>>> u=u.flatten()
>>> v=v.flatten()
>>> x = u
>>> y = u*np.cos(v)
>>> z = u*np.sin(v)
>>> points2D = np.vstack([u,v]).T
>>> tri = Delaunay(points2D)
>>> simplices = tri.simplices
>>> # Define distance function
>>> def dist_origin(x, y, z):
... return np.sqrt((1.0 * x)**2 + (1.0 * y)**2 + (1.0 * z)**2)
>>> # Create a figure
>>> fig1 = create_trisurf(x=x, y=y, z=z,
... colormap=['#FFFFFF', '#E4FFFE',
... '#A4F6F9', '#FF99FE',
... '#BA52ED'],
... scale=[0, 0.6, 0.71, 0.89, 1],
... simplices=simplices,
... color_func=dist_origin)
Example 5: Enter color_func as a list of colors
>>> # Necessary Imports for Trisurf
>>> import numpy as np
>>> from scipy.spatial import Delaunay
>>> import random
>>> from plotly.figure_factory import create_trisurf
>>> from plotly.graph_objs import graph_objs
>>> # Make data for plot
>>> u=np.linspace(-np.pi, np.pi, 30)
>>> v=np.linspace(-np.pi, np.pi, 30)
>>> u,v=np.meshgrid(u,v)
>>> u=u.flatten()
>>> v=v.flatten()
>>> x = u
>>> y = u*np.cos(v)
>>> z = u*np.sin(v)
>>> points2D = np.vstack([u,v]).T
>>> tri = Delaunay(points2D)
>>> simplices = tri.simplices
>>> colors = []
>>> color_choices = ['rgb(0, 0, 0)', '#6c4774', '#d6c7dd']
>>> for index in range(len(simplices)):
... colors.append(random.choice(color_choices))
>>> fig = create_trisurf(
... x, y, z, simplices,
... color_func=colors,
... show_colorbar=True,
... edges_color='rgb(2, 85, 180)',
... title=' Modern Art'
... )
"""
if aspectratio is None:
aspectratio = {"x": 1, "y": 1, "z": 1}
# Validate colormap
clrs.validate_colors(colormap)
colormap, scale = clrs.convert_colors_to_same_type(
colormap, colortype="tuple", return_default_colors=True, scale=scale
)
data1 = trisurf(
x,
y,
z,
simplices,
show_colorbar=show_colorbar,
color_func=color_func,
colormap=colormap,
scale=scale,
edges_color=edges_color,
plot_edges=plot_edges,
)
axis = dict(
showbackground=showbackground,
backgroundcolor=backgroundcolor,
gridcolor=gridcolor,
zerolinecolor=zerolinecolor,
)
layout = graph_objs.Layout(
title=title,
width=width,
height=height,
scene=graph_objs.layout.Scene(
xaxis=graph_objs.layout.scene.XAxis(**axis),
yaxis=graph_objs.layout.scene.YAxis(**axis),
zaxis=graph_objs.layout.scene.ZAxis(**axis),
aspectratio=dict(
x=aspectratio["x"], y=aspectratio["y"], z=aspectratio["z"]
),
),
)
return graph_objs.Figure(data=data1, layout=layout)
| _trisurf.create_trisurf |
plotly.py | 62 | packages/python/plotly/plotly/graph_objs/layout/_updatemenu.py | def __init__(
self,
arg=None,
active=None,
bgcolor=None,
bordercolor=None,
borderwidth=None,
buttons=None,
buttondefaults=None,
direction=None,
font=None,
name=None,
pad=None,
showactive=None,
templateitemname=None,
type=None,
visible=None,
x=None,
xanchor=None,
y=None,
yanchor=None,
**kwargs,
):
"""
Construct a new Updatemenu object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.layout.Updatemenu`
active
Determines which button (by index starting from 0) is
considered active.
bgcolor
Sets the background color of the update menu buttons.
bordercolor
Sets the color of the border enclosing the update menu.
borderwidth
Sets the width (in px) of the border enclosing the
update menu.
buttons
A tuple of
:class:`plotly.graph_objects.layout.updatemenu.Button`
instances or dicts with compatible properties
buttondefaults
When used in a template (as
layout.template.layout.updatemenu.buttondefaults), sets
the default property values to use for elements of
layout.updatemenu.buttons
direction
Determines the direction in which the buttons are laid
out, whether in a dropdown menu or a row/column of
buttons. For `left` and `up`, the buttons will still
appear in left-to-right or top-to-bottom order
respectively.
font
Sets the font of the update menu button text.
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
pad
Sets the padding around the buttons or dropdown menu.
showactive
Highlights active dropdown item or active button if
true.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
type
Determines whether the buttons are accessible via a
dropdown menu or whether the buttons are stacked
horizontally or vertically
visible
Determines whether or not the update menu is visible.
x
Sets the x position (in normalized coordinates) of the
update menu.
xanchor
Sets the update menu's horizontal position anchor. This
anchor binds the `x` position to the "left", "center"
or "right" of the range selector.
y
Sets the y position (in normalized coordinates) of the
update menu.
yanchor
Sets the update menu's vertical position anchor This
anchor binds the `y` position to the "top", "middle" or
"bottom" of the range selector.
Returns
-------
Updatemenu
"""
| /usr/src/app/target_test_cases/failed_tests__updatemenu.Updatemenu.__init__.txt | def __init__(
self,
arg=None,
active=None,
bgcolor=None,
bordercolor=None,
borderwidth=None,
buttons=None,
buttondefaults=None,
direction=None,
font=None,
name=None,
pad=None,
showactive=None,
templateitemname=None,
type=None,
visible=None,
x=None,
xanchor=None,
y=None,
yanchor=None,
**kwargs,
):
"""
Construct a new Updatemenu object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.layout.Updatemenu`
active
Determines which button (by index starting from 0) is
considered active.
bgcolor
Sets the background color of the update menu buttons.
bordercolor
Sets the color of the border enclosing the update menu.
borderwidth
Sets the width (in px) of the border enclosing the
update menu.
buttons
A tuple of
:class:`plotly.graph_objects.layout.updatemenu.Button`
instances or dicts with compatible properties
buttondefaults
When used in a template (as
layout.template.layout.updatemenu.buttondefaults), sets
the default property values to use for elements of
layout.updatemenu.buttons
direction
Determines the direction in which the buttons are laid
out, whether in a dropdown menu or a row/column of
buttons. For `left` and `up`, the buttons will still
appear in left-to-right or top-to-bottom order
respectively.
font
Sets the font of the update menu button text.
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
pad
Sets the padding around the buttons or dropdown menu.
showactive
Highlights active dropdown item or active button if
true.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
type
Determines whether the buttons are accessible via a
dropdown menu or whether the buttons are stacked
horizontally or vertically
visible
Determines whether or not the update menu is visible.
x
Sets the x position (in normalized coordinates) of the
update menu.
xanchor
Sets the update menu's horizontal position anchor. This
anchor binds the `x` position to the "left", "center"
or "right" of the range selector.
y
Sets the y position (in normalized coordinates) of the
update menu.
yanchor
Sets the update menu's vertical position anchor This
anchor binds the `y` position to the "top", "middle" or
"bottom" of the range selector.
Returns
-------
Updatemenu
"""
super(Updatemenu, self).__init__("updatemenus")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.layout.Updatemenu
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.Updatemenu`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("active", None)
_v = active if active is not None else _v
if _v is not None:
self["active"] = _v
_v = arg.pop("bgcolor", None)
_v = bgcolor if bgcolor is not None else _v
if _v is not None:
self["bgcolor"] = _v
_v = arg.pop("bordercolor", None)
_v = bordercolor if bordercolor is not None else _v
if _v is not None:
self["bordercolor"] = _v
_v = arg.pop("borderwidth", None)
_v = borderwidth if borderwidth is not None else _v
if _v is not None:
self["borderwidth"] = _v
_v = arg.pop("buttons", None)
_v = buttons if buttons is not None else _v
if _v is not None:
self["buttons"] = _v
_v = arg.pop("buttondefaults", None)
_v = buttondefaults if buttondefaults is not None else _v
if _v is not None:
self["buttondefaults"] = _v
_v = arg.pop("direction", None)
_v = direction if direction is not None else _v
if _v is not None:
self["direction"] = _v
_v = arg.pop("font", None)
_v = font if font is not None else _v
if _v is not None:
self["font"] = _v
_v = arg.pop("name", None)
_v = name if name is not None else _v
if _v is not None:
self["name"] = _v
_v = arg.pop("pad", None)
_v = pad if pad is not None else _v
if _v is not None:
self["pad"] = _v
_v = arg.pop("showactive", None)
_v = showactive if showactive is not None else _v
if _v is not None:
self["showactive"] = _v
_v = arg.pop("templateitemname", None)
_v = templateitemname if templateitemname is not None else _v
if _v is not None:
self["templateitemname"] = _v
_v = arg.pop("type", None)
_v = type if type is not None else _v
if _v is not None:
self["type"] = _v
_v = arg.pop("visible", None)
_v = visible if visible is not None else _v
if _v is not None:
self["visible"] = _v
_v = arg.pop("x", None)
_v = x if x is not None else _v
if _v is not None:
self["x"] = _v
_v = arg.pop("xanchor", None)
_v = xanchor if xanchor is not None else _v
if _v is not None:
self["xanchor"] = _v
_v = arg.pop("y", None)
_v = y if y is not None else _v
if _v is not None:
self["y"] = _v
_v = arg.pop("yanchor", None)
_v = yanchor if yanchor is not None else _v
if _v is not None:
self["yanchor"] = _v
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| _updatemenu.Updatemenu.__init__ |
plotly.py | 63 | packages/python/plotly/plotly/graph_objs/layout/_updatemenu.py | def buttons(self):
"""
The 'buttons' property is a tuple of instances of
Button that may be specified as:
- A list or tuple of instances of plotly.graph_objs.layout.updatemenu.Button
- A list or tuple of dicts of string/value properties that
will be passed to the Button constructor
Supported dict properties:
args
Sets the arguments values to be passed to the
Plotly method set in `method` on click.
args2
Sets a 2nd set of `args`, these arguments
values are passed to the Plotly method set in
`method` when clicking this button while in the
active state. Use this to create toggle
buttons.
execute
When true, the API method is executed. When
false, all other behaviors are the same and
command execution is skipped. This may be
useful when hooking into, for example, the
`plotly_buttonclicked` method and executing the
API command manually without losing the benefit
of the updatemenu automatically binding to the
state of the plot through the specification of
`method` and `args`.
label
Sets the text label to appear on the button.
method
Sets the Plotly method to be called on click.
If the `skip` method is used, the API
updatemenu will function as normal but will
perform no API calls and will not bind
automatically to state updates. This may be
used to create a component interface and attach
to updatemenu events manually via JavaScript.
name
When used in a template, named items are
created in the output figure in addition to any
items the figure already has in this array. You
can modify these items in the output figure by
making your own item with `templateitemname`
matching this `name` alongside your
modifications (including `visible: false` or
`enabled: false` to hide it). Has no effect
outside of a template.
templateitemname
Used to refer to a named item in this array in
the template. Named items from the template
will be created even without a matching item in
the input figure, but you can modify one by
making an item with `templateitemname` matching
its `name`, alongside your modifications
(including `visible: false` or `enabled: false`
to hide it). If there is no template or no
matching item, this item will be hidden unless
you explicitly show it with `visible: true`.
visible
Determines whether or not this button is
visible.
Returns
-------
tuple[plotly.graph_objs.layout.updatemenu.Button]
"""
| /usr/src/app/target_test_cases/failed_tests__updatemenu.buttons.txt | def buttons(self):
"""
The 'buttons' property is a tuple of instances of
Button that may be specified as:
- A list or tuple of instances of plotly.graph_objs.layout.updatemenu.Button
- A list or tuple of dicts of string/value properties that
will be passed to the Button constructor
Supported dict properties:
args
Sets the arguments values to be passed to the
Plotly method set in `method` on click.
args2
Sets a 2nd set of `args`, these arguments
values are passed to the Plotly method set in
`method` when clicking this button while in the
active state. Use this to create toggle
buttons.
execute
When true, the API method is executed. When
false, all other behaviors are the same and
command execution is skipped. This may be
useful when hooking into, for example, the
`plotly_buttonclicked` method and executing the
API command manually without losing the benefit
of the updatemenu automatically binding to the
state of the plot through the specification of
`method` and `args`.
label
Sets the text label to appear on the button.
method
Sets the Plotly method to be called on click.
If the `skip` method is used, the API
updatemenu will function as normal but will
perform no API calls and will not bind
automatically to state updates. This may be
used to create a component interface and attach
to updatemenu events manually via JavaScript.
name
When used in a template, named items are
created in the output figure in addition to any
items the figure already has in this array. You
can modify these items in the output figure by
making your own item with `templateitemname`
matching this `name` alongside your
modifications (including `visible: false` or
`enabled: false` to hide it). Has no effect
outside of a template.
templateitemname
Used to refer to a named item in this array in
the template. Named items from the template
will be created even without a matching item in
the input figure, but you can modify one by
making an item with `templateitemname` matching
its `name`, alongside your modifications
(including `visible: false` or `enabled: false`
to hide it). If there is no template or no
matching item, this item will be hidden unless
you explicitly show it with `visible: true`.
visible
Determines whether or not this button is
visible.
Returns
-------
tuple[plotly.graph_objs.layout.updatemenu.Button]
"""
return self["buttons"]
| _updatemenu.buttons |
plotly.py | 64 | packages/python/plotly/plotly/graph_objs/_violin.py | def __init__(
self,
arg=None,
alignmentgroup=None,
bandwidth=None,
box=None,
customdata=None,
customdatasrc=None,
fillcolor=None,
hoverinfo=None,
hoverinfosrc=None,
hoverlabel=None,
hoveron=None,
hovertemplate=None,
hovertemplatesrc=None,
hovertext=None,
hovertextsrc=None,
ids=None,
idssrc=None,
jitter=None,
legend=None,
legendgroup=None,
legendgrouptitle=None,
legendrank=None,
legendwidth=None,
line=None,
marker=None,
meanline=None,
meta=None,
metasrc=None,
name=None,
offsetgroup=None,
opacity=None,
orientation=None,
pointpos=None,
points=None,
quartilemethod=None,
scalegroup=None,
scalemode=None,
selected=None,
selectedpoints=None,
showlegend=None,
side=None,
span=None,
spanmode=None,
stream=None,
text=None,
textsrc=None,
uid=None,
uirevision=None,
unselected=None,
visible=None,
width=None,
x=None,
x0=None,
xaxis=None,
xhoverformat=None,
xsrc=None,
y=None,
y0=None,
yaxis=None,
yhoverformat=None,
ysrc=None,
zorder=None,
**kwargs,
):
"""
Construct a new Violin object
In vertical (horizontal) violin plots, statistics are computed
using `y` (`x`) values. By supplying an `x` (`y`) array, one
violin per distinct x (y) value is drawn If no `x` (`y`) list
is provided, a single violin is drawn. That violin position is
then positioned with with `name` or with `x0` (`y0`) if
provided.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.Violin`
alignmentgroup
Set several traces linked to the same position axis or
matching axes to the same alignmentgroup. This controls
whether bars compute their positional range dependently
or independently.
bandwidth
Sets the bandwidth used to compute the kernel density
estimate. By default, the bandwidth is determined by
Silverman's rule of thumb.
box
:class:`plotly.graph_objects.violin.Box` instance or
dict with compatible properties
customdata
Assigns extra data each datum. This may be useful when
listening to hover, click and selection events. Note
that, "scatter" traces also appends customdata items in
the markers DOM elements
customdatasrc
Sets the source reference on Chart Studio Cloud for
`customdata`.
fillcolor
Sets the fill color. Defaults to a half-transparent
variant of the line color, marker color, or marker line
color, whichever is available.
hoverinfo
Determines which trace information appear on hover. If
`none` or `skip` are set, no information is displayed
upon hovering. But, if `none` is set, click and hover
events are still fired.
hoverinfosrc
Sets the source reference on Chart Studio Cloud for
`hoverinfo`.
hoverlabel
:class:`plotly.graph_objects.violin.Hoverlabel`
instance or dict with compatible properties
hoveron
Do the hover effects highlight individual violins or
sample points or the kernel density estimate or any
combination of them?
hovertemplate
Template string used for rendering the information that
appear on hover box. Note that this will override
`hoverinfo`. Variables are inserted using %{variable},
for example "y: %{y}" as well as %{xother}, {%_xother},
{%_xother_}, {%xother_}. When showing info for several
points, "xother" will be added to those with different
x positions from the first point. An underscore before
or after "(x|y)other" will add a space on that side,
only when this field is shown. Numbers are formatted
using d3-format's syntax %{variable:d3-format}, for
example "Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. The variables available in
`hovertemplate` are the ones emitted as event data
described at this link
https://plotly.com/javascript/plotlyjs-events/#event-
data. Additionally, every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Anything contained in tag `<extra>` is
displayed in the secondary box, for example
"<extra>{fullData.name}</extra>". To hide the secondary
box completely, use an empty tag `<extra></extra>`.
hovertemplatesrc
Sets the source reference on Chart Studio Cloud for
`hovertemplate`.
hovertext
Same as `text`.
hovertextsrc
Sets the source reference on Chart Studio Cloud for
`hovertext`.
ids
Assigns id labels to each datum. These ids for object
constancy of data points during animation. Should be an
array of strings, not numbers or any other type.
idssrc
Sets the source reference on Chart Studio Cloud for
`ids`.
jitter
Sets the amount of jitter in the sample points drawn.
If 0, the sample points align along the distribution
axis. If 1, the sample points are drawn in a random
jitter of width equal to the width of the violins.
legend
Sets the reference to a legend to show this trace in.
References to these legends are "legend", "legend2",
"legend3", etc. Settings for these legends are set in
the layout, under `layout.legend`, `layout.legend2`,
etc.
legendgroup
Sets the legend group for this trace. Traces and shapes
part of the same legend group hide/show at the same
time when toggling legend items.
legendgrouptitle
:class:`plotly.graph_objects.violin.Legendgrouptitle`
instance or dict with compatible properties
legendrank
Sets the legend rank for this trace. Items and groups
with smaller ranks are presented on top/left side while
with "reversed" `legend.traceorder` they are on
bottom/right side. The default legendrank is 1000, so
that you can use ranks less than 1000 to place certain
items before all unranked items, and ranks greater than
1000 to go after all unranked items. When having
unranked or equal rank items shapes would be displayed
after traces i.e. according to their order in data and
layout.
legendwidth
Sets the width (in px or fraction) of the legend for
this trace.
line
:class:`plotly.graph_objects.violin.Line` instance or
dict with compatible properties
marker
:class:`plotly.graph_objects.violin.Marker` instance or
dict with compatible properties
meanline
:class:`plotly.graph_objects.violin.Meanline` instance
or dict with compatible properties
meta
Assigns extra meta information associated with this
trace that can be used in various text attributes.
Attributes such as trace `name`, graph, axis and
colorbar `title.text`, annotation `text`
`rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta`
values in an attribute in the same trace, simply use
`%{meta[i]}` where `i` is the index or key of the
`meta` item in question. To access trace `meta` in
layout attributes, use `%{data[n[.meta[i]}` where `i`
is the index or key of the `meta` and `n` is the trace
index.
metasrc
Sets the source reference on Chart Studio Cloud for
`meta`.
name
Sets the trace name. The trace name appears as the
legend item and on hover. For violin traces, the name
will also be used for the position coordinate, if `x`
and `x0` (`y` and `y0` if horizontal) are missing and
the position axis is categorical. Note that the trace
name is also used as a default value for attribute
`scalegroup` (please see its description for details).
offsetgroup
Set several traces linked to the same position axis or
matching axes to the same offsetgroup where bars of the
same position coordinate will line up.
opacity
Sets the opacity of the trace.
orientation
Sets the orientation of the violin(s). If "v" ("h"),
the distribution is visualized along the vertical
(horizontal).
pointpos
Sets the position of the sample points in relation to
the violins. If 0, the sample points are places over
the center of the violins. Positive (negative) values
correspond to positions to the right (left) for
vertical violins and above (below) for horizontal
violins.
points
If "outliers", only the sample points lying outside the
whiskers are shown If "suspectedoutliers", the outlier
points are shown and points either less than 4*Q1-3*Q3
or greater than 4*Q3-3*Q1 are highlighted (see
`outliercolor`) If "all", all sample points are shown
If False, only the violins are shown with no sample
points. Defaults to "suspectedoutliers" when
`marker.outliercolor` or `marker.line.outliercolor` is
set, otherwise defaults to "outliers".
quartilemethod
Sets the method used to compute the sample's Q1 and Q3
quartiles. The "linear" method uses the 25th percentile
for Q1 and 75th percentile for Q3 as computed using
method #10 (listed on
http://jse.amstat.org/v14n3/langford.html). The
"exclusive" method uses the median to divide the
ordered dataset into two halves if the sample is odd,
it does not include the median in either half - Q1 is
then the median of the lower half and Q3 the median of
the upper half. The "inclusive" method also uses the
median to divide the ordered dataset into two halves
but if the sample is odd, it includes the median in
both halves - Q1 is then the median of the lower half
and Q3 the median of the upper half.
scalegroup
If there are multiple violins that should be sized
according to to some metric (see `scalemode`), link
them by providing a non-empty group id here shared by
every trace in the same group. If a violin's `width` is
undefined, `scalegroup` will default to the trace's
name. In this case, violins with the same names will be
linked together
scalemode
Sets the metric by which the width of each violin is
determined. "width" means each violin has the same
(max) width "count" means the violins are scaled by the
number of sample points making up each violin.
selected
:class:`plotly.graph_objects.violin.Selected` instance
or dict with compatible properties
selectedpoints
Array containing integer indices of selected points.
Has an effect only for traces that support selections.
Note that an empty array means an empty selection where
the `unselected` are turned on for all points, whereas,
any other non-array values means no selection all where
the `selected` and `unselected` styles have no effect.
showlegend
Determines whether or not an item corresponding to this
trace is shown in the legend.
side
Determines on which side of the position value the
density function making up one half of a violin is
plotted. Useful when comparing two violin traces under
"overlay" mode, where one trace has `side` set to
"positive" and the other to "negative".
span
Sets the span in data space for which the density
function will be computed. Has an effect only when
`spanmode` is set to "manual".
spanmode
Sets the method by which the span in data space where
the density function will be computed. "soft" means the
span goes from the sample's minimum value minus two
bandwidths to the sample's maximum value plus two
bandwidths. "hard" means the span goes from the
sample's minimum to its maximum value. For custom span
settings, use mode "manual" and fill in the `span`
attribute.
stream
:class:`plotly.graph_objects.violin.Stream` instance or
dict with compatible properties
text
Sets the text elements associated with each sample
value. If a single string, the same string appears over
all the data points. If an array of string, the items
are mapped in order to the this trace's (x,y)
coordinates. To be seen, trace `hoverinfo` must contain
a "text" flag.
textsrc
Sets the source reference on Chart Studio Cloud for
`text`.
uid
Assign an id to this trace, Use this to provide object
constancy between traces during animations and
transitions.
uirevision
Controls persistence of some user-driven changes to the
trace: `constraintrange` in `parcoords` traces, as well
as some `editable: true` modifications such as `name`
and `colorbar.title`. Defaults to `layout.uirevision`.
Note that other user-driven trace attribute changes are
controlled by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
unselected
:class:`plotly.graph_objects.violin.Unselected`
instance or dict with compatible properties
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
width
Sets the width of the violin in data coordinates. If 0
(default value) the width is automatically selected
based on the positions of other violin traces in the
same subplot.
x
Sets the x sample data or coordinates. See overview for
more info.
x0
Sets the x coordinate for single-box traces or the
starting coordinate for multi-box traces set using
q1/median/q3. See overview for more info.
xaxis
Sets a reference between this trace's x coordinates and
a 2D cartesian x axis. If "x" (the default value), the
x coordinates refer to `layout.xaxis`. If "x2", the x
coordinates refer to `layout.xaxis2`, and so on.
xhoverformat
Sets the hover text formatting rulefor `x` using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display *09~15~23.46*By default the values are
formatted using `xaxis.hoverformat`.
xsrc
Sets the source reference on Chart Studio Cloud for
`x`.
y
Sets the y sample data or coordinates. See overview for
more info.
y0
Sets the y coordinate for single-box traces or the
starting coordinate for multi-box traces set using
q1/median/q3. See overview for more info.
yaxis
Sets a reference between this trace's y coordinates and
a 2D cartesian y axis. If "y" (the default value), the
y coordinates refer to `layout.yaxis`. If "y2", the y
coordinates refer to `layout.yaxis2`, and so on.
yhoverformat
Sets the hover text formatting rulefor `y` using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display *09~15~23.46*By default the values are
formatted using `yaxis.hoverformat`.
ysrc
Sets the source reference on Chart Studio Cloud for
`y`.
zorder
Sets the layer on which this trace is displayed,
relative to other SVG traces on the same subplot. SVG
traces with higher `zorder` appear in front of those
with lower `zorder`.
Returns
-------
Violin
"""
| /usr/src/app/target_test_cases/failed_tests__violin.Violin.__init__.txt | def __init__(
self,
arg=None,
alignmentgroup=None,
bandwidth=None,
box=None,
customdata=None,
customdatasrc=None,
fillcolor=None,
hoverinfo=None,
hoverinfosrc=None,
hoverlabel=None,
hoveron=None,
hovertemplate=None,
hovertemplatesrc=None,
hovertext=None,
hovertextsrc=None,
ids=None,
idssrc=None,
jitter=None,
legend=None,
legendgroup=None,
legendgrouptitle=None,
legendrank=None,
legendwidth=None,
line=None,
marker=None,
meanline=None,
meta=None,
metasrc=None,
name=None,
offsetgroup=None,
opacity=None,
orientation=None,
pointpos=None,
points=None,
quartilemethod=None,
scalegroup=None,
scalemode=None,
selected=None,
selectedpoints=None,
showlegend=None,
side=None,
span=None,
spanmode=None,
stream=None,
text=None,
textsrc=None,
uid=None,
uirevision=None,
unselected=None,
visible=None,
width=None,
x=None,
x0=None,
xaxis=None,
xhoverformat=None,
xsrc=None,
y=None,
y0=None,
yaxis=None,
yhoverformat=None,
ysrc=None,
zorder=None,
**kwargs,
):
"""
Construct a new Violin object
In vertical (horizontal) violin plots, statistics are computed
using `y` (`x`) values. By supplying an `x` (`y`) array, one
violin per distinct x (y) value is drawn If no `x` (`y`) list
is provided, a single violin is drawn. That violin position is
then positioned with with `name` or with `x0` (`y0`) if
provided.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.Violin`
alignmentgroup
Set several traces linked to the same position axis or
matching axes to the same alignmentgroup. This controls
whether bars compute their positional range dependently
or independently.
bandwidth
Sets the bandwidth used to compute the kernel density
estimate. By default, the bandwidth is determined by
Silverman's rule of thumb.
box
:class:`plotly.graph_objects.violin.Box` instance or
dict with compatible properties
customdata
Assigns extra data each datum. This may be useful when
listening to hover, click and selection events. Note
that, "scatter" traces also appends customdata items in
the markers DOM elements
customdatasrc
Sets the source reference on Chart Studio Cloud for
`customdata`.
fillcolor
Sets the fill color. Defaults to a half-transparent
variant of the line color, marker color, or marker line
color, whichever is available.
hoverinfo
Determines which trace information appear on hover. If
`none` or `skip` are set, no information is displayed
upon hovering. But, if `none` is set, click and hover
events are still fired.
hoverinfosrc
Sets the source reference on Chart Studio Cloud for
`hoverinfo`.
hoverlabel
:class:`plotly.graph_objects.violin.Hoverlabel`
instance or dict with compatible properties
hoveron
Do the hover effects highlight individual violins or
sample points or the kernel density estimate or any
combination of them?
hovertemplate
Template string used for rendering the information that
appear on hover box. Note that this will override
`hoverinfo`. Variables are inserted using %{variable},
for example "y: %{y}" as well as %{xother}, {%_xother},
{%_xother_}, {%xother_}. When showing info for several
points, "xother" will be added to those with different
x positions from the first point. An underscore before
or after "(x|y)other" will add a space on that side,
only when this field is shown. Numbers are formatted
using d3-format's syntax %{variable:d3-format}, for
example "Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. The variables available in
`hovertemplate` are the ones emitted as event data
described at this link
https://plotly.com/javascript/plotlyjs-events/#event-
data. Additionally, every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Anything contained in tag `<extra>` is
displayed in the secondary box, for example
"<extra>{fullData.name}</extra>". To hide the secondary
box completely, use an empty tag `<extra></extra>`.
hovertemplatesrc
Sets the source reference on Chart Studio Cloud for
`hovertemplate`.
hovertext
Same as `text`.
hovertextsrc
Sets the source reference on Chart Studio Cloud for
`hovertext`.
ids
Assigns id labels to each datum. These ids for object
constancy of data points during animation. Should be an
array of strings, not numbers or any other type.
idssrc
Sets the source reference on Chart Studio Cloud for
`ids`.
jitter
Sets the amount of jitter in the sample points drawn.
If 0, the sample points align along the distribution
axis. If 1, the sample points are drawn in a random
jitter of width equal to the width of the violins.
legend
Sets the reference to a legend to show this trace in.
References to these legends are "legend", "legend2",
"legend3", etc. Settings for these legends are set in
the layout, under `layout.legend`, `layout.legend2`,
etc.
legendgroup
Sets the legend group for this trace. Traces and shapes
part of the same legend group hide/show at the same
time when toggling legend items.
legendgrouptitle
:class:`plotly.graph_objects.violin.Legendgrouptitle`
instance or dict with compatible properties
legendrank
Sets the legend rank for this trace. Items and groups
with smaller ranks are presented on top/left side while
with "reversed" `legend.traceorder` they are on
bottom/right side. The default legendrank is 1000, so
that you can use ranks less than 1000 to place certain
items before all unranked items, and ranks greater than
1000 to go after all unranked items. When having
unranked or equal rank items shapes would be displayed
after traces i.e. according to their order in data and
layout.
legendwidth
Sets the width (in px or fraction) of the legend for
this trace.
line
:class:`plotly.graph_objects.violin.Line` instance or
dict with compatible properties
marker
:class:`plotly.graph_objects.violin.Marker` instance or
dict with compatible properties
meanline
:class:`plotly.graph_objects.violin.Meanline` instance
or dict with compatible properties
meta
Assigns extra meta information associated with this
trace that can be used in various text attributes.
Attributes such as trace `name`, graph, axis and
colorbar `title.text`, annotation `text`
`rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta`
values in an attribute in the same trace, simply use
`%{meta[i]}` where `i` is the index or key of the
`meta` item in question. To access trace `meta` in
layout attributes, use `%{data[n[.meta[i]}` where `i`
is the index or key of the `meta` and `n` is the trace
index.
metasrc
Sets the source reference on Chart Studio Cloud for
`meta`.
name
Sets the trace name. The trace name appears as the
legend item and on hover. For violin traces, the name
will also be used for the position coordinate, if `x`
and `x0` (`y` and `y0` if horizontal) are missing and
the position axis is categorical. Note that the trace
name is also used as a default value for attribute
`scalegroup` (please see its description for details).
offsetgroup
Set several traces linked to the same position axis or
matching axes to the same offsetgroup where bars of the
same position coordinate will line up.
opacity
Sets the opacity of the trace.
orientation
Sets the orientation of the violin(s). If "v" ("h"),
the distribution is visualized along the vertical
(horizontal).
pointpos
Sets the position of the sample points in relation to
the violins. If 0, the sample points are places over
the center of the violins. Positive (negative) values
correspond to positions to the right (left) for
vertical violins and above (below) for horizontal
violins.
points
If "outliers", only the sample points lying outside the
whiskers are shown If "suspectedoutliers", the outlier
points are shown and points either less than 4*Q1-3*Q3
or greater than 4*Q3-3*Q1 are highlighted (see
`outliercolor`) If "all", all sample points are shown
If False, only the violins are shown with no sample
points. Defaults to "suspectedoutliers" when
`marker.outliercolor` or `marker.line.outliercolor` is
set, otherwise defaults to "outliers".
quartilemethod
Sets the method used to compute the sample's Q1 and Q3
quartiles. The "linear" method uses the 25th percentile
for Q1 and 75th percentile for Q3 as computed using
method #10 (listed on
http://jse.amstat.org/v14n3/langford.html). The
"exclusive" method uses the median to divide the
ordered dataset into two halves if the sample is odd,
it does not include the median in either half - Q1 is
then the median of the lower half and Q3 the median of
the upper half. The "inclusive" method also uses the
median to divide the ordered dataset into two halves
but if the sample is odd, it includes the median in
both halves - Q1 is then the median of the lower half
and Q3 the median of the upper half.
scalegroup
If there are multiple violins that should be sized
according to to some metric (see `scalemode`), link
them by providing a non-empty group id here shared by
every trace in the same group. If a violin's `width` is
undefined, `scalegroup` will default to the trace's
name. In this case, violins with the same names will be
linked together
scalemode
Sets the metric by which the width of each violin is
determined. "width" means each violin has the same
(max) width "count" means the violins are scaled by the
number of sample points making up each violin.
selected
:class:`plotly.graph_objects.violin.Selected` instance
or dict with compatible properties
selectedpoints
Array containing integer indices of selected points.
Has an effect only for traces that support selections.
Note that an empty array means an empty selection where
the `unselected` are turned on for all points, whereas,
any other non-array values means no selection all where
the `selected` and `unselected` styles have no effect.
showlegend
Determines whether or not an item corresponding to this
trace is shown in the legend.
side
Determines on which side of the position value the
density function making up one half of a violin is
plotted. Useful when comparing two violin traces under
"overlay" mode, where one trace has `side` set to
"positive" and the other to "negative".
span
Sets the span in data space for which the density
function will be computed. Has an effect only when
`spanmode` is set to "manual".
spanmode
Sets the method by which the span in data space where
the density function will be computed. "soft" means the
span goes from the sample's minimum value minus two
bandwidths to the sample's maximum value plus two
bandwidths. "hard" means the span goes from the
sample's minimum to its maximum value. For custom span
settings, use mode "manual" and fill in the `span`
attribute.
stream
:class:`plotly.graph_objects.violin.Stream` instance or
dict with compatible properties
text
Sets the text elements associated with each sample
value. If a single string, the same string appears over
all the data points. If an array of string, the items
are mapped in order to the this trace's (x,y)
coordinates. To be seen, trace `hoverinfo` must contain
a "text" flag.
textsrc
Sets the source reference on Chart Studio Cloud for
`text`.
uid
Assign an id to this trace, Use this to provide object
constancy between traces during animations and
transitions.
uirevision
Controls persistence of some user-driven changes to the
trace: `constraintrange` in `parcoords` traces, as well
as some `editable: true` modifications such as `name`
and `colorbar.title`. Defaults to `layout.uirevision`.
Note that other user-driven trace attribute changes are
controlled by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
unselected
:class:`plotly.graph_objects.violin.Unselected`
instance or dict with compatible properties
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
width
Sets the width of the violin in data coordinates. If 0
(default value) the width is automatically selected
based on the positions of other violin traces in the
same subplot.
x
Sets the x sample data or coordinates. See overview for
more info.
x0
Sets the x coordinate for single-box traces or the
starting coordinate for multi-box traces set using
q1/median/q3. See overview for more info.
xaxis
Sets a reference between this trace's x coordinates and
a 2D cartesian x axis. If "x" (the default value), the
x coordinates refer to `layout.xaxis`. If "x2", the x
coordinates refer to `layout.xaxis2`, and so on.
xhoverformat
Sets the hover text formatting rulefor `x` using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display *09~15~23.46*By default the values are
formatted using `xaxis.hoverformat`.
xsrc
Sets the source reference on Chart Studio Cloud for
`x`.
y
Sets the y sample data or coordinates. See overview for
more info.
y0
Sets the y coordinate for single-box traces or the
starting coordinate for multi-box traces set using
q1/median/q3. See overview for more info.
yaxis
Sets a reference between this trace's y coordinates and
a 2D cartesian y axis. If "y" (the default value), the
y coordinates refer to `layout.yaxis`. If "y2", the y
coordinates refer to `layout.yaxis2`, and so on.
yhoverformat
Sets the hover text formatting rulefor `y` using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display *09~15~23.46*By default the values are
formatted using `yaxis.hoverformat`.
ysrc
Sets the source reference on Chart Studio Cloud for
`y`.
zorder
Sets the layer on which this trace is displayed,
relative to other SVG traces on the same subplot. SVG
traces with higher `zorder` appear in front of those
with lower `zorder`.
Returns
-------
Violin
"""
super(Violin, self).__init__("violin")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.Violin
constructor must be a dict or
an instance of :class:`plotly.graph_objs.Violin`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("alignmentgroup", None)
_v = alignmentgroup if alignmentgroup is not None else _v
if _v is not None:
self["alignmentgroup"] = _v
_v = arg.pop("bandwidth", None)
_v = bandwidth if bandwidth is not None else _v
if _v is not None:
self["bandwidth"] = _v
_v = arg.pop("box", None)
_v = box if box is not None else _v
if _v is not None:
self["box"] = _v
_v = arg.pop("customdata", None)
_v = customdata if customdata is not None else _v
if _v is not None:
self["customdata"] = _v
_v = arg.pop("customdatasrc", None)
_v = customdatasrc if customdatasrc is not None else _v
if _v is not None:
self["customdatasrc"] = _v
_v = arg.pop("fillcolor", None)
_v = fillcolor if fillcolor is not None else _v
if _v is not None:
self["fillcolor"] = _v
_v = arg.pop("hoverinfo", None)
_v = hoverinfo if hoverinfo is not None else _v
if _v is not None:
self["hoverinfo"] = _v
_v = arg.pop("hoverinfosrc", None)
_v = hoverinfosrc if hoverinfosrc is not None else _v
if _v is not None:
self["hoverinfosrc"] = _v
_v = arg.pop("hoverlabel", None)
_v = hoverlabel if hoverlabel is not None else _v
if _v is not None:
self["hoverlabel"] = _v
_v = arg.pop("hoveron", None)
_v = hoveron if hoveron is not None else _v
if _v is not None:
self["hoveron"] = _v
_v = arg.pop("hovertemplate", None)
_v = hovertemplate if hovertemplate is not None else _v
if _v is not None:
self["hovertemplate"] = _v
_v = arg.pop("hovertemplatesrc", None)
_v = hovertemplatesrc if hovertemplatesrc is not None else _v
if _v is not None:
self["hovertemplatesrc"] = _v
_v = arg.pop("hovertext", None)
_v = hovertext if hovertext is not None else _v
if _v is not None:
self["hovertext"] = _v
_v = arg.pop("hovertextsrc", None)
_v = hovertextsrc if hovertextsrc is not None else _v
if _v is not None:
self["hovertextsrc"] = _v
_v = arg.pop("ids", None)
_v = ids if ids is not None else _v
if _v is not None:
self["ids"] = _v
_v = arg.pop("idssrc", None)
_v = idssrc if idssrc is not None else _v
if _v is not None:
self["idssrc"] = _v
_v = arg.pop("jitter", None)
_v = jitter if jitter is not None else _v
if _v is not None:
self["jitter"] = _v
_v = arg.pop("legend", None)
_v = legend if legend is not None else _v
if _v is not None:
self["legend"] = _v
_v = arg.pop("legendgroup", None)
_v = legendgroup if legendgroup is not None else _v
if _v is not None:
self["legendgroup"] = _v
_v = arg.pop("legendgrouptitle", None)
_v = legendgrouptitle if legendgrouptitle is not None else _v
if _v is not None:
self["legendgrouptitle"] = _v
_v = arg.pop("legendrank", None)
_v = legendrank if legendrank is not None else _v
if _v is not None:
self["legendrank"] = _v
_v = arg.pop("legendwidth", None)
_v = legendwidth if legendwidth is not None else _v
if _v is not None:
self["legendwidth"] = _v
_v = arg.pop("line", None)
_v = line if line is not None else _v
if _v is not None:
self["line"] = _v
_v = arg.pop("marker", None)
_v = marker if marker is not None else _v
if _v is not None:
self["marker"] = _v
_v = arg.pop("meanline", None)
_v = meanline if meanline is not None else _v
if _v is not None:
self["meanline"] = _v
_v = arg.pop("meta", None)
_v = meta if meta is not None else _v
if _v is not None:
self["meta"] = _v
_v = arg.pop("metasrc", None)
_v = metasrc if metasrc is not None else _v
if _v is not None:
self["metasrc"] = _v
_v = arg.pop("name", None)
_v = name if name is not None else _v
if _v is not None:
self["name"] = _v
_v = arg.pop("offsetgroup", None)
_v = offsetgroup if offsetgroup is not None else _v
if _v is not None:
self["offsetgroup"] = _v
_v = arg.pop("opacity", None)
_v = opacity if opacity is not None else _v
if _v is not None:
self["opacity"] = _v
_v = arg.pop("orientation", None)
_v = orientation if orientation is not None else _v
if _v is not None:
self["orientation"] = _v
_v = arg.pop("pointpos", None)
_v = pointpos if pointpos is not None else _v
if _v is not None:
self["pointpos"] = _v
_v = arg.pop("points", None)
_v = points if points is not None else _v
if _v is not None:
self["points"] = _v
_v = arg.pop("quartilemethod", None)
_v = quartilemethod if quartilemethod is not None else _v
if _v is not None:
self["quartilemethod"] = _v
_v = arg.pop("scalegroup", None)
_v = scalegroup if scalegroup is not None else _v
if _v is not None:
self["scalegroup"] = _v
_v = arg.pop("scalemode", None)
_v = scalemode if scalemode is not None else _v
if _v is not None:
self["scalemode"] = _v
_v = arg.pop("selected", None)
_v = selected if selected is not None else _v
if _v is not None:
self["selected"] = _v
_v = arg.pop("selectedpoints", None)
_v = selectedpoints if selectedpoints is not None else _v
if _v is not None:
self["selectedpoints"] = _v
_v = arg.pop("showlegend", None)
_v = showlegend if showlegend is not None else _v
if _v is not None:
self["showlegend"] = _v
_v = arg.pop("side", None)
_v = side if side is not None else _v
if _v is not None:
self["side"] = _v
_v = arg.pop("span", None)
_v = span if span is not None else _v
if _v is not None:
self["span"] = _v
_v = arg.pop("spanmode", None)
_v = spanmode if spanmode is not None else _v
if _v is not None:
self["spanmode"] = _v
_v = arg.pop("stream", None)
_v = stream if stream is not None else _v
if _v is not None:
self["stream"] = _v
_v = arg.pop("text", None)
_v = text if text is not None else _v
if _v is not None:
self["text"] = _v
_v = arg.pop("textsrc", None)
_v = textsrc if textsrc is not None else _v
if _v is not None:
self["textsrc"] = _v
_v = arg.pop("uid", None)
_v = uid if uid is not None else _v
if _v is not None:
self["uid"] = _v
_v = arg.pop("uirevision", None)
_v = uirevision if uirevision is not None else _v
if _v is not None:
self["uirevision"] = _v
_v = arg.pop("unselected", None)
_v = unselected if unselected is not None else _v
if _v is not None:
self["unselected"] = _v
_v = arg.pop("visible", None)
_v = visible if visible is not None else _v
if _v is not None:
self["visible"] = _v
_v = arg.pop("width", None)
_v = width if width is not None else _v
if _v is not None:
self["width"] = _v
_v = arg.pop("x", None)
_v = x if x is not None else _v
if _v is not None:
self["x"] = _v
_v = arg.pop("x0", None)
_v = x0 if x0 is not None else _v
if _v is not None:
self["x0"] = _v
_v = arg.pop("xaxis", None)
_v = xaxis if xaxis is not None else _v
if _v is not None:
self["xaxis"] = _v
_v = arg.pop("xhoverformat", None)
_v = xhoverformat if xhoverformat is not None else _v
if _v is not None:
self["xhoverformat"] = _v
_v = arg.pop("xsrc", None)
_v = xsrc if xsrc is not None else _v
if _v is not None:
self["xsrc"] = _v
_v = arg.pop("y", None)
_v = y if y is not None else _v
if _v is not None:
self["y"] = _v
_v = arg.pop("y0", None)
_v = y0 if y0 is not None else _v
if _v is not None:
self["y0"] = _v
_v = arg.pop("yaxis", None)
_v = yaxis if yaxis is not None else _v
if _v is not None:
self["yaxis"] = _v
_v = arg.pop("yhoverformat", None)
_v = yhoverformat if yhoverformat is not None else _v
if _v is not None:
self["yhoverformat"] = _v
_v = arg.pop("ysrc", None)
_v = ysrc if ysrc is not None else _v
if _v is not None:
self["ysrc"] = _v
_v = arg.pop("zorder", None)
_v = zorder if zorder is not None else _v
if _v is not None:
self["zorder"] = _v
# Read-only literals
# ------------------
self._props["type"] = "violin"
arg.pop("type", None)
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| _violin.Violin.__init__ |
plotly.py | 65 | packages/python/plotly/plotly/figure_factory/_violin.py | def create_violin(
data,
data_header=None,
group_header=None,
colors=None,
use_colorscale=False,
group_stats=None,
rugplot=True,
sort=False,
height=450,
width=600,
title="Violin and Rug Plot",
):
"""
**deprecated**, use instead the plotly.graph_objects trace
:class:`plotly.graph_objects.Violin`.
:param (list|array) data: accepts either a list of numerical values,
a list of dictionaries all with identical keys and at least one
column of numeric values, or a pandas dataframe with at least one
column of numbers.
:param (str) data_header: the header of the data column to be used
from an inputted pandas dataframe. Not applicable if 'data' is
a list of numeric values.
:param (str) group_header: applicable if grouping data by a variable.
'group_header' must be set to the name of the grouping variable.
:param (str|tuple|list|dict) colors: either a plotly scale name,
an rgb or hex color, a color tuple, a list of colors or a
dictionary. An rgb color is of the form 'rgb(x, y, z)' where
x, y and z belong to the interval [0, 255] and a color tuple is a
tuple of the form (a, b, c) where a, b and c belong to [0, 1].
If colors is a list, it must contain valid color types as its
members.
:param (bool) use_colorscale: only applicable if grouping by another
variable. Will implement a colorscale based on the first 2 colors
of param colors. This means colors must be a list with at least 2
colors in it (Plotly colorscales are accepted since they map to a
list of two rgb colors). Default = False
:param (dict) group_stats: a dictionary where each key is a unique
value from the group_header column in data. Each value must be a
number and will be used to color the violin plots if a colorscale
is being used.
:param (bool) rugplot: determines if a rugplot is draw on violin plot.
Default = True
:param (bool) sort: determines if violins are sorted
alphabetically (True) or by input order (False). Default = False
:param (float) height: the height of the violin plot.
:param (float) width: the width of the violin plot.
:param (str) title: the title of the violin plot.
Example 1: Single Violin Plot
>>> from plotly.figure_factory import create_violin
>>> import plotly.graph_objs as graph_objects
>>> import numpy as np
>>> from scipy import stats
>>> # create list of random values
>>> data_list = np.random.randn(100)
>>> # create violin fig
>>> fig = create_violin(data_list, colors='#604d9e')
>>> # plot
>>> fig.show()
Example 2: Multiple Violin Plots with Qualitative Coloring
>>> from plotly.figure_factory import create_violin
>>> import plotly.graph_objs as graph_objects
>>> import numpy as np
>>> import pandas as pd
>>> from scipy import stats
>>> # create dataframe
>>> np.random.seed(619517)
>>> Nr=250
>>> y = np.random.randn(Nr)
>>> gr = np.random.choice(list("ABCDE"), Nr)
>>> norm_params=[(0, 1.2), (0.7, 1), (-0.5, 1.4), (0.3, 1), (0.8, 0.9)]
>>> for i, letter in enumerate("ABCDE"):
... y[gr == letter] *=norm_params[i][1]+ norm_params[i][0]
>>> df = pd.DataFrame(dict(Score=y, Group=gr))
>>> # create violin fig
>>> fig = create_violin(df, data_header='Score', group_header='Group',
... sort=True, height=600, width=1000)
>>> # plot
>>> fig.show()
Example 3: Violin Plots with Colorscale
>>> from plotly.figure_factory import create_violin
>>> import plotly.graph_objs as graph_objects
>>> import numpy as np
>>> import pandas as pd
>>> from scipy import stats
>>> # create dataframe
>>> np.random.seed(619517)
>>> Nr=250
>>> y = np.random.randn(Nr)
>>> gr = np.random.choice(list("ABCDE"), Nr)
>>> norm_params=[(0, 1.2), (0.7, 1), (-0.5, 1.4), (0.3, 1), (0.8, 0.9)]
>>> for i, letter in enumerate("ABCDE"):
... y[gr == letter] *=norm_params[i][1]+ norm_params[i][0]
>>> df = pd.DataFrame(dict(Score=y, Group=gr))
>>> # define header params
>>> data_header = 'Score'
>>> group_header = 'Group'
>>> # make groupby object with pandas
>>> group_stats = {}
>>> groupby_data = df.groupby([group_header])
>>> for group in "ABCDE":
... data_from_group = groupby_data.get_group(group)[data_header]
... # take a stat of the grouped data
... stat = np.median(data_from_group)
... # add to dictionary
... group_stats[group] = stat
>>> # create violin fig
>>> fig = create_violin(df, data_header='Score', group_header='Group',
... height=600, width=1000, use_colorscale=True,
... group_stats=group_stats)
>>> # plot
>>> fig.show()
"""
| /usr/src/app/target_test_cases/failed_tests__violin.create_violin.txt | def create_violin(
data,
data_header=None,
group_header=None,
colors=None,
use_colorscale=False,
group_stats=None,
rugplot=True,
sort=False,
height=450,
width=600,
title="Violin and Rug Plot",
):
"""
**deprecated**, use instead the plotly.graph_objects trace
:class:`plotly.graph_objects.Violin`.
:param (list|array) data: accepts either a list of numerical values,
a list of dictionaries all with identical keys and at least one
column of numeric values, or a pandas dataframe with at least one
column of numbers.
:param (str) data_header: the header of the data column to be used
from an inputted pandas dataframe. Not applicable if 'data' is
a list of numeric values.
:param (str) group_header: applicable if grouping data by a variable.
'group_header' must be set to the name of the grouping variable.
:param (str|tuple|list|dict) colors: either a plotly scale name,
an rgb or hex color, a color tuple, a list of colors or a
dictionary. An rgb color is of the form 'rgb(x, y, z)' where
x, y and z belong to the interval [0, 255] and a color tuple is a
tuple of the form (a, b, c) where a, b and c belong to [0, 1].
If colors is a list, it must contain valid color types as its
members.
:param (bool) use_colorscale: only applicable if grouping by another
variable. Will implement a colorscale based on the first 2 colors
of param colors. This means colors must be a list with at least 2
colors in it (Plotly colorscales are accepted since they map to a
list of two rgb colors). Default = False
:param (dict) group_stats: a dictionary where each key is a unique
value from the group_header column in data. Each value must be a
number and will be used to color the violin plots if a colorscale
is being used.
:param (bool) rugplot: determines if a rugplot is draw on violin plot.
Default = True
:param (bool) sort: determines if violins are sorted
alphabetically (True) or by input order (False). Default = False
:param (float) height: the height of the violin plot.
:param (float) width: the width of the violin plot.
:param (str) title: the title of the violin plot.
Example 1: Single Violin Plot
>>> from plotly.figure_factory import create_violin
>>> import plotly.graph_objs as graph_objects
>>> import numpy as np
>>> from scipy import stats
>>> # create list of random values
>>> data_list = np.random.randn(100)
>>> # create violin fig
>>> fig = create_violin(data_list, colors='#604d9e')
>>> # plot
>>> fig.show()
Example 2: Multiple Violin Plots with Qualitative Coloring
>>> from plotly.figure_factory import create_violin
>>> import plotly.graph_objs as graph_objects
>>> import numpy as np
>>> import pandas as pd
>>> from scipy import stats
>>> # create dataframe
>>> np.random.seed(619517)
>>> Nr=250
>>> y = np.random.randn(Nr)
>>> gr = np.random.choice(list("ABCDE"), Nr)
>>> norm_params=[(0, 1.2), (0.7, 1), (-0.5, 1.4), (0.3, 1), (0.8, 0.9)]
>>> for i, letter in enumerate("ABCDE"):
... y[gr == letter] *=norm_params[i][1]+ norm_params[i][0]
>>> df = pd.DataFrame(dict(Score=y, Group=gr))
>>> # create violin fig
>>> fig = create_violin(df, data_header='Score', group_header='Group',
... sort=True, height=600, width=1000)
>>> # plot
>>> fig.show()
Example 3: Violin Plots with Colorscale
>>> from plotly.figure_factory import create_violin
>>> import plotly.graph_objs as graph_objects
>>> import numpy as np
>>> import pandas as pd
>>> from scipy import stats
>>> # create dataframe
>>> np.random.seed(619517)
>>> Nr=250
>>> y = np.random.randn(Nr)
>>> gr = np.random.choice(list("ABCDE"), Nr)
>>> norm_params=[(0, 1.2), (0.7, 1), (-0.5, 1.4), (0.3, 1), (0.8, 0.9)]
>>> for i, letter in enumerate("ABCDE"):
... y[gr == letter] *=norm_params[i][1]+ norm_params[i][0]
>>> df = pd.DataFrame(dict(Score=y, Group=gr))
>>> # define header params
>>> data_header = 'Score'
>>> group_header = 'Group'
>>> # make groupby object with pandas
>>> group_stats = {}
>>> groupby_data = df.groupby([group_header])
>>> for group in "ABCDE":
... data_from_group = groupby_data.get_group(group)[data_header]
... # take a stat of the grouped data
... stat = np.median(data_from_group)
... # add to dictionary
... group_stats[group] = stat
>>> # create violin fig
>>> fig = create_violin(df, data_header='Score', group_header='Group',
... height=600, width=1000, use_colorscale=True,
... group_stats=group_stats)
>>> # plot
>>> fig.show()
"""
# Validate colors
if isinstance(colors, dict):
valid_colors = clrs.validate_colors_dict(colors, "rgb")
else:
valid_colors = clrs.validate_colors(colors, "rgb")
# validate data and choose plot type
if group_header is None:
if isinstance(data, list):
if len(data) <= 0:
raise exceptions.PlotlyError(
"If data is a list, it must be "
"nonempty and contain either "
"numbers or dictionaries."
)
if not all(isinstance(element, Number) for element in data):
raise exceptions.PlotlyError(
"If data is a list, it must " "contain only numbers."
)
if pd and isinstance(data, pd.core.frame.DataFrame):
if data_header is None:
raise exceptions.PlotlyError(
"data_header must be the "
"column name with the "
"desired numeric data for "
"the violin plot."
)
data = data[data_header].values.tolist()
# call the plotting functions
plot_data, plot_xrange = violinplot(
data, fillcolor=valid_colors[0], rugplot=rugplot
)
layout = graph_objs.Layout(
title=title,
autosize=False,
font=graph_objs.layout.Font(size=11),
height=height,
showlegend=False,
width=width,
xaxis=make_XAxis("", plot_xrange),
yaxis=make_YAxis(""),
hovermode="closest",
)
layout["yaxis"].update(dict(showline=False, showticklabels=False, ticks=""))
fig = graph_objs.Figure(data=plot_data, layout=layout)
return fig
else:
if not isinstance(data, pd.core.frame.DataFrame):
raise exceptions.PlotlyError(
"Error. You must use a pandas "
"DataFrame if you are using a "
"group header."
)
if data_header is None:
raise exceptions.PlotlyError(
"data_header must be the column "
"name with the desired numeric "
"data for the violin plot."
)
if use_colorscale is False:
if isinstance(valid_colors, dict):
# validate colors dict choice below
fig = violin_dict(
data,
data_header,
group_header,
valid_colors,
use_colorscale,
group_stats,
rugplot,
sort,
height,
width,
title,
)
return fig
else:
fig = violin_no_colorscale(
data,
data_header,
group_header,
valid_colors,
use_colorscale,
group_stats,
rugplot,
sort,
height,
width,
title,
)
return fig
else:
if isinstance(valid_colors, dict):
raise exceptions.PlotlyError(
"The colors param cannot be "
"a dictionary if you are "
"using a colorscale."
)
if len(valid_colors) < 2:
raise exceptions.PlotlyError(
"colors must be a list with "
"at least 2 colors. A "
"Plotly scale is allowed."
)
if not isinstance(group_stats, dict):
raise exceptions.PlotlyError(
"Your group_stats param " "must be a dictionary."
)
fig = violin_colorscale(
data,
data_header,
group_header,
valid_colors,
use_colorscale,
group_stats,
rugplot,
sort,
height,
width,
title,
)
return fig
| _violin.create_violin |
plotly.py | 66 | packages/python/plotly/plotly/graph_objs/_waterfall.py | def __init__(
self,
arg=None,
alignmentgroup=None,
base=None,
cliponaxis=None,
connector=None,
constraintext=None,
customdata=None,
customdatasrc=None,
decreasing=None,
dx=None,
dy=None,
hoverinfo=None,
hoverinfosrc=None,
hoverlabel=None,
hovertemplate=None,
hovertemplatesrc=None,
hovertext=None,
hovertextsrc=None,
ids=None,
idssrc=None,
increasing=None,
insidetextanchor=None,
insidetextfont=None,
legend=None,
legendgroup=None,
legendgrouptitle=None,
legendrank=None,
legendwidth=None,
measure=None,
measuresrc=None,
meta=None,
metasrc=None,
name=None,
offset=None,
offsetgroup=None,
offsetsrc=None,
opacity=None,
orientation=None,
outsidetextfont=None,
selectedpoints=None,
showlegend=None,
stream=None,
text=None,
textangle=None,
textfont=None,
textinfo=None,
textposition=None,
textpositionsrc=None,
textsrc=None,
texttemplate=None,
texttemplatesrc=None,
totals=None,
uid=None,
uirevision=None,
visible=None,
width=None,
widthsrc=None,
x=None,
x0=None,
xaxis=None,
xhoverformat=None,
xperiod=None,
xperiod0=None,
xperiodalignment=None,
xsrc=None,
y=None,
y0=None,
yaxis=None,
yhoverformat=None,
yperiod=None,
yperiod0=None,
yperiodalignment=None,
ysrc=None,
zorder=None,
**kwargs,
):
"""
Construct a new Waterfall object
Draws waterfall trace which is useful graph to displays the
contribution of various elements (either positive or negative)
in a bar chart. The data visualized by the span of the bars is
set in `y` if `orientation` is set to "v" (the default) and the
labels are set in `x`. By setting `orientation` to "h", the
roles are interchanged.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.Waterfall`
alignmentgroup
Set several traces linked to the same position axis or
matching axes to the same alignmentgroup. This controls
whether bars compute their positional range dependently
or independently.
base
Sets where the bar base is drawn (in position axis
units).
cliponaxis
Determines whether the text nodes are clipped about the
subplot axes. To show the text nodes above axis lines
and tick labels, make sure to set `xaxis.layer` and
`yaxis.layer` to *below traces*.
connector
:class:`plotly.graph_objects.waterfall.Connector`
instance or dict with compatible properties
constraintext
Constrain the size of text inside or outside a bar to
be no larger than the bar itself.
customdata
Assigns extra data each datum. This may be useful when
listening to hover, click and selection events. Note
that, "scatter" traces also appends customdata items in
the markers DOM elements
customdatasrc
Sets the source reference on Chart Studio Cloud for
`customdata`.
decreasing
:class:`plotly.graph_objects.waterfall.Decreasing`
instance or dict with compatible properties
dx
Sets the x coordinate step. See `x0` for more info.
dy
Sets the y coordinate step. See `y0` for more info.
hoverinfo
Determines which trace information appear on hover. If
`none` or `skip` are set, no information is displayed
upon hovering. But, if `none` is set, click and hover
events are still fired.
hoverinfosrc
Sets the source reference on Chart Studio Cloud for
`hoverinfo`.
hoverlabel
:class:`plotly.graph_objects.waterfall.Hoverlabel`
instance or dict with compatible properties
hovertemplate
Template string used for rendering the information that
appear on hover box. Note that this will override
`hoverinfo`. Variables are inserted using %{variable},
for example "y: %{y}" as well as %{xother}, {%_xother},
{%_xother_}, {%xother_}. When showing info for several
points, "xother" will be added to those with different
x positions from the first point. An underscore before
or after "(x|y)other" will add a space on that side,
only when this field is shown. Numbers are formatted
using d3-format's syntax %{variable:d3-format}, for
example "Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. The variables available in
`hovertemplate` are the ones emitted as event data
described at this link
https://plotly.com/javascript/plotlyjs-events/#event-
data. Additionally, every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Finally, the template string has access
to variables `initial`, `delta` and `final`. Anything
contained in tag `<extra>` is displayed in the
secondary box, for example
"<extra>{fullData.name}</extra>". To hide the secondary
box completely, use an empty tag `<extra></extra>`.
hovertemplatesrc
Sets the source reference on Chart Studio Cloud for
`hovertemplate`.
hovertext
Sets hover text elements associated with each (x,y)
pair. If a single string, the same string appears over
all the data points. If an array of string, the items
are mapped in order to the this trace's (x,y)
coordinates. To be seen, trace `hoverinfo` must contain
a "text" flag.
hovertextsrc
Sets the source reference on Chart Studio Cloud for
`hovertext`.
ids
Assigns id labels to each datum. These ids for object
constancy of data points during animation. Should be an
array of strings, not numbers or any other type.
idssrc
Sets the source reference on Chart Studio Cloud for
`ids`.
increasing
:class:`plotly.graph_objects.waterfall.Increasing`
instance or dict with compatible properties
insidetextanchor
Determines if texts are kept at center or start/end
points in `textposition` "inside" mode.
insidetextfont
Sets the font used for `text` lying inside the bar.
legend
Sets the reference to a legend to show this trace in.
References to these legends are "legend", "legend2",
"legend3", etc. Settings for these legends are set in
the layout, under `layout.legend`, `layout.legend2`,
etc.
legendgroup
Sets the legend group for this trace. Traces and shapes
part of the same legend group hide/show at the same
time when toggling legend items.
legendgrouptitle
:class:`plotly.graph_objects.waterfall.Legendgrouptitle
` instance or dict with compatible properties
legendrank
Sets the legend rank for this trace. Items and groups
with smaller ranks are presented on top/left side while
with "reversed" `legend.traceorder` they are on
bottom/right side. The default legendrank is 1000, so
that you can use ranks less than 1000 to place certain
items before all unranked items, and ranks greater than
1000 to go after all unranked items. When having
unranked or equal rank items shapes would be displayed
after traces i.e. according to their order in data and
layout.
legendwidth
Sets the width (in px or fraction) of the legend for
this trace.
measure
An array containing types of values. By default the
values are considered as 'relative'. However; it is
possible to use 'total' to compute the sums. Also
'absolute' could be applied to reset the computed total
or to declare an initial value where needed.
measuresrc
Sets the source reference on Chart Studio Cloud for
`measure`.
meta
Assigns extra meta information associated with this
trace that can be used in various text attributes.
Attributes such as trace `name`, graph, axis and
colorbar `title.text`, annotation `text`
`rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta`
values in an attribute in the same trace, simply use
`%{meta[i]}` where `i` is the index or key of the
`meta` item in question. To access trace `meta` in
layout attributes, use `%{data[n[.meta[i]}` where `i`
is the index or key of the `meta` and `n` is the trace
index.
metasrc
Sets the source reference on Chart Studio Cloud for
`meta`.
name
Sets the trace name. The trace name appears as the
legend item and on hover.
offset
Shifts the position where the bar is drawn (in position
axis units). In "group" barmode, traces that set
"offset" will be excluded and drawn in "overlay" mode
instead.
offsetgroup
Set several traces linked to the same position axis or
matching axes to the same offsetgroup where bars of the
same position coordinate will line up.
offsetsrc
Sets the source reference on Chart Studio Cloud for
`offset`.
opacity
Sets the opacity of the trace.
orientation
Sets the orientation of the bars. With "v" ("h"), the
value of the each bar spans along the vertical
(horizontal).
outsidetextfont
Sets the font used for `text` lying outside the bar.
selectedpoints
Array containing integer indices of selected points.
Has an effect only for traces that support selections.
Note that an empty array means an empty selection where
the `unselected` are turned on for all points, whereas,
any other non-array values means no selection all where
the `selected` and `unselected` styles have no effect.
showlegend
Determines whether or not an item corresponding to this
trace is shown in the legend.
stream
:class:`plotly.graph_objects.waterfall.Stream` instance
or dict with compatible properties
text
Sets text elements associated with each (x,y) pair. If
a single string, the same string appears over all the
data points. If an array of string, the items are
mapped in order to the this trace's (x,y) coordinates.
If trace `hoverinfo` contains a "text" flag and
"hovertext" is not set, these elements will be seen in
the hover labels.
textangle
Sets the angle of the tick labels with respect to the
bar. For example, a `tickangle` of -90 draws the tick
labels vertically. With "auto" the texts may
automatically be rotated to fit with the maximum size
in bars.
textfont
Sets the font used for `text`.
textinfo
Determines which trace information appear on the graph.
In the case of having multiple waterfalls, totals are
computed separately (per trace).
textposition
Specifies the location of the `text`. "inside"
positions `text` inside, next to the bar end (rotated
and scaled if needed). "outside" positions `text`
outside, next to the bar end (scaled if needed), unless
there is another bar stacked on this one, then the text
gets pushed inside. "auto" tries to position `text`
inside the bar, but if the bar is too small and no bar
is stacked on this one the text is moved outside. If
"none", no text appears.
textpositionsrc
Sets the source reference on Chart Studio Cloud for
`textposition`.
textsrc
Sets the source reference on Chart Studio Cloud for
`text`.
texttemplate
Template string used for rendering the information text
that appear on points. Note that this will override
`textinfo`. Variables are inserted using %{variable},
for example "y: %{y}". Numbers are formatted using
d3-format's syntax %{variable:d3-format}, for example
"Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. Every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Finally, the template string has access
to variables `initial`, `delta`, `final` and `label`.
texttemplatesrc
Sets the source reference on Chart Studio Cloud for
`texttemplate`.
totals
:class:`plotly.graph_objects.waterfall.Totals` instance
or dict with compatible properties
uid
Assign an id to this trace, Use this to provide object
constancy between traces during animations and
transitions.
uirevision
Controls persistence of some user-driven changes to the
trace: `constraintrange` in `parcoords` traces, as well
as some `editable: true` modifications such as `name`
and `colorbar.title`. Defaults to `layout.uirevision`.
Note that other user-driven trace attribute changes are
controlled by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
width
Sets the bar width (in position axis units).
widthsrc
Sets the source reference on Chart Studio Cloud for
`width`.
x
Sets the x coordinates.
x0
Alternate to `x`. Builds a linear space of x
coordinates. Use with `dx` where `x0` is the starting
coordinate and `dx` the step.
xaxis
Sets a reference between this trace's x coordinates and
a 2D cartesian x axis. If "x" (the default value), the
x coordinates refer to `layout.xaxis`. If "x2", the x
coordinates refer to `layout.xaxis2`, and so on.
xhoverformat
Sets the hover text formatting rulefor `x` using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display *09~15~23.46*By default the values are
formatted using `xaxis.hoverformat`.
xperiod
Only relevant when the axis `type` is "date". Sets the
period positioning in milliseconds or "M<n>" on the x
axis. Special values in the form of "M<n>" could be
used to declare the number of months. In this case `n`
must be a positive integer.
xperiod0
Only relevant when the axis `type` is "date". Sets the
base for period positioning in milliseconds or date
string on the x0 axis. When `x0period` is round number
of weeks, the `x0period0` by default would be on a
Sunday i.e. 2000-01-02, otherwise it would be at
2000-01-01.
xperiodalignment
Only relevant when the axis `type` is "date". Sets the
alignment of data points on the x axis.
xsrc
Sets the source reference on Chart Studio Cloud for
`x`.
y
Sets the y coordinates.
y0
Alternate to `y`. Builds a linear space of y
coordinates. Use with `dy` where `y0` is the starting
coordinate and `dy` the step.
yaxis
Sets a reference between this trace's y coordinates and
a 2D cartesian y axis. If "y" (the default value), the
y coordinates refer to `layout.yaxis`. If "y2", the y
coordinates refer to `layout.yaxis2`, and so on.
yhoverformat
Sets the hover text formatting rulefor `y` using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display *09~15~23.46*By default the values are
formatted using `yaxis.hoverformat`.
yperiod
Only relevant when the axis `type` is "date". Sets the
period positioning in milliseconds or "M<n>" on the y
axis. Special values in the form of "M<n>" could be
used to declare the number of months. In this case `n`
must be a positive integer.
yperiod0
Only relevant when the axis `type` is "date". Sets the
base for period positioning in milliseconds or date
string on the y0 axis. When `y0period` is round number
of weeks, the `y0period0` by default would be on a
Sunday i.e. 2000-01-02, otherwise it would be at
2000-01-01.
yperiodalignment
Only relevant when the axis `type` is "date". Sets the
alignment of data points on the y axis.
ysrc
Sets the source reference on Chart Studio Cloud for
`y`.
zorder
Sets the layer on which this trace is displayed,
relative to other SVG traces on the same subplot. SVG
traces with higher `zorder` appear in front of those
with lower `zorder`.
Returns
-------
Waterfall
"""
| /usr/src/app/target_test_cases/failed_tests__waterfall.Waterfall.__init__.txt | def __init__(
self,
arg=None,
alignmentgroup=None,
base=None,
cliponaxis=None,
connector=None,
constraintext=None,
customdata=None,
customdatasrc=None,
decreasing=None,
dx=None,
dy=None,
hoverinfo=None,
hoverinfosrc=None,
hoverlabel=None,
hovertemplate=None,
hovertemplatesrc=None,
hovertext=None,
hovertextsrc=None,
ids=None,
idssrc=None,
increasing=None,
insidetextanchor=None,
insidetextfont=None,
legend=None,
legendgroup=None,
legendgrouptitle=None,
legendrank=None,
legendwidth=None,
measure=None,
measuresrc=None,
meta=None,
metasrc=None,
name=None,
offset=None,
offsetgroup=None,
offsetsrc=None,
opacity=None,
orientation=None,
outsidetextfont=None,
selectedpoints=None,
showlegend=None,
stream=None,
text=None,
textangle=None,
textfont=None,
textinfo=None,
textposition=None,
textpositionsrc=None,
textsrc=None,
texttemplate=None,
texttemplatesrc=None,
totals=None,
uid=None,
uirevision=None,
visible=None,
width=None,
widthsrc=None,
x=None,
x0=None,
xaxis=None,
xhoverformat=None,
xperiod=None,
xperiod0=None,
xperiodalignment=None,
xsrc=None,
y=None,
y0=None,
yaxis=None,
yhoverformat=None,
yperiod=None,
yperiod0=None,
yperiodalignment=None,
ysrc=None,
zorder=None,
**kwargs,
):
"""
Construct a new Waterfall object
Draws waterfall trace which is useful graph to displays the
contribution of various elements (either positive or negative)
in a bar chart. The data visualized by the span of the bars is
set in `y` if `orientation` is set to "v" (the default) and the
labels are set in `x`. By setting `orientation` to "h", the
roles are interchanged.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.Waterfall`
alignmentgroup
Set several traces linked to the same position axis or
matching axes to the same alignmentgroup. This controls
whether bars compute their positional range dependently
or independently.
base
Sets where the bar base is drawn (in position axis
units).
cliponaxis
Determines whether the text nodes are clipped about the
subplot axes. To show the text nodes above axis lines
and tick labels, make sure to set `xaxis.layer` and
`yaxis.layer` to *below traces*.
connector
:class:`plotly.graph_objects.waterfall.Connector`
instance or dict with compatible properties
constraintext
Constrain the size of text inside or outside a bar to
be no larger than the bar itself.
customdata
Assigns extra data each datum. This may be useful when
listening to hover, click and selection events. Note
that, "scatter" traces also appends customdata items in
the markers DOM elements
customdatasrc
Sets the source reference on Chart Studio Cloud for
`customdata`.
decreasing
:class:`plotly.graph_objects.waterfall.Decreasing`
instance or dict with compatible properties
dx
Sets the x coordinate step. See `x0` for more info.
dy
Sets the y coordinate step. See `y0` for more info.
hoverinfo
Determines which trace information appear on hover. If
`none` or `skip` are set, no information is displayed
upon hovering. But, if `none` is set, click and hover
events are still fired.
hoverinfosrc
Sets the source reference on Chart Studio Cloud for
`hoverinfo`.
hoverlabel
:class:`plotly.graph_objects.waterfall.Hoverlabel`
instance or dict with compatible properties
hovertemplate
Template string used for rendering the information that
appear on hover box. Note that this will override
`hoverinfo`. Variables are inserted using %{variable},
for example "y: %{y}" as well as %{xother}, {%_xother},
{%_xother_}, {%xother_}. When showing info for several
points, "xother" will be added to those with different
x positions from the first point. An underscore before
or after "(x|y)other" will add a space on that side,
only when this field is shown. Numbers are formatted
using d3-format's syntax %{variable:d3-format}, for
example "Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. The variables available in
`hovertemplate` are the ones emitted as event data
described at this link
https://plotly.com/javascript/plotlyjs-events/#event-
data. Additionally, every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Finally, the template string has access
to variables `initial`, `delta` and `final`. Anything
contained in tag `<extra>` is displayed in the
secondary box, for example
"<extra>{fullData.name}</extra>". To hide the secondary
box completely, use an empty tag `<extra></extra>`.
hovertemplatesrc
Sets the source reference on Chart Studio Cloud for
`hovertemplate`.
hovertext
Sets hover text elements associated with each (x,y)
pair. If a single string, the same string appears over
all the data points. If an array of string, the items
are mapped in order to the this trace's (x,y)
coordinates. To be seen, trace `hoverinfo` must contain
a "text" flag.
hovertextsrc
Sets the source reference on Chart Studio Cloud for
`hovertext`.
ids
Assigns id labels to each datum. These ids for object
constancy of data points during animation. Should be an
array of strings, not numbers or any other type.
idssrc
Sets the source reference on Chart Studio Cloud for
`ids`.
increasing
:class:`plotly.graph_objects.waterfall.Increasing`
instance or dict with compatible properties
insidetextanchor
Determines if texts are kept at center or start/end
points in `textposition` "inside" mode.
insidetextfont
Sets the font used for `text` lying inside the bar.
legend
Sets the reference to a legend to show this trace in.
References to these legends are "legend", "legend2",
"legend3", etc. Settings for these legends are set in
the layout, under `layout.legend`, `layout.legend2`,
etc.
legendgroup
Sets the legend group for this trace. Traces and shapes
part of the same legend group hide/show at the same
time when toggling legend items.
legendgrouptitle
:class:`plotly.graph_objects.waterfall.Legendgrouptitle
` instance or dict with compatible properties
legendrank
Sets the legend rank for this trace. Items and groups
with smaller ranks are presented on top/left side while
with "reversed" `legend.traceorder` they are on
bottom/right side. The default legendrank is 1000, so
that you can use ranks less than 1000 to place certain
items before all unranked items, and ranks greater than
1000 to go after all unranked items. When having
unranked or equal rank items shapes would be displayed
after traces i.e. according to their order in data and
layout.
legendwidth
Sets the width (in px or fraction) of the legend for
this trace.
measure
An array containing types of values. By default the
values are considered as 'relative'. However; it is
possible to use 'total' to compute the sums. Also
'absolute' could be applied to reset the computed total
or to declare an initial value where needed.
measuresrc
Sets the source reference on Chart Studio Cloud for
`measure`.
meta
Assigns extra meta information associated with this
trace that can be used in various text attributes.
Attributes such as trace `name`, graph, axis and
colorbar `title.text`, annotation `text`
`rangeselector`, `updatemenues` and `sliders` `label`
text all support `meta`. To access the trace `meta`
values in an attribute in the same trace, simply use
`%{meta[i]}` where `i` is the index or key of the
`meta` item in question. To access trace `meta` in
layout attributes, use `%{data[n[.meta[i]}` where `i`
is the index or key of the `meta` and `n` is the trace
index.
metasrc
Sets the source reference on Chart Studio Cloud for
`meta`.
name
Sets the trace name. The trace name appears as the
legend item and on hover.
offset
Shifts the position where the bar is drawn (in position
axis units). In "group" barmode, traces that set
"offset" will be excluded and drawn in "overlay" mode
instead.
offsetgroup
Set several traces linked to the same position axis or
matching axes to the same offsetgroup where bars of the
same position coordinate will line up.
offsetsrc
Sets the source reference on Chart Studio Cloud for
`offset`.
opacity
Sets the opacity of the trace.
orientation
Sets the orientation of the bars. With "v" ("h"), the
value of the each bar spans along the vertical
(horizontal).
outsidetextfont
Sets the font used for `text` lying outside the bar.
selectedpoints
Array containing integer indices of selected points.
Has an effect only for traces that support selections.
Note that an empty array means an empty selection where
the `unselected` are turned on for all points, whereas,
any other non-array values means no selection all where
the `selected` and `unselected` styles have no effect.
showlegend
Determines whether or not an item corresponding to this
trace is shown in the legend.
stream
:class:`plotly.graph_objects.waterfall.Stream` instance
or dict with compatible properties
text
Sets text elements associated with each (x,y) pair. If
a single string, the same string appears over all the
data points. If an array of string, the items are
mapped in order to the this trace's (x,y) coordinates.
If trace `hoverinfo` contains a "text" flag and
"hovertext" is not set, these elements will be seen in
the hover labels.
textangle
Sets the angle of the tick labels with respect to the
bar. For example, a `tickangle` of -90 draws the tick
labels vertically. With "auto" the texts may
automatically be rotated to fit with the maximum size
in bars.
textfont
Sets the font used for `text`.
textinfo
Determines which trace information appear on the graph.
In the case of having multiple waterfalls, totals are
computed separately (per trace).
textposition
Specifies the location of the `text`. "inside"
positions `text` inside, next to the bar end (rotated
and scaled if needed). "outside" positions `text`
outside, next to the bar end (scaled if needed), unless
there is another bar stacked on this one, then the text
gets pushed inside. "auto" tries to position `text`
inside the bar, but if the bar is too small and no bar
is stacked on this one the text is moved outside. If
"none", no text appears.
textpositionsrc
Sets the source reference on Chart Studio Cloud for
`textposition`.
textsrc
Sets the source reference on Chart Studio Cloud for
`text`.
texttemplate
Template string used for rendering the information text
that appear on points. Note that this will override
`textinfo`. Variables are inserted using %{variable},
for example "y: %{y}". Numbers are formatted using
d3-format's syntax %{variable:d3-format}, for example
"Price: %{y:$.2f}".
https://github.com/d3/d3-format/tree/v1.4.5#d3-format
for details on the formatting syntax. Dates are
formatted using d3-time-format's syntax
%{variable|d3-time-format}, for example "Day:
%{2019-01-01|%A}". https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format for details on the
date formatting syntax. Every attributes that can be
specified per-point (the ones that are `arrayOk: true`)
are available. Finally, the template string has access
to variables `initial`, `delta`, `final` and `label`.
texttemplatesrc
Sets the source reference on Chart Studio Cloud for
`texttemplate`.
totals
:class:`plotly.graph_objects.waterfall.Totals` instance
or dict with compatible properties
uid
Assign an id to this trace, Use this to provide object
constancy between traces during animations and
transitions.
uirevision
Controls persistence of some user-driven changes to the
trace: `constraintrange` in `parcoords` traces, as well
as some `editable: true` modifications such as `name`
and `colorbar.title`. Defaults to `layout.uirevision`.
Note that other user-driven trace attribute changes are
controlled by `layout` attributes: `trace.visible` is
controlled by `layout.legend.uirevision`,
`selectedpoints` is controlled by
`layout.selectionrevision`, and `colorbar.(x|y)`
(accessible with `config: {editable: true}`) is
controlled by `layout.editrevision`. Trace changes are
tracked by `uid`, which only falls back on trace index
if no `uid` is provided. So if your app can add/remove
traces before the end of the `data` array, such that
the same trace has a different index, you can still
preserve user-driven changes if you give each trace a
`uid` that stays with it as it moves.
visible
Determines whether or not this trace is visible. If
"legendonly", the trace is not drawn, but can appear as
a legend item (provided that the legend itself is
visible).
width
Sets the bar width (in position axis units).
widthsrc
Sets the source reference on Chart Studio Cloud for
`width`.
x
Sets the x coordinates.
x0
Alternate to `x`. Builds a linear space of x
coordinates. Use with `dx` where `x0` is the starting
coordinate and `dx` the step.
xaxis
Sets a reference between this trace's x coordinates and
a 2D cartesian x axis. If "x" (the default value), the
x coordinates refer to `layout.xaxis`. If "x2", the x
coordinates refer to `layout.xaxis2`, and so on.
xhoverformat
Sets the hover text formatting rulefor `x` using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display *09~15~23.46*By default the values are
formatted using `xaxis.hoverformat`.
xperiod
Only relevant when the axis `type` is "date". Sets the
period positioning in milliseconds or "M<n>" on the x
axis. Special values in the form of "M<n>" could be
used to declare the number of months. In this case `n`
must be a positive integer.
xperiod0
Only relevant when the axis `type` is "date". Sets the
base for period positioning in milliseconds or date
string on the x0 axis. When `x0period` is round number
of weeks, the `x0period0` by default would be on a
Sunday i.e. 2000-01-02, otherwise it would be at
2000-01-01.
xperiodalignment
Only relevant when the axis `type` is "date". Sets the
alignment of data points on the x axis.
xsrc
Sets the source reference on Chart Studio Cloud for
`x`.
y
Sets the y coordinates.
y0
Alternate to `y`. Builds a linear space of y
coordinates. Use with `dy` where `y0` is the starting
coordinate and `dy` the step.
yaxis
Sets a reference between this trace's y coordinates and
a 2D cartesian y axis. If "y" (the default value), the
y coordinates refer to `layout.yaxis`. If "y2", the y
coordinates refer to `layout.yaxis2`, and so on.
yhoverformat
Sets the hover text formatting rulefor `y` using d3
formatting mini-languages which are very similar to
those in Python. For numbers, see:
https://github.com/d3/d3-format/tree/v1.4.5#d3-format.
And for dates see: https://github.com/d3/d3-time-
format/tree/v2.2.3#locale_format. We add two items to
d3's date formatter: "%h" for half of the year as a
decimal number as well as "%{n}f" for fractional
seconds with n digits. For example, *2016-10-13
09:15:23.456* with tickformat "%H~%M~%S.%2f" would
display *09~15~23.46*By default the values are
formatted using `yaxis.hoverformat`.
yperiod
Only relevant when the axis `type` is "date". Sets the
period positioning in milliseconds or "M<n>" on the y
axis. Special values in the form of "M<n>" could be
used to declare the number of months. In this case `n`
must be a positive integer.
yperiod0
Only relevant when the axis `type` is "date". Sets the
base for period positioning in milliseconds or date
string on the y0 axis. When `y0period` is round number
of weeks, the `y0period0` by default would be on a
Sunday i.e. 2000-01-02, otherwise it would be at
2000-01-01.
yperiodalignment
Only relevant when the axis `type` is "date". Sets the
alignment of data points on the y axis.
ysrc
Sets the source reference on Chart Studio Cloud for
`y`.
zorder
Sets the layer on which this trace is displayed,
relative to other SVG traces on the same subplot. SVG
traces with higher `zorder` appear in front of those
with lower `zorder`.
Returns
-------
Waterfall
"""
super(Waterfall, self).__init__("waterfall")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
# Validate arg
# ------------
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError(
"""\
The first argument to the plotly.graph_objs.Waterfall
constructor must be a dict or
an instance of :class:`plotly.graph_objs.Waterfall`"""
)
# Handle skip_invalid
# -------------------
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
# Populate data dict with properties
# ----------------------------------
_v = arg.pop("alignmentgroup", None)
_v = alignmentgroup if alignmentgroup is not None else _v
if _v is not None:
self["alignmentgroup"] = _v
_v = arg.pop("base", None)
_v = base if base is not None else _v
if _v is not None:
self["base"] = _v
_v = arg.pop("cliponaxis", None)
_v = cliponaxis if cliponaxis is not None else _v
if _v is not None:
self["cliponaxis"] = _v
_v = arg.pop("connector", None)
_v = connector if connector is not None else _v
if _v is not None:
self["connector"] = _v
_v = arg.pop("constraintext", None)
_v = constraintext if constraintext is not None else _v
if _v is not None:
self["constraintext"] = _v
_v = arg.pop("customdata", None)
_v = customdata if customdata is not None else _v
if _v is not None:
self["customdata"] = _v
_v = arg.pop("customdatasrc", None)
_v = customdatasrc if customdatasrc is not None else _v
if _v is not None:
self["customdatasrc"] = _v
_v = arg.pop("decreasing", None)
_v = decreasing if decreasing is not None else _v
if _v is not None:
self["decreasing"] = _v
_v = arg.pop("dx", None)
_v = dx if dx is not None else _v
if _v is not None:
self["dx"] = _v
_v = arg.pop("dy", None)
_v = dy if dy is not None else _v
if _v is not None:
self["dy"] = _v
_v = arg.pop("hoverinfo", None)
_v = hoverinfo if hoverinfo is not None else _v
if _v is not None:
self["hoverinfo"] = _v
_v = arg.pop("hoverinfosrc", None)
_v = hoverinfosrc if hoverinfosrc is not None else _v
if _v is not None:
self["hoverinfosrc"] = _v
_v = arg.pop("hoverlabel", None)
_v = hoverlabel if hoverlabel is not None else _v
if _v is not None:
self["hoverlabel"] = _v
_v = arg.pop("hovertemplate", None)
_v = hovertemplate if hovertemplate is not None else _v
if _v is not None:
self["hovertemplate"] = _v
_v = arg.pop("hovertemplatesrc", None)
_v = hovertemplatesrc if hovertemplatesrc is not None else _v
if _v is not None:
self["hovertemplatesrc"] = _v
_v = arg.pop("hovertext", None)
_v = hovertext if hovertext is not None else _v
if _v is not None:
self["hovertext"] = _v
_v = arg.pop("hovertextsrc", None)
_v = hovertextsrc if hovertextsrc is not None else _v
if _v is not None:
self["hovertextsrc"] = _v
_v = arg.pop("ids", None)
_v = ids if ids is not None else _v
if _v is not None:
self["ids"] = _v
_v = arg.pop("idssrc", None)
_v = idssrc if idssrc is not None else _v
if _v is not None:
self["idssrc"] = _v
_v = arg.pop("increasing", None)
_v = increasing if increasing is not None else _v
if _v is not None:
self["increasing"] = _v
_v = arg.pop("insidetextanchor", None)
_v = insidetextanchor if insidetextanchor is not None else _v
if _v is not None:
self["insidetextanchor"] = _v
_v = arg.pop("insidetextfont", None)
_v = insidetextfont if insidetextfont is not None else _v
if _v is not None:
self["insidetextfont"] = _v
_v = arg.pop("legend", None)
_v = legend if legend is not None else _v
if _v is not None:
self["legend"] = _v
_v = arg.pop("legendgroup", None)
_v = legendgroup if legendgroup is not None else _v
if _v is not None:
self["legendgroup"] = _v
_v = arg.pop("legendgrouptitle", None)
_v = legendgrouptitle if legendgrouptitle is not None else _v
if _v is not None:
self["legendgrouptitle"] = _v
_v = arg.pop("legendrank", None)
_v = legendrank if legendrank is not None else _v
if _v is not None:
self["legendrank"] = _v
_v = arg.pop("legendwidth", None)
_v = legendwidth if legendwidth is not None else _v
if _v is not None:
self["legendwidth"] = _v
_v = arg.pop("measure", None)
_v = measure if measure is not None else _v
if _v is not None:
self["measure"] = _v
_v = arg.pop("measuresrc", None)
_v = measuresrc if measuresrc is not None else _v
if _v is not None:
self["measuresrc"] = _v
_v = arg.pop("meta", None)
_v = meta if meta is not None else _v
if _v is not None:
self["meta"] = _v
_v = arg.pop("metasrc", None)
_v = metasrc if metasrc is not None else _v
if _v is not None:
self["metasrc"] = _v
_v = arg.pop("name", None)
_v = name if name is not None else _v
if _v is not None:
self["name"] = _v
_v = arg.pop("offset", None)
_v = offset if offset is not None else _v
if _v is not None:
self["offset"] = _v
_v = arg.pop("offsetgroup", None)
_v = offsetgroup if offsetgroup is not None else _v
if _v is not None:
self["offsetgroup"] = _v
_v = arg.pop("offsetsrc", None)
_v = offsetsrc if offsetsrc is not None else _v
if _v is not None:
self["offsetsrc"] = _v
_v = arg.pop("opacity", None)
_v = opacity if opacity is not None else _v
if _v is not None:
self["opacity"] = _v
_v = arg.pop("orientation", None)
_v = orientation if orientation is not None else _v
if _v is not None:
self["orientation"] = _v
_v = arg.pop("outsidetextfont", None)
_v = outsidetextfont if outsidetextfont is not None else _v
if _v is not None:
self["outsidetextfont"] = _v
_v = arg.pop("selectedpoints", None)
_v = selectedpoints if selectedpoints is not None else _v
if _v is not None:
self["selectedpoints"] = _v
_v = arg.pop("showlegend", None)
_v = showlegend if showlegend is not None else _v
if _v is not None:
self["showlegend"] = _v
_v = arg.pop("stream", None)
_v = stream if stream is not None else _v
if _v is not None:
self["stream"] = _v
_v = arg.pop("text", None)
_v = text if text is not None else _v
if _v is not None:
self["text"] = _v
_v = arg.pop("textangle", None)
_v = textangle if textangle is not None else _v
if _v is not None:
self["textangle"] = _v
_v = arg.pop("textfont", None)
_v = textfont if textfont is not None else _v
if _v is not None:
self["textfont"] = _v
_v = arg.pop("textinfo", None)
_v = textinfo if textinfo is not None else _v
if _v is not None:
self["textinfo"] = _v
_v = arg.pop("textposition", None)
_v = textposition if textposition is not None else _v
if _v is not None:
self["textposition"] = _v
_v = arg.pop("textpositionsrc", None)
_v = textpositionsrc if textpositionsrc is not None else _v
if _v is not None:
self["textpositionsrc"] = _v
_v = arg.pop("textsrc", None)
_v = textsrc if textsrc is not None else _v
if _v is not None:
self["textsrc"] = _v
_v = arg.pop("texttemplate", None)
_v = texttemplate if texttemplate is not None else _v
if _v is not None:
self["texttemplate"] = _v
_v = arg.pop("texttemplatesrc", None)
_v = texttemplatesrc if texttemplatesrc is not None else _v
if _v is not None:
self["texttemplatesrc"] = _v
_v = arg.pop("totals", None)
_v = totals if totals is not None else _v
if _v is not None:
self["totals"] = _v
_v = arg.pop("uid", None)
_v = uid if uid is not None else _v
if _v is not None:
self["uid"] = _v
_v = arg.pop("uirevision", None)
_v = uirevision if uirevision is not None else _v
if _v is not None:
self["uirevision"] = _v
_v = arg.pop("visible", None)
_v = visible if visible is not None else _v
if _v is not None:
self["visible"] = _v
_v = arg.pop("width", None)
_v = width if width is not None else _v
if _v is not None:
self["width"] = _v
_v = arg.pop("widthsrc", None)
_v = widthsrc if widthsrc is not None else _v
if _v is not None:
self["widthsrc"] = _v
_v = arg.pop("x", None)
_v = x if x is not None else _v
if _v is not None:
self["x"] = _v
_v = arg.pop("x0", None)
_v = x0 if x0 is not None else _v
if _v is not None:
self["x0"] = _v
_v = arg.pop("xaxis", None)
_v = xaxis if xaxis is not None else _v
if _v is not None:
self["xaxis"] = _v
_v = arg.pop("xhoverformat", None)
_v = xhoverformat if xhoverformat is not None else _v
if _v is not None:
self["xhoverformat"] = _v
_v = arg.pop("xperiod", None)
_v = xperiod if xperiod is not None else _v
if _v is not None:
self["xperiod"] = _v
_v = arg.pop("xperiod0", None)
_v = xperiod0 if xperiod0 is not None else _v
if _v is not None:
self["xperiod0"] = _v
_v = arg.pop("xperiodalignment", None)
_v = xperiodalignment if xperiodalignment is not None else _v
if _v is not None:
self["xperiodalignment"] = _v
_v = arg.pop("xsrc", None)
_v = xsrc if xsrc is not None else _v
if _v is not None:
self["xsrc"] = _v
_v = arg.pop("y", None)
_v = y if y is not None else _v
if _v is not None:
self["y"] = _v
_v = arg.pop("y0", None)
_v = y0 if y0 is not None else _v
if _v is not None:
self["y0"] = _v
_v = arg.pop("yaxis", None)
_v = yaxis if yaxis is not None else _v
if _v is not None:
self["yaxis"] = _v
_v = arg.pop("yhoverformat", None)
_v = yhoverformat if yhoverformat is not None else _v
if _v is not None:
self["yhoverformat"] = _v
_v = arg.pop("yperiod", None)
_v = yperiod if yperiod is not None else _v
if _v is not None:
self["yperiod"] = _v
_v = arg.pop("yperiod0", None)
_v = yperiod0 if yperiod0 is not None else _v
if _v is not None:
self["yperiod0"] = _v
_v = arg.pop("yperiodalignment", None)
_v = yperiodalignment if yperiodalignment is not None else _v
if _v is not None:
self["yperiodalignment"] = _v
_v = arg.pop("ysrc", None)
_v = ysrc if ysrc is not None else _v
if _v is not None:
self["ysrc"] = _v
_v = arg.pop("zorder", None)
_v = zorder if zorder is not None else _v
if _v is not None:
self["zorder"] = _v
# Read-only literals
# ------------------
self._props["type"] = "waterfall"
arg.pop("type", None)
# Process unknown kwargs
# ----------------------
self._process_kwargs(**dict(arg, **kwargs))
# Reset skip_invalid
# ------------------
self._skip_invalid = False
| _waterfall.Waterfall.__init__ |
plotly.py | 67 | packages/python/plotly/plotly/basedatatypes.py | def add_trace(
self, trace, row=None, col=None, secondary_y=None, exclude_empty_subplots=False
):
"""
Add a trace to the figure
Parameters
----------
trace : BaseTraceType or dict
Either:
- An instances of a trace classe from the plotly.graph_objs
package (e.g plotly.graph_objs.Scatter, plotly.graph_objs.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.
Returns
-------
BaseFigure
The Figure that add_trace was called on
Examples
--------
>>> from plotly import subplots
>>> import plotly.graph_objs 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])) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2])) # doctest: +ELLIPSIS
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) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=2, col=1) # doctest: +ELLIPSIS
Figure(...)
"""
| /usr/src/app/target_test_cases/failed_tests_basedatatypes.BaseFigure.add_trace.txt | def add_trace(
self, trace, row=None, col=None, secondary_y=None, exclude_empty_subplots=False
):
"""
Add a trace to the figure
Parameters
----------
trace : BaseTraceType or dict
Either:
- An instances of a trace classe from the plotly.graph_objs
package (e.g plotly.graph_objs.Scatter, plotly.graph_objs.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.
Returns
-------
BaseFigure
The Figure that add_trace was called on
Examples
--------
>>> from plotly import subplots
>>> import plotly.graph_objs 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])) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2])) # doctest: +ELLIPSIS
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) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=2, col=1) # doctest: +ELLIPSIS
Figure(...)
"""
# Make sure we have both row and col or neither
if row is not None and col is None:
raise ValueError(
"Received row parameter but not col.\n"
"row and col must be specified together"
)
elif col is not None and row is None:
raise ValueError(
"Received col parameter but not row.\n"
"row and col must be specified together"
)
# Address multiple subplots
if row is not None and _is_select_subplot_coordinates_arg(row, col):
# TODO add product argument
rows_cols = self._select_subplot_coordinates(row, col)
for r, c in rows_cols:
self.add_trace(
trace,
row=r,
col=c,
secondary_y=secondary_y,
exclude_empty_subplots=exclude_empty_subplots,
)
return self
return self.add_traces(
data=[trace],
rows=[row] if row is not None else None,
cols=[col] if col is not None else None,
secondary_ys=[secondary_y] if secondary_y is not None else None,
exclude_empty_subplots=exclude_empty_subplots,
)
| basedatatypes.BaseFigure.add_trace |
plotly.py | 68 | packages/python/plotly/plotly/basedatatypes.py | def batch_animate(self, 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
- quad
- cubic
- sin
- exp
- circle
- elastic
- back
- 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_objs 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
"""
| /usr/src/app/target_test_cases/failed_tests_basedatatypes.batch_animate.txt | def batch_animate(self, 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
- quad
- cubic
- sin
- exp
- circle
- elastic
- back
- 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_objs 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
"""
# Validate inputs
# ---------------
duration = self._animation_duration_validator.validate_coerce(duration)
easing = self._animation_easing_validator.validate_coerce(easing)
if self._in_batch_mode is True:
yield
else:
try:
self._in_batch_mode = True
yield
finally:
# Exit batch mode
# ---------------
self._in_batch_mode = False
# Apply batch animate
# -------------------
self._perform_batch_animate(
{
"transition": {"duration": duration, "easing": easing},
"frame": {"duration": duration},
}
)
| basedatatypes.batch_animate |
plotly.py | 69 | packages/python/plotly/plotly/express/imshow_utils.py | def rescale_intensity(image, in_range="image", out_range="dtype"):
"""Return image after stretching or shrinking its intensity levels.
The desired intensity range of the input and output, `in_range` and
`out_range` respectively, are used to stretch or shrink the intensity range
of the input image. See examples below.
Parameters
----------
image : array
Image array.
in_range, out_range : str or 2-tuple, optional
Min and max intensity values of input and output image.
The possible values for this parameter are enumerated below.
'image'
Use image min/max as the intensity range.
'dtype'
Use min/max of the image's dtype as the intensity range.
dtype-name
Use intensity range based on desired `dtype`. Must be valid key
in `DTYPE_RANGE`.
2-tuple
Use `range_values` as explicit min/max intensities.
Returns
-------
out : array
Image array after rescaling its intensity. This image is the same dtype
as the input image.
Notes
-----
.. versionchanged:: 0.17
The dtype of the output array has changed to match the output dtype, or
float if the output range is specified by a pair of floats.
See Also
--------
equalize_hist
Examples
--------
By default, the min/max intensities of the input image are stretched to
the limits allowed by the image's dtype, since `in_range` defaults to
'image' and `out_range` defaults to 'dtype':
>>> image = np.array([51, 102, 153], dtype=np.uint8)
>>> rescale_intensity(image)
array([ 0, 127, 255], dtype=uint8)
It's easy to accidentally convert an image dtype from uint8 to float:
>>> 1.0 * image
array([ 51., 102., 153.])
Use `rescale_intensity` to rescale to the proper range for float dtypes:
>>> image_float = 1.0 * image
>>> rescale_intensity(image_float)
array([0. , 0.5, 1. ])
To maintain the low contrast of the original, use the `in_range` parameter:
>>> rescale_intensity(image_float, in_range=(0, 255))
array([0.2, 0.4, 0.6])
If the min/max value of `in_range` is more/less than the min/max image
intensity, then the intensity levels are clipped:
>>> rescale_intensity(image_float, in_range=(0, 102))
array([0.5, 1. , 1. ])
If you have an image with signed integers but want to rescale the image to
just the positive range, use the `out_range` parameter. In that case, the
output dtype will be float:
>>> image = np.array([-10, 0, 10], dtype=np.int8)
>>> rescale_intensity(image, out_range=(0, 127))
array([ 0. , 63.5, 127. ])
To get the desired range with a specific dtype, use ``.astype()``:
>>> rescale_intensity(image, out_range=(0, 127)).astype(np.int8)
array([ 0, 63, 127], dtype=int8)
If the input image is constant, the output will be clipped directly to the
output range:
>>> image = np.array([130, 130, 130], dtype=np.int32)
>>> rescale_intensity(image, out_range=(0, 127)).astype(np.int32)
array([127, 127, 127], dtype=int32)
"""
| /usr/src/app/target_test_cases/failed_tests_imshow_utils.rescale_intensity.txt | def rescale_intensity(image, in_range="image", out_range="dtype"):
"""Return image after stretching or shrinking its intensity levels.
The desired intensity range of the input and output, `in_range` and
`out_range` respectively, are used to stretch or shrink the intensity range
of the input image. See examples below.
Parameters
----------
image : array
Image array.
in_range, out_range : str or 2-tuple, optional
Min and max intensity values of input and output image.
The possible values for this parameter are enumerated below.
'image'
Use image min/max as the intensity range.
'dtype'
Use min/max of the image's dtype as the intensity range.
dtype-name
Use intensity range based on desired `dtype`. Must be valid key
in `DTYPE_RANGE`.
2-tuple
Use `range_values` as explicit min/max intensities.
Returns
-------
out : array
Image array after rescaling its intensity. This image is the same dtype
as the input image.
Notes
-----
.. versionchanged:: 0.17
The dtype of the output array has changed to match the output dtype, or
float if the output range is specified by a pair of floats.
See Also
--------
equalize_hist
Examples
--------
By default, the min/max intensities of the input image are stretched to
the limits allowed by the image's dtype, since `in_range` defaults to
'image' and `out_range` defaults to 'dtype':
>>> image = np.array([51, 102, 153], dtype=np.uint8)
>>> rescale_intensity(image)
array([ 0, 127, 255], dtype=uint8)
It's easy to accidentally convert an image dtype from uint8 to float:
>>> 1.0 * image
array([ 51., 102., 153.])
Use `rescale_intensity` to rescale to the proper range for float dtypes:
>>> image_float = 1.0 * image
>>> rescale_intensity(image_float)
array([0. , 0.5, 1. ])
To maintain the low contrast of the original, use the `in_range` parameter:
>>> rescale_intensity(image_float, in_range=(0, 255))
array([0.2, 0.4, 0.6])
If the min/max value of `in_range` is more/less than the min/max image
intensity, then the intensity levels are clipped:
>>> rescale_intensity(image_float, in_range=(0, 102))
array([0.5, 1. , 1. ])
If you have an image with signed integers but want to rescale the image to
just the positive range, use the `out_range` parameter. In that case, the
output dtype will be float:
>>> image = np.array([-10, 0, 10], dtype=np.int8)
>>> rescale_intensity(image, out_range=(0, 127))
array([ 0. , 63.5, 127. ])
To get the desired range with a specific dtype, use ``.astype()``:
>>> rescale_intensity(image, out_range=(0, 127)).astype(np.int8)
array([ 0, 63, 127], dtype=int8)
If the input image is constant, the output will be clipped directly to the
output range:
>>> image = np.array([130, 130, 130], dtype=np.int32)
>>> rescale_intensity(image, out_range=(0, 127)).astype(np.int32)
array([127, 127, 127], dtype=int32)
"""
if out_range in ["dtype", "image"]:
out_dtype = _output_dtype(image.dtype.type)
else:
out_dtype = _output_dtype(out_range)
imin, imax = map(float, intensity_range(image, in_range))
omin, omax = map(
float, intensity_range(image, out_range, clip_negative=(imin >= 0))
)
if np.any(np.isnan([imin, imax, omin, omax])):
warn(
"One or more intensity levels are NaN. Rescaling will broadcast "
"NaN to the full image. Provide intensity levels yourself to "
"avoid this. E.g. with np.nanmin(image), np.nanmax(image).",
stacklevel=2,
)
image = np.clip(image, imin, imax)
if imin != imax:
image = (image - imin) / (imax - imin)
return np.asarray(image * (omax - omin) + omin, dtype=out_dtype)
else:
return np.clip(image, omin, omax).astype(out_dtype)
| imshow_utils.rescale_intensity |
plotly.py | 70 | packages/python/plotly/plotly/offline/offline.py | def iplot(
figure_or_data,
show_link=False,
link_text="Export to plot.ly",
validate=True,
image=None,
filename="plot_image",
image_width=800,
image_height=600,
config=None,
auto_play=True,
animation_opts=None,
):
"""
Draw plotly graphs inside an IPython or Jupyter notebook
figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or
dict or list that describes a Plotly graph.
See https://plot.ly/python/ for examples of
graph descriptions.
Keyword arguments:
show_link (default=False) -- display a link in the bottom-right corner of
of the chart that will export the chart to
Plotly Cloud or Plotly Enterprise
link_text (default='Export to plot.ly') -- the text of export link
validate (default=True) -- validate that all of the keys in the figure
are valid? omit if your version of plotly.js
has become outdated with your version of
graph_reference.json or if you need to include
extra, unnecessary keys in your figure.
image (default=None |'png' |'jpeg' |'svg' |'webp') -- This parameter sets
the format of the image to be downloaded, if we choose to download an
image. This parameter has a default value of None indicating that no
image should be downloaded. Please note: for higher resolution images
and more export options, consider using plotly.io.write_image. See
https://plot.ly/python/static-image-export/ for more details.
filename (default='plot') -- Sets the name of the file your image
will be saved to. The extension should not be included.
image_height (default=600) -- Specifies the height of the image in `px`.
image_width (default=800) -- Specifies the width of the image in `px`.
config (default=None) -- Plot view options dictionary. Keyword arguments
`show_link` and `link_text` set the associated options in this
dictionary if it doesn't contain them already.
auto_play (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.
animation_opts (default=None) -- Dict of custom animation parameters that
are used for the automatically started animation on page load. This
dict is 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.
Example:
```
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode()
iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}])
# We can also download an image of the plot by setting the image to the
format you want. e.g. `image='png'`
iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}], image='png')
```
animation_opts Example:
```
from plotly.offline import iplot
figure = {'data': [{'x': [0, 1], 'y': [0, 1]}],
'layout': {'xaxis': {'range': [0, 5], 'autorange': False},
'yaxis': {'range': [0, 5], 'autorange': False},
'title': 'Start Title'},
'frames': [{'data': [{'x': [1, 2], 'y': [1, 2]}]},
{'data': [{'x': [1, 4], 'y': [1, 4]}]},
{'data': [{'x': [3, 4], 'y': [3, 4]}],
'layout': {'title': 'End Title'}}]}
iplot(figure, animation_opts={'frame': {'duration': 1}})
```
"""
| /usr/src/app/target_test_cases/failed_tests_offline.iplot.txt | def iplot(
figure_or_data,
show_link=False,
link_text="Export to plot.ly",
validate=True,
image=None,
filename="plot_image",
image_width=800,
image_height=600,
config=None,
auto_play=True,
animation_opts=None,
):
"""
Draw plotly graphs inside an IPython or Jupyter notebook
figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or
dict or list that describes a Plotly graph.
See https://plot.ly/python/ for examples of
graph descriptions.
Keyword arguments:
show_link (default=False) -- display a link in the bottom-right corner of
of the chart that will export the chart to
Plotly Cloud or Plotly Enterprise
link_text (default='Export to plot.ly') -- the text of export link
validate (default=True) -- validate that all of the keys in the figure
are valid? omit if your version of plotly.js
has become outdated with your version of
graph_reference.json or if you need to include
extra, unnecessary keys in your figure.
image (default=None |'png' |'jpeg' |'svg' |'webp') -- This parameter sets
the format of the image to be downloaded, if we choose to download an
image. This parameter has a default value of None indicating that no
image should be downloaded. Please note: for higher resolution images
and more export options, consider using plotly.io.write_image. See
https://plot.ly/python/static-image-export/ for more details.
filename (default='plot') -- Sets the name of the file your image
will be saved to. The extension should not be included.
image_height (default=600) -- Specifies the height of the image in `px`.
image_width (default=800) -- Specifies the width of the image in `px`.
config (default=None) -- Plot view options dictionary. Keyword arguments
`show_link` and `link_text` set the associated options in this
dictionary if it doesn't contain them already.
auto_play (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.
animation_opts (default=None) -- Dict of custom animation parameters that
are used for the automatically started animation on page load. This
dict is 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.
Example:
```
from plotly.offline import init_notebook_mode, iplot
init_notebook_mode()
iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}])
# We can also download an image of the plot by setting the image to the
format you want. e.g. `image='png'`
iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}], image='png')
```
animation_opts Example:
```
from plotly.offline import iplot
figure = {'data': [{'x': [0, 1], 'y': [0, 1]}],
'layout': {'xaxis': {'range': [0, 5], 'autorange': False},
'yaxis': {'range': [0, 5], 'autorange': False},
'title': 'Start Title'},
'frames': [{'data': [{'x': [1, 2], 'y': [1, 2]}]},
{'data': [{'x': [1, 4], 'y': [1, 4]}]},
{'data': [{'x': [3, 4], 'y': [3, 4]}],
'layout': {'title': 'End Title'}}]}
iplot(figure, animation_opts={'frame': {'duration': 1}})
```
"""
import plotly.io as pio
ipython = get_module("IPython")
if not ipython:
raise ImportError("`iplot` can only run inside an IPython Notebook.")
config = dict(config) if config else {}
config.setdefault("showLink", show_link)
config.setdefault("linkText", link_text)
# Get figure
figure = tools.return_figure_from_figure_or_data(figure_or_data, validate)
# Handle image request
post_script = build_save_image_post_script(
image, filename, image_height, image_width, "iplot"
)
# Show figure
pio.show(
figure,
validate=validate,
config=config,
auto_play=auto_play,
post_script=post_script,
animation_opts=animation_opts,
)
| offline.iplot |
plotly.py | 71 | packages/python/plotly/plotly/offline/offline.py | def plot(
figure_or_data,
show_link=False,
link_text="Export to plot.ly",
validate=True,
output_type="file",
include_plotlyjs=True,
filename="temp-plot.html",
auto_open=True,
image=None,
image_filename="plot_image",
image_width=800,
image_height=600,
config=None,
include_mathjax=False,
auto_play=True,
animation_opts=None,
):
"""Create a plotly graph locally as an HTML document or string.
Example:
```
from plotly.offline import plot
import plotly.graph_objs as go
plot([go.Scatter(x=[1, 2, 3], y=[3, 2, 6])], filename='my-graph.html')
# We can also download an image of the plot by setting the image parameter
# to the image format we want
plot([go.Scatter(x=[1, 2, 3], y=[3, 2, 6])], filename='my-graph.html',
image='jpeg')
```
More examples below.
figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or
dict or list that describes a Plotly graph.
See https://plot.ly/python/ for examples of
graph descriptions.
Keyword arguments:
show_link (default=False) -- display a link in the bottom-right corner of
of the chart that will export the chart to Plotly Cloud or
Plotly Enterprise
link_text (default='Export to plot.ly') -- the text of export link
validate (default=True) -- validate that all of the keys in the figure
are valid? omit if your version of plotly.js has become outdated
with your version of graph_reference.json or if you need to include
extra, unnecessary keys in your figure.
output_type ('file' | 'div' - default 'file') -- if 'file', then
the graph is saved as a standalone HTML file and `plot`
returns None.
If 'div', then `plot` returns a string that just contains the
HTML <div> that contains the graph and the script to generate the
graph.
Use 'file' if you want to save and view a single graph at a time
in a standalone HTML file.
Use 'div' if you are embedding these graphs in an HTML file with
other graphs or HTML markup, like a HTML report or an website.
include_plotlyjs (True | False | 'cdn' | 'directory' | path - default=True)
Specifies how the plotly.js library is included in the output html
file or 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 output_type='file' 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 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.
If False, no script tag referencing plotly.js is included. This is
useful when output_type='div' and the resulting div string will be
placed inside an HTML document that already loads plotly.js. This
option is not advised when output_type='file' as it will result in
a non-functional html file.
filename (default='temp-plot.html') -- The local filename to save the
outputted chart to. If the filename already exists, it will be
overwritten. This argument only applies if `output_type` is 'file'.
auto_open (default=True) -- If True, open the saved file in a
web browser after saving.
This argument only applies if `output_type` is 'file'.
image (default=None |'png' |'jpeg' |'svg' |'webp') -- This parameter sets
the format of the image to be downloaded, if we choose to download an
image. This parameter has a default value of None indicating that no
image should be downloaded. Please note: for higher resolution images
and more export options, consider making requests to our image servers.
Type: `help(py.image)` for more details.
image_filename (default='plot_image') -- Sets the name of the file your
image will be saved to. The extension should not be included.
image_height (default=600) -- Specifies the height of the image in `px`.
image_width (default=800) -- Specifies the width of the image in `px`.
config (default=None) -- Plot view options dictionary. Keyword arguments
`show_link` and `link_text` set the associated options in this
dictionary if it doesn't contain them already.
include_mathjax (False | 'cdn' | path - default=False) --
Specifies how the MathJax.js library is included in the output html
file or 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. HTML files generated with this option will not be able to
display LaTeX typesetting.
If 'cdn', a script tag that references a MathJax CDN location will be
included in the output. HTML files generated with this option will be
able to display LaTeX typesetting as long as they have internet access.
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.
auto_play (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.
animation_opts (default=None) -- Dict of custom animation parameters that
are used for the automatically started animation on page load. This
dict is 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.
Example:
```
from plotly.offline import plot
figure = {'data': [{'x': [0, 1], 'y': [0, 1]}],
'layout': {'xaxis': {'range': [0, 5], 'autorange': False},
'yaxis': {'range': [0, 5], 'autorange': False},
'title': 'Start Title'},
'frames': [{'data': [{'x': [1, 2], 'y': [1, 2]}]},
{'data': [{'x': [1, 4], 'y': [1, 4]}]},
{'data': [{'x': [3, 4], 'y': [3, 4]}],
'layout': {'title': 'End Title'}}]}
plot(figure, animation_opts={'frame': {'duration': 1}})
```
"""
| /usr/src/app/target_test_cases/failed_tests_offline.plot.txt | def plot(
figure_or_data,
show_link=False,
link_text="Export to plot.ly",
validate=True,
output_type="file",
include_plotlyjs=True,
filename="temp-plot.html",
auto_open=True,
image=None,
image_filename="plot_image",
image_width=800,
image_height=600,
config=None,
include_mathjax=False,
auto_play=True,
animation_opts=None,
):
"""Create a plotly graph locally as an HTML document or string.
Example:
```
from plotly.offline import plot
import plotly.graph_objs as go
plot([go.Scatter(x=[1, 2, 3], y=[3, 2, 6])], filename='my-graph.html')
# We can also download an image of the plot by setting the image parameter
# to the image format we want
plot([go.Scatter(x=[1, 2, 3], y=[3, 2, 6])], filename='my-graph.html',
image='jpeg')
```
More examples below.
figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or
dict or list that describes a Plotly graph.
See https://plot.ly/python/ for examples of
graph descriptions.
Keyword arguments:
show_link (default=False) -- display a link in the bottom-right corner of
of the chart that will export the chart to Plotly Cloud or
Plotly Enterprise
link_text (default='Export to plot.ly') -- the text of export link
validate (default=True) -- validate that all of the keys in the figure
are valid? omit if your version of plotly.js has become outdated
with your version of graph_reference.json or if you need to include
extra, unnecessary keys in your figure.
output_type ('file' | 'div' - default 'file') -- if 'file', then
the graph is saved as a standalone HTML file and `plot`
returns None.
If 'div', then `plot` returns a string that just contains the
HTML <div> that contains the graph and the script to generate the
graph.
Use 'file' if you want to save and view a single graph at a time
in a standalone HTML file.
Use 'div' if you are embedding these graphs in an HTML file with
other graphs or HTML markup, like a HTML report or an website.
include_plotlyjs (True | False | 'cdn' | 'directory' | path - default=True)
Specifies how the plotly.js library is included in the output html
file or 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 output_type='file' 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 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.
If False, no script tag referencing plotly.js is included. This is
useful when output_type='div' and the resulting div string will be
placed inside an HTML document that already loads plotly.js. This
option is not advised when output_type='file' as it will result in
a non-functional html file.
filename (default='temp-plot.html') -- The local filename to save the
outputted chart to. If the filename already exists, it will be
overwritten. This argument only applies if `output_type` is 'file'.
auto_open (default=True) -- If True, open the saved file in a
web browser after saving.
This argument only applies if `output_type` is 'file'.
image (default=None |'png' |'jpeg' |'svg' |'webp') -- This parameter sets
the format of the image to be downloaded, if we choose to download an
image. This parameter has a default value of None indicating that no
image should be downloaded. Please note: for higher resolution images
and more export options, consider making requests to our image servers.
Type: `help(py.image)` for more details.
image_filename (default='plot_image') -- Sets the name of the file your
image will be saved to. The extension should not be included.
image_height (default=600) -- Specifies the height of the image in `px`.
image_width (default=800) -- Specifies the width of the image in `px`.
config (default=None) -- Plot view options dictionary. Keyword arguments
`show_link` and `link_text` set the associated options in this
dictionary if it doesn't contain them already.
include_mathjax (False | 'cdn' | path - default=False) --
Specifies how the MathJax.js library is included in the output html
file or 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. HTML files generated with this option will not be able to
display LaTeX typesetting.
If 'cdn', a script tag that references a MathJax CDN location will be
included in the output. HTML files generated with this option will be
able to display LaTeX typesetting as long as they have internet access.
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.
auto_play (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.
animation_opts (default=None) -- Dict of custom animation parameters that
are used for the automatically started animation on page load. This
dict is 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.
Example:
```
from plotly.offline import plot
figure = {'data': [{'x': [0, 1], 'y': [0, 1]}],
'layout': {'xaxis': {'range': [0, 5], 'autorange': False},
'yaxis': {'range': [0, 5], 'autorange': False},
'title': 'Start Title'},
'frames': [{'data': [{'x': [1, 2], 'y': [1, 2]}]},
{'data': [{'x': [1, 4], 'y': [1, 4]}]},
{'data': [{'x': [3, 4], 'y': [3, 4]}],
'layout': {'title': 'End Title'}}]}
plot(figure, animation_opts={'frame': {'duration': 1}})
```
"""
import plotly.io as pio
# Output type
if output_type not in ["div", "file"]:
raise ValueError(
"`output_type` argument must be 'div' or 'file'. "
"You supplied `" + output_type + "``"
)
if not filename.endswith(".html") and output_type == "file":
warnings.warn(
"Your filename `" + filename + "` didn't end with .html. "
"Adding .html to the end of your file."
)
filename += ".html"
# Config
config = dict(config) if config else {}
config.setdefault("showLink", show_link)
config.setdefault("linkText", link_text)
figure = tools.return_figure_from_figure_or_data(figure_or_data, validate)
width = figure.get("layout", {}).get("width", "100%")
height = figure.get("layout", {}).get("height", "100%")
if width == "100%" or height == "100%":
config.setdefault("responsive", True)
# Handle image request
post_script = build_save_image_post_script(
image, image_filename, image_height, image_width, "plot"
)
if output_type == "file":
pio.write_html(
figure,
filename,
config=config,
auto_play=auto_play,
include_plotlyjs=include_plotlyjs,
include_mathjax=include_mathjax,
post_script=post_script,
full_html=True,
validate=validate,
animation_opts=animation_opts,
auto_open=auto_open,
)
return filename
else:
return pio.to_html(
figure,
config=config,
auto_play=auto_play,
include_plotlyjs=include_plotlyjs,
include_mathjax=include_mathjax,
post_script=post_script,
full_html=False,
validate=validate,
animation_opts=animation_opts,
)
| offline.plot |
plotly.py | 72 | packages/python/plotly/_plotly_utils/png.py | def __init__(
self,
width=None,
height=None,
size=None,
greyscale=Default,
alpha=False,
bitdepth=8,
palette=None,
transparent=None,
background=None,
gamma=None,
compression=None,
interlace=False,
planes=None,
colormap=None,
maxval=None,
chunk_limit=2**20,
x_pixels_per_unit=None,
y_pixels_per_unit=None,
unit_is_meter=False,
):
"""
Create a PNG encoder object.
Arguments:
width, height
Image size in pixels, as two separate arguments.
size
Image size (w,h) in pixels, as single argument.
greyscale
Pixels are greyscale, not RGB.
alpha
Input data has alpha channel (RGBA or LA).
bitdepth
Bit depth: from 1 to 16 (for each channel).
palette
Create a palette for a colour mapped image (colour type 3).
transparent
Specify a transparent colour (create a ``tRNS`` chunk).
background
Specify a default background colour (create a ``bKGD`` chunk).
gamma
Specify a gamma value (create a ``gAMA`` chunk).
compression
zlib compression level: 0 (none) to 9 (more compressed);
default: -1 or None.
interlace
Create an interlaced image.
chunk_limit
Write multiple ``IDAT`` chunks to save memory.
x_pixels_per_unit
Number of pixels a unit along the x axis (write a
`pHYs` chunk).
y_pixels_per_unit
Number of pixels a unit along the y axis (write a
`pHYs` chunk). Along with `x_pixel_unit`, this gives
the pixel size ratio.
unit_is_meter
`True` to indicate that the unit (for the `pHYs`
chunk) is metre.
The image size (in pixels) can be specified either by using the
`width` and `height` arguments, or with the single `size`
argument.
If `size` is used it should be a pair (*width*, *height*).
The `greyscale` argument indicates whether input pixels
are greyscale (when true), or colour (when false).
The default is true unless `palette=` is used.
The `alpha` argument (a boolean) specifies
whether input pixels have an alpha channel (or not).
`bitdepth` specifies the bit depth of the source pixel values.
Each channel may have a different bit depth.
Each source pixel must have values that are
an integer between 0 and ``2**bitdepth-1``, where
`bitdepth` is the bit depth for the corresponding channel.
For example, 8-bit images have values between 0 and 255.
PNG only stores images with bit depths of
1,2,4,8, or 16 (the same for all channels).
When `bitdepth` is not one of these values or where
channels have different bit depths,
the next highest valid bit depth is selected,
and an ``sBIT`` (significant bits) chunk is generated
that specifies the original precision of the source image.
In this case the supplied pixel values will be rescaled to
fit the range of the selected bit depth.
The PNG file format supports many bit depth / colour model
combinations, but not all.
The details are somewhat arcane
(refer to the PNG specification for full details).
Briefly:
Bit depths < 8 (1,2,4) are only allowed with greyscale and
colour mapped images;
colour mapped images cannot have bit depth 16.
For colour mapped images
(in other words, when the `palette` argument is specified)
the `bitdepth` argument must match one of
the valid PNG bit depths: 1, 2, 4, or 8.
(It is valid to have a PNG image with a palette and
an ``sBIT`` chunk, but the meaning is slightly different;
it would be awkward to use the `bitdepth` argument for this.)
The `palette` option, when specified,
causes a colour mapped image to be created:
the PNG colour type is set to 3;
`greyscale` must not be true; `alpha` must not be true;
`transparent` must not be set.
The bit depth must be 1,2,4, or 8.
When a colour mapped image is created,
the pixel values are palette indexes and
the `bitdepth` argument specifies the size of these indexes
(not the size of the colour values in the palette).
The palette argument value should be a sequence of 3- or
4-tuples.
3-tuples specify RGB palette entries;
4-tuples specify RGBA palette entries.
All the 4-tuples (if present) must come before all the 3-tuples.
A ``PLTE`` chunk is created;
if there are 4-tuples then a ``tRNS`` chunk is created as well.
The ``PLTE`` chunk will contain all the RGB triples in the same
sequence;
the ``tRNS`` chunk will contain the alpha channel for
all the 4-tuples, in the same sequence.
Palette entries are always 8-bit.
If specified, the `transparent` and `background` parameters must be
a tuple with one element for each channel in the image.
Either a 3-tuple of integer (RGB) values for a colour image, or
a 1-tuple of a single integer for a greyscale image.
If specified, the `gamma` parameter must be a positive number
(generally, a `float`).
A ``gAMA`` chunk will be created.
Note that this will not change the values of the pixels as
they appear in the PNG file,
they are assumed to have already
been converted appropriately for the gamma specified.
The `compression` argument specifies the compression level to
be used by the ``zlib`` module.
Values from 1 to 9 (highest) specify compression.
0 means no compression.
-1 and ``None`` both mean that the ``zlib`` module uses
the default level of compession (which is generally acceptable).
If `interlace` is true then an interlaced image is created
(using PNG's so far only interace method, *Adam7*).
This does not affect how the pixels should be passed in,
rather it changes how they are arranged into the PNG file.
On slow connexions interlaced images can be
partially decoded by the browser to give
a rough view of the image that is
successively refined as more image data appears.
.. note ::
Enabling the `interlace` option requires the entire image
to be processed in working memory.
`chunk_limit` is used to limit the amount of memory used whilst
compressing the image.
In order to avoid using large amounts of memory,
multiple ``IDAT`` chunks may be created.
"""
| /usr/src/app/target_test_cases/failed_tests_png.Writer.__init__.txt | def __init__(
self,
width=None,
height=None,
size=None,
greyscale=Default,
alpha=False,
bitdepth=8,
palette=None,
transparent=None,
background=None,
gamma=None,
compression=None,
interlace=False,
planes=None,
colormap=None,
maxval=None,
chunk_limit=2**20,
x_pixels_per_unit=None,
y_pixels_per_unit=None,
unit_is_meter=False,
):
"""
Create a PNG encoder object.
Arguments:
width, height
Image size in pixels, as two separate arguments.
size
Image size (w,h) in pixels, as single argument.
greyscale
Pixels are greyscale, not RGB.
alpha
Input data has alpha channel (RGBA or LA).
bitdepth
Bit depth: from 1 to 16 (for each channel).
palette
Create a palette for a colour mapped image (colour type 3).
transparent
Specify a transparent colour (create a ``tRNS`` chunk).
background
Specify a default background colour (create a ``bKGD`` chunk).
gamma
Specify a gamma value (create a ``gAMA`` chunk).
compression
zlib compression level: 0 (none) to 9 (more compressed);
default: -1 or None.
interlace
Create an interlaced image.
chunk_limit
Write multiple ``IDAT`` chunks to save memory.
x_pixels_per_unit
Number of pixels a unit along the x axis (write a
`pHYs` chunk).
y_pixels_per_unit
Number of pixels a unit along the y axis (write a
`pHYs` chunk). Along with `x_pixel_unit`, this gives
the pixel size ratio.
unit_is_meter
`True` to indicate that the unit (for the `pHYs`
chunk) is metre.
The image size (in pixels) can be specified either by using the
`width` and `height` arguments, or with the single `size`
argument.
If `size` is used it should be a pair (*width*, *height*).
The `greyscale` argument indicates whether input pixels
are greyscale (when true), or colour (when false).
The default is true unless `palette=` is used.
The `alpha` argument (a boolean) specifies
whether input pixels have an alpha channel (or not).
`bitdepth` specifies the bit depth of the source pixel values.
Each channel may have a different bit depth.
Each source pixel must have values that are
an integer between 0 and ``2**bitdepth-1``, where
`bitdepth` is the bit depth for the corresponding channel.
For example, 8-bit images have values between 0 and 255.
PNG only stores images with bit depths of
1,2,4,8, or 16 (the same for all channels).
When `bitdepth` is not one of these values or where
channels have different bit depths,
the next highest valid bit depth is selected,
and an ``sBIT`` (significant bits) chunk is generated
that specifies the original precision of the source image.
In this case the supplied pixel values will be rescaled to
fit the range of the selected bit depth.
The PNG file format supports many bit depth / colour model
combinations, but not all.
The details are somewhat arcane
(refer to the PNG specification for full details).
Briefly:
Bit depths < 8 (1,2,4) are only allowed with greyscale and
colour mapped images;
colour mapped images cannot have bit depth 16.
For colour mapped images
(in other words, when the `palette` argument is specified)
the `bitdepth` argument must match one of
the valid PNG bit depths: 1, 2, 4, or 8.
(It is valid to have a PNG image with a palette and
an ``sBIT`` chunk, but the meaning is slightly different;
it would be awkward to use the `bitdepth` argument for this.)
The `palette` option, when specified,
causes a colour mapped image to be created:
the PNG colour type is set to 3;
`greyscale` must not be true; `alpha` must not be true;
`transparent` must not be set.
The bit depth must be 1,2,4, or 8.
When a colour mapped image is created,
the pixel values are palette indexes and
the `bitdepth` argument specifies the size of these indexes
(not the size of the colour values in the palette).
The palette argument value should be a sequence of 3- or
4-tuples.
3-tuples specify RGB palette entries;
4-tuples specify RGBA palette entries.
All the 4-tuples (if present) must come before all the 3-tuples.
A ``PLTE`` chunk is created;
if there are 4-tuples then a ``tRNS`` chunk is created as well.
The ``PLTE`` chunk will contain all the RGB triples in the same
sequence;
the ``tRNS`` chunk will contain the alpha channel for
all the 4-tuples, in the same sequence.
Palette entries are always 8-bit.
If specified, the `transparent` and `background` parameters must be
a tuple with one element for each channel in the image.
Either a 3-tuple of integer (RGB) values for a colour image, or
a 1-tuple of a single integer for a greyscale image.
If specified, the `gamma` parameter must be a positive number
(generally, a `float`).
A ``gAMA`` chunk will be created.
Note that this will not change the values of the pixels as
they appear in the PNG file,
they are assumed to have already
been converted appropriately for the gamma specified.
The `compression` argument specifies the compression level to
be used by the ``zlib`` module.
Values from 1 to 9 (highest) specify compression.
0 means no compression.
-1 and ``None`` both mean that the ``zlib`` module uses
the default level of compession (which is generally acceptable).
If `interlace` is true then an interlaced image is created
(using PNG's so far only interace method, *Adam7*).
This does not affect how the pixels should be passed in,
rather it changes how they are arranged into the PNG file.
On slow connexions interlaced images can be
partially decoded by the browser to give
a rough view of the image that is
successively refined as more image data appears.
.. note ::
Enabling the `interlace` option requires the entire image
to be processed in working memory.
`chunk_limit` is used to limit the amount of memory used whilst
compressing the image.
In order to avoid using large amounts of memory,
multiple ``IDAT`` chunks may be created.
"""
# At the moment the `planes` argument is ignored;
# its purpose is to act as a dummy so that
# ``Writer(x, y, **info)`` works, where `info` is a dictionary
# returned by Reader.read and friends.
# Ditto for `colormap`.
width, height = check_sizes(size, width, height)
del size
if not is_natural(width) or not is_natural(height):
raise ProtocolError("width and height must be integers")
if width <= 0 or height <= 0:
raise ProtocolError("width and height must be greater than zero")
# http://www.w3.org/TR/PNG/#7Integers-and-byte-order
if width > 2**31 - 1 or height > 2**31 - 1:
raise ProtocolError("width and height cannot exceed 2**31-1")
if alpha and transparent is not None:
raise ProtocolError("transparent colour not allowed with alpha channel")
# bitdepth is either single integer, or tuple of integers.
# Convert to tuple.
try:
len(bitdepth)
except TypeError:
bitdepth = (bitdepth,)
for b in bitdepth:
valid = is_natural(b) and 1 <= b <= 16
if not valid:
raise ProtocolError(
"each bitdepth %r must be a positive integer <= 16" % (bitdepth,)
)
# Calculate channels, and
# expand bitdepth to be one element per channel.
palette = check_palette(palette)
alpha = bool(alpha)
colormap = bool(palette)
if greyscale is Default and palette:
greyscale = False
greyscale = bool(greyscale)
if colormap:
color_planes = 1
planes = 1
else:
color_planes = (3, 1)[greyscale]
planes = color_planes + alpha
if len(bitdepth) == 1:
bitdepth *= planes
bitdepth, self.rescale = check_bitdepth_rescale(
palette, bitdepth, transparent, alpha, greyscale
)
# These are assertions, because above logic should have
# corrected or raised all problematic cases.
if bitdepth < 8:
assert greyscale or palette
assert not alpha
if bitdepth > 8:
assert not palette
transparent = check_color(transparent, greyscale, "transparent")
background = check_color(background, greyscale, "background")
# It's important that the true boolean values
# (greyscale, alpha, colormap, interlace) are converted
# to bool because Iverson's convention is relied upon later on.
self.width = width
self.height = height
self.transparent = transparent
self.background = background
self.gamma = gamma
self.greyscale = greyscale
self.alpha = alpha
self.colormap = colormap
self.bitdepth = int(bitdepth)
self.compression = compression
self.chunk_limit = chunk_limit
self.interlace = bool(interlace)
self.palette = palette
self.x_pixels_per_unit = x_pixels_per_unit
self.y_pixels_per_unit = y_pixels_per_unit
self.unit_is_meter = bool(unit_is_meter)
self.color_type = 4 * self.alpha + 2 * (not greyscale) + 1 * self.colormap
assert self.color_type in (0, 2, 3, 4, 6)
self.color_planes = color_planes
self.planes = planes
# :todo: fix for bitdepth < 8
self.psize = (self.bitdepth / 8) * self.planes
| png.Writer.__init__ |
plotly.py | 73 | packages/python/plotly/_plotly_utils/png.py | def from_array(a, mode=None, info={}):
"""
Create a PNG :class:`Image` object from a 2-dimensional array.
One application of this function is easy PIL-style saving:
``png.from_array(pixels, 'L').save('foo.png')``.
Unless they are specified using the *info* parameter,
the PNG's height and width are taken from the array size.
The first axis is the height; the second axis is the
ravelled width and channel index.
The array is treated is a sequence of rows,
each row being a sequence of values (``width*channels`` in number).
So an RGB image that is 16 pixels high and 8 wide will
occupy a 2-dimensional array that is 16x24
(each row will be 8*3 = 24 sample values).
*mode* is a string that specifies the image colour format in a
PIL-style mode. It can be:
``'L'``
greyscale (1 channel)
``'LA'``
greyscale with alpha (2 channel)
``'RGB'``
colour image (3 channel)
``'RGBA'``
colour image with alpha (4 channel)
The mode string can also specify the bit depth
(overriding how this function normally derives the bit depth,
see below).
Appending ``';16'`` to the mode will cause the PNG to be
16 bits per channel;
any decimal from 1 to 16 can be used to specify the bit depth.
When a 2-dimensional array is used *mode* determines how many
channels the image has, and so allows the width to be derived from
the second array dimension.
The array is expected to be a ``numpy`` array,
but it can be any suitable Python sequence.
For example, a list of lists can be used:
``png.from_array([[0, 255, 0], [255, 0, 255]], 'L')``.
The exact rules are: ``len(a)`` gives the first dimension, height;
``len(a[0])`` gives the second dimension.
It's slightly more complicated than that because
an iterator of rows can be used, and it all still works.
Using an iterator allows data to be streamed efficiently.
The bit depth of the PNG is normally taken from
the array element's datatype
(but if *mode* specifies a bitdepth then that is used instead).
The array element's datatype is determined in a way which
is supposed to work both for ``numpy`` arrays and for Python
``array.array`` objects.
A 1 byte datatype will give a bit depth of 8,
a 2 byte datatype will give a bit depth of 16.
If the datatype does not have an implicit size,
like the above example where it is a plain Python list of lists,
then a default of 8 is used.
The *info* parameter is a dictionary that can
be used to specify metadata (in the same style as
the arguments to the :class:`png.Writer` class).
For this function the keys that are useful are:
height
overrides the height derived from the array dimensions and
allows *a* to be an iterable.
width
overrides the width derived from the array dimensions.
bitdepth
overrides the bit depth derived from the element datatype
(but must match *mode* if that also specifies a bit depth).
Generally anything specified in the *info* dictionary will
override any implicit choices that this function would otherwise make,
but must match any explicit ones.
For example, if the *info* dictionary has a ``greyscale`` key then
this must be true when mode is ``'L'`` or ``'LA'`` and
false when mode is ``'RGB'`` or ``'RGBA'``.
"""
| /usr/src/app/target_test_cases/failed_tests_png.from_array.txt | def from_array(a, mode=None, info={}):
"""
Create a PNG :class:`Image` object from a 2-dimensional array.
One application of this function is easy PIL-style saving:
``png.from_array(pixels, 'L').save('foo.png')``.
Unless they are specified using the *info* parameter,
the PNG's height and width are taken from the array size.
The first axis is the height; the second axis is the
ravelled width and channel index.
The array is treated is a sequence of rows,
each row being a sequence of values (``width*channels`` in number).
So an RGB image that is 16 pixels high and 8 wide will
occupy a 2-dimensional array that is 16x24
(each row will be 8*3 = 24 sample values).
*mode* is a string that specifies the image colour format in a
PIL-style mode. It can be:
``'L'``
greyscale (1 channel)
``'LA'``
greyscale with alpha (2 channel)
``'RGB'``
colour image (3 channel)
``'RGBA'``
colour image with alpha (4 channel)
The mode string can also specify the bit depth
(overriding how this function normally derives the bit depth,
see below).
Appending ``';16'`` to the mode will cause the PNG to be
16 bits per channel;
any decimal from 1 to 16 can be used to specify the bit depth.
When a 2-dimensional array is used *mode* determines how many
channels the image has, and so allows the width to be derived from
the second array dimension.
The array is expected to be a ``numpy`` array,
but it can be any suitable Python sequence.
For example, a list of lists can be used:
``png.from_array([[0, 255, 0], [255, 0, 255]], 'L')``.
The exact rules are: ``len(a)`` gives the first dimension, height;
``len(a[0])`` gives the second dimension.
It's slightly more complicated than that because
an iterator of rows can be used, and it all still works.
Using an iterator allows data to be streamed efficiently.
The bit depth of the PNG is normally taken from
the array element's datatype
(but if *mode* specifies a bitdepth then that is used instead).
The array element's datatype is determined in a way which
is supposed to work both for ``numpy`` arrays and for Python
``array.array`` objects.
A 1 byte datatype will give a bit depth of 8,
a 2 byte datatype will give a bit depth of 16.
If the datatype does not have an implicit size,
like the above example where it is a plain Python list of lists,
then a default of 8 is used.
The *info* parameter is a dictionary that can
be used to specify metadata (in the same style as
the arguments to the :class:`png.Writer` class).
For this function the keys that are useful are:
height
overrides the height derived from the array dimensions and
allows *a* to be an iterable.
width
overrides the width derived from the array dimensions.
bitdepth
overrides the bit depth derived from the element datatype
(but must match *mode* if that also specifies a bit depth).
Generally anything specified in the *info* dictionary will
override any implicit choices that this function would otherwise make,
but must match any explicit ones.
For example, if the *info* dictionary has a ``greyscale`` key then
this must be true when mode is ``'L'`` or ``'LA'`` and
false when mode is ``'RGB'`` or ``'RGBA'``.
"""
# We abuse the *info* parameter by modifying it. Take a copy here.
# (Also typechecks *info* to some extent).
info = dict(info)
# Syntax check mode string.
match = RegexModeDecode.match(mode)
if not match:
raise Error("mode string should be 'RGB' or 'L;16' or similar.")
mode, bitdepth = match.groups()
if bitdepth:
bitdepth = int(bitdepth)
# Colour format.
if "greyscale" in info:
if bool(info["greyscale"]) != ("L" in mode):
raise ProtocolError("info['greyscale'] should match mode.")
info["greyscale"] = "L" in mode
alpha = "A" in mode
if "alpha" in info:
if bool(info["alpha"]) != alpha:
raise ProtocolError("info['alpha'] should match mode.")
info["alpha"] = alpha
# Get bitdepth from *mode* if possible.
if bitdepth:
if info.get("bitdepth") and bitdepth != info["bitdepth"]:
raise ProtocolError(
"bitdepth (%d) should match bitdepth of info (%d)."
% (bitdepth, info["bitdepth"])
)
info["bitdepth"] = bitdepth
# Fill in and/or check entries in *info*.
# Dimensions.
width, height = check_sizes(info.get("size"), info.get("width"), info.get("height"))
if width:
info["width"] = width
if height:
info["height"] = height
if "height" not in info:
try:
info["height"] = len(a)
except TypeError:
raise ProtocolError("len(a) does not work, supply info['height'] instead.")
planes = len(mode)
if "planes" in info:
if info["planes"] != planes:
raise Error("info['planes'] should match mode.")
# In order to work out whether we the array is 2D or 3D we need its
# first row, which requires that we take a copy of its iterator.
# We may also need the first row to derive width and bitdepth.
a, t = itertools.tee(a)
row = next(t)
del t
testelement = row
if "width" not in info:
width = len(row) // planes
info["width"] = width
if "bitdepth" not in info:
try:
dtype = testelement.dtype
# goto the "else:" clause. Sorry.
except AttributeError:
try:
# Try a Python array.array.
bitdepth = 8 * testelement.itemsize
except AttributeError:
# We can't determine it from the array element's datatype,
# use a default of 8.
bitdepth = 8
else:
# If we got here without exception,
# we now assume that the array is a numpy array.
if dtype.kind == "b":
bitdepth = 1
else:
bitdepth = 8 * dtype.itemsize
info["bitdepth"] = bitdepth
for thing in ["width", "height", "bitdepth", "greyscale", "alpha"]:
assert thing in info
return Image(a, info)
| png.from_array |
plotly.py | 74 | packages/python/plotly/plotly/subplots.py | def make_subplots(
rows=1,
cols=1,
shared_xaxes=False,
shared_yaxes=False,
start_cell="top-left",
print_grid=False,
horizontal_spacing=None,
vertical_spacing=None,
subplot_titles=None,
column_widths=None,
row_heights=None,
specs=None,
insets=None,
column_titles=None,
row_titles=None,
x_title=None,
y_title=None,
figure=None,
**kwargs,
) -> go.Figure:
"""
Return an instance of plotly.graph_objs.Figure with predefined subplots
configured in 'layout'.
Parameters
----------
rows: int (default 1)
Number of rows in the subplot grid. Must be greater than zero.
cols: int (default 1)
Number of columns in the subplot grid. Must be greater than zero.
shared_xaxes: boolean or str (default False)
Assign shared (linked) x-axes for 2D cartesian subplots
- True or 'columns': Share axes among subplots in the same column
- 'rows': Share axes among subplots in the same row
- 'all': Share axes across all subplots in the grid.
shared_yaxes: boolean or str (default False)
Assign shared (linked) y-axes for 2D cartesian subplots
- 'columns': Share axes among subplots in the same column
- True or 'rows': Share axes among subplots in the same row
- 'all': Share axes across all subplots in the grid.
start_cell: 'bottom-left' or 'top-left' (default 'top-left')
Choose the starting cell in the subplot grid used to set the
domains_grid of the subplots.
- 'top-left': Subplots are numbered with (1, 1) in the top
left corner
- 'bottom-left': Subplots are numbererd with (1, 1) in the bottom
left corner
print_grid: boolean (default True):
If True, prints a string representation of the plot grid. Grid may
also be printed using the `Figure.print_grid()` method on the
resulting figure.
horizontal_spacing: float (default 0.2 / cols)
Space between subplot columns in normalized plot coordinates. Must be
a float between 0 and 1.
Applies to all columns (use 'specs' subplot-dependents spacing)
vertical_spacing: float (default 0.3 / rows)
Space between subplot rows in normalized plot coordinates. Must be
a float between 0 and 1.
Applies to all rows (use 'specs' subplot-dependents spacing)
subplot_titles: list of str or None (default None)
Title of each subplot as a list in row-major ordering.
Empty strings ("") can be included in the list if no subplot title
is desired in that space so that the titles are properly indexed.
specs: list of lists of dict or None (default None)
Per subplot specifications of subplot type, row/column spanning, and
spacing.
ex1: specs=[[{}, {}], [{'colspan': 2}, None]]
ex2: specs=[[{'rowspan': 2}, {}], [None, {}]]
- Indices of the outer list correspond to subplot grid rows
starting from the top, if start_cell='top-left',
or bottom, if start_cell='bottom-left'.
The number of rows in 'specs' must be equal to 'rows'.
- Indices of the inner lists correspond to subplot grid columns
starting from the left. The number of columns in 'specs'
must be equal to 'cols'.
- Each item in the 'specs' list corresponds to one subplot
in a subplot grid. (N.B. The subplot grid has exactly 'rows'
times 'cols' cells.)
- Use None for a blank a subplot cell (or to move past a col/row span).
- Note that specs[0][0] has the specs of the 'start_cell' subplot.
- Each item in 'specs' is a dictionary.
The available keys are:
* type (string, default 'xy'): Subplot type. One of
- 'xy': 2D Cartesian subplot type for scatter, bar, etc.
- 'scene': 3D Cartesian subplot for scatter3d, cone, etc.
- 'polar': Polar subplot for scatterpolar, barpolar, etc.
- 'ternary': Ternary subplot for scatterternary
- 'map': Map subplot for scattermap
- 'mapbox': Mapbox subplot for scattermapbox
- 'domain': Subplot type for traces that are individually
positioned. pie, parcoords, parcats, etc.
- trace type: A trace type which will be used to determine
the appropriate subplot type for that trace
* secondary_y (bool, default False): If True, create a secondary
y-axis positioned on the right side of the subplot. Only valid
if type='xy'.
* colspan (int, default 1): number of subplot columns
for this subplot to span.
* rowspan (int, default 1): number of subplot rows
for this subplot to span.
* l (float, default 0.0): padding left of cell
* r (float, default 0.0): padding right of cell
* t (float, default 0.0): padding right of cell
* b (float, default 0.0): padding bottom of cell
- Note: Use 'horizontal_spacing' and 'vertical_spacing' to adjust
the spacing in between the subplots.
insets: list of dict or None (default None):
Inset specifications. Insets are subplots that overlay grid subplots
- Each item in 'insets' is a dictionary.
The available keys are:
* cell (tuple, default=(1,1)): (row, col) index of the
subplot cell to overlay inset axes onto.
* type (string, default 'xy'): Subplot type
* l (float, default=0.0): padding left of inset
in fraction of cell width
* w (float or 'to_end', default='to_end') inset width
in fraction of cell width ('to_end': to cell right edge)
* b (float, default=0.0): padding bottom of inset
in fraction of cell height
* h (float or 'to_end', default='to_end') inset height
in fraction of cell height ('to_end': to cell top edge)
column_widths: list of numbers or None (default None)
list of length `cols` of the relative widths of each column of subplots.
Values are normalized internally and used to distribute overall width
of the figure (excluding padding) among the columns.
For backward compatibility, may also be specified using the
`column_width` keyword argument.
row_heights: list of numbers or None (default None)
list of length `rows` of the relative heights of each row of subplots.
If start_cell='top-left' then row heights are applied top to bottom.
Otherwise, if start_cell='bottom-left' then row heights are applied
bottom to top.
For backward compatibility, may also be specified using the
`row_width` kwarg. If specified as `row_width`, then the width values
are applied from bottom to top regardless of the value of start_cell.
This matches the legacy behavior of the `row_width` argument.
column_titles: list of str or None (default None)
list of length `cols` of titles to place above the top subplot in
each column.
row_titles: list of str or None (default None)
list of length `rows` of titles to place on the right side of each
row of subplots. If start_cell='top-left' then row titles are
applied top to bottom. Otherwise, if start_cell='bottom-left' then
row titles are applied bottom to top.
x_title: str or None (default None)
Title to place below the bottom row of subplots,
centered horizontally
y_title: str or None (default None)
Title to place to the left of the left column of subplots,
centered vertically
figure: go.Figure or None (default None)
If None, a new go.Figure instance will be created and its axes will be
populated with those corresponding to the requested subplot geometry and
this new figure will be returned.
If a go.Figure instance, the axes will be added to the
layout of this figure and this figure will be returned. If the figure
already contains axes, they will be overwritten.
Examples
--------
Example 1:
>>> # Stack two subplots vertically, and add a scatter trace to each
>>> from plotly.subplots import make_subplots
>>> import plotly.graph_objects as go
>>> fig = make_subplots(rows=2)
This is the format of your plot grid:
[ (1,1) xaxis1,yaxis1 ]
[ (2,1) xaxis2,yaxis2 ]
>>> fig.add_scatter(y=[2, 1, 3], row=1, col=1) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_scatter(y=[1, 3, 2], row=2, col=1) # doctest: +ELLIPSIS
Figure(...)
or see Figure.append_trace
Example 2:
>>> # Stack a scatter plot
>>> fig = make_subplots(rows=2, shared_xaxes=True)
This is the format of your plot grid:
[ (1,1) xaxis1,yaxis1 ]
[ (2,1) xaxis2,yaxis2 ]
>>> fig.add_scatter(y=[2, 1, 3], row=1, col=1) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_scatter(y=[1, 3, 2], row=2, col=1) # doctest: +ELLIPSIS
Figure(...)
Example 3:
>>> # irregular subplot layout (more examples below under 'specs')
>>> fig = make_subplots(rows=2, cols=2,
... specs=[[{}, {}],
... [{'colspan': 2}, None]])
This is the format of your plot grid:
[ (1,1) xaxis1,yaxis1 ] [ (1,2) xaxis2,yaxis2 ]
[ (2,1) xaxis3,yaxis3 - ]
>>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=1, col=1) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=1, col=2) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=2, col=1) # doctest: +ELLIPSIS
Figure(...)
Example 4:
>>> # insets
>>> fig = make_subplots(insets=[{'cell': (1,1), 'l': 0.7, 'b': 0.3}])
This is the format of your plot grid:
[ (1,1) xaxis1,yaxis1 ]
With insets:
[ xaxis2,yaxis2 ] over [ (1,1) xaxis1,yaxis1 ]
>>> fig.add_scatter(x=[1,2,3], y=[2,1,1]) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_scatter(x=[1,2,3], y=[2,1,2], xaxis='x2', yaxis='y2') # doctest: +ELLIPSIS
Figure(...)
Example 5:
>>> # include subplot titles
>>> fig = make_subplots(rows=2, subplot_titles=('Plot 1','Plot 2'))
This is the format of your plot grid:
[ (1,1) x1,y1 ]
[ (2,1) x2,y2 ]
>>> fig.add_scatter(x=[1,2,3], y=[2,1,2], row=1, col=1) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_bar(x=[1,2,3], y=[2,1,2], row=2, col=1) # doctest: +ELLIPSIS
Figure(...)
Example 6:
Subplot with mixed subplot types
>>> fig = make_subplots(rows=2, cols=2,
... specs=[[{'type': 'xy'}, {'type': 'polar'}],
... [{'type': 'scene'}, {'type': 'ternary'}]])
>>> fig.add_traces(
... [go.Scatter(y=[2, 3, 1]),
... go.Scatterpolar(r=[1, 3, 2], theta=[0, 45, 90]),
... go.Scatter3d(x=[1, 2, 1], y=[2, 3, 1], z=[0, 3, 5]),
... go.Scatterternary(a=[0.1, 0.2, 0.1],
... b=[0.2, 0.3, 0.1],
... c=[0.7, 0.5, 0.8])],
... rows=[1, 1, 2, 2],
... cols=[1, 2, 1, 2]) # doctest: +ELLIPSIS
Figure(...)
"""
| /usr/src/app/target_test_cases/failed_tests_subplots.make_subplots.txt | def make_subplots(
rows=1,
cols=1,
shared_xaxes=False,
shared_yaxes=False,
start_cell="top-left",
print_grid=False,
horizontal_spacing=None,
vertical_spacing=None,
subplot_titles=None,
column_widths=None,
row_heights=None,
specs=None,
insets=None,
column_titles=None,
row_titles=None,
x_title=None,
y_title=None,
figure=None,
**kwargs,
) -> go.Figure:
"""
Return an instance of plotly.graph_objs.Figure with predefined subplots
configured in 'layout'.
Parameters
----------
rows: int (default 1)
Number of rows in the subplot grid. Must be greater than zero.
cols: int (default 1)
Number of columns in the subplot grid. Must be greater than zero.
shared_xaxes: boolean or str (default False)
Assign shared (linked) x-axes for 2D cartesian subplots
- True or 'columns': Share axes among subplots in the same column
- 'rows': Share axes among subplots in the same row
- 'all': Share axes across all subplots in the grid.
shared_yaxes: boolean or str (default False)
Assign shared (linked) y-axes for 2D cartesian subplots
- 'columns': Share axes among subplots in the same column
- True or 'rows': Share axes among subplots in the same row
- 'all': Share axes across all subplots in the grid.
start_cell: 'bottom-left' or 'top-left' (default 'top-left')
Choose the starting cell in the subplot grid used to set the
domains_grid of the subplots.
- 'top-left': Subplots are numbered with (1, 1) in the top
left corner
- 'bottom-left': Subplots are numbererd with (1, 1) in the bottom
left corner
print_grid: boolean (default True):
If True, prints a string representation of the plot grid. Grid may
also be printed using the `Figure.print_grid()` method on the
resulting figure.
horizontal_spacing: float (default 0.2 / cols)
Space between subplot columns in normalized plot coordinates. Must be
a float between 0 and 1.
Applies to all columns (use 'specs' subplot-dependents spacing)
vertical_spacing: float (default 0.3 / rows)
Space between subplot rows in normalized plot coordinates. Must be
a float between 0 and 1.
Applies to all rows (use 'specs' subplot-dependents spacing)
subplot_titles: list of str or None (default None)
Title of each subplot as a list in row-major ordering.
Empty strings ("") can be included in the list if no subplot title
is desired in that space so that the titles are properly indexed.
specs: list of lists of dict or None (default None)
Per subplot specifications of subplot type, row/column spanning, and
spacing.
ex1: specs=[[{}, {}], [{'colspan': 2}, None]]
ex2: specs=[[{'rowspan': 2}, {}], [None, {}]]
- Indices of the outer list correspond to subplot grid rows
starting from the top, if start_cell='top-left',
or bottom, if start_cell='bottom-left'.
The number of rows in 'specs' must be equal to 'rows'.
- Indices of the inner lists correspond to subplot grid columns
starting from the left. The number of columns in 'specs'
must be equal to 'cols'.
- Each item in the 'specs' list corresponds to one subplot
in a subplot grid. (N.B. The subplot grid has exactly 'rows'
times 'cols' cells.)
- Use None for a blank a subplot cell (or to move past a col/row span).
- Note that specs[0][0] has the specs of the 'start_cell' subplot.
- Each item in 'specs' is a dictionary.
The available keys are:
* type (string, default 'xy'): Subplot type. One of
- 'xy': 2D Cartesian subplot type for scatter, bar, etc.
- 'scene': 3D Cartesian subplot for scatter3d, cone, etc.
- 'polar': Polar subplot for scatterpolar, barpolar, etc.
- 'ternary': Ternary subplot for scatterternary
- 'map': Map subplot for scattermap
- 'mapbox': Mapbox subplot for scattermapbox
- 'domain': Subplot type for traces that are individually
positioned. pie, parcoords, parcats, etc.
- trace type: A trace type which will be used to determine
the appropriate subplot type for that trace
* secondary_y (bool, default False): If True, create a secondary
y-axis positioned on the right side of the subplot. Only valid
if type='xy'.
* colspan (int, default 1): number of subplot columns
for this subplot to span.
* rowspan (int, default 1): number of subplot rows
for this subplot to span.
* l (float, default 0.0): padding left of cell
* r (float, default 0.0): padding right of cell
* t (float, default 0.0): padding right of cell
* b (float, default 0.0): padding bottom of cell
- Note: Use 'horizontal_spacing' and 'vertical_spacing' to adjust
the spacing in between the subplots.
insets: list of dict or None (default None):
Inset specifications. Insets are subplots that overlay grid subplots
- Each item in 'insets' is a dictionary.
The available keys are:
* cell (tuple, default=(1,1)): (row, col) index of the
subplot cell to overlay inset axes onto.
* type (string, default 'xy'): Subplot type
* l (float, default=0.0): padding left of inset
in fraction of cell width
* w (float or 'to_end', default='to_end') inset width
in fraction of cell width ('to_end': to cell right edge)
* b (float, default=0.0): padding bottom of inset
in fraction of cell height
* h (float or 'to_end', default='to_end') inset height
in fraction of cell height ('to_end': to cell top edge)
column_widths: list of numbers or None (default None)
list of length `cols` of the relative widths of each column of subplots.
Values are normalized internally and used to distribute overall width
of the figure (excluding padding) among the columns.
For backward compatibility, may also be specified using the
`column_width` keyword argument.
row_heights: list of numbers or None (default None)
list of length `rows` of the relative heights of each row of subplots.
If start_cell='top-left' then row heights are applied top to bottom.
Otherwise, if start_cell='bottom-left' then row heights are applied
bottom to top.
For backward compatibility, may also be specified using the
`row_width` kwarg. If specified as `row_width`, then the width values
are applied from bottom to top regardless of the value of start_cell.
This matches the legacy behavior of the `row_width` argument.
column_titles: list of str or None (default None)
list of length `cols` of titles to place above the top subplot in
each column.
row_titles: list of str or None (default None)
list of length `rows` of titles to place on the right side of each
row of subplots. If start_cell='top-left' then row titles are
applied top to bottom. Otherwise, if start_cell='bottom-left' then
row titles are applied bottom to top.
x_title: str or None (default None)
Title to place below the bottom row of subplots,
centered horizontally
y_title: str or None (default None)
Title to place to the left of the left column of subplots,
centered vertically
figure: go.Figure or None (default None)
If None, a new go.Figure instance will be created and its axes will be
populated with those corresponding to the requested subplot geometry and
this new figure will be returned.
If a go.Figure instance, the axes will be added to the
layout of this figure and this figure will be returned. If the figure
already contains axes, they will be overwritten.
Examples
--------
Example 1:
>>> # Stack two subplots vertically, and add a scatter trace to each
>>> from plotly.subplots import make_subplots
>>> import plotly.graph_objects as go
>>> fig = make_subplots(rows=2)
This is the format of your plot grid:
[ (1,1) xaxis1,yaxis1 ]
[ (2,1) xaxis2,yaxis2 ]
>>> fig.add_scatter(y=[2, 1, 3], row=1, col=1) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_scatter(y=[1, 3, 2], row=2, col=1) # doctest: +ELLIPSIS
Figure(...)
or see Figure.append_trace
Example 2:
>>> # Stack a scatter plot
>>> fig = make_subplots(rows=2, shared_xaxes=True)
This is the format of your plot grid:
[ (1,1) xaxis1,yaxis1 ]
[ (2,1) xaxis2,yaxis2 ]
>>> fig.add_scatter(y=[2, 1, 3], row=1, col=1) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_scatter(y=[1, 3, 2], row=2, col=1) # doctest: +ELLIPSIS
Figure(...)
Example 3:
>>> # irregular subplot layout (more examples below under 'specs')
>>> fig = make_subplots(rows=2, cols=2,
... specs=[[{}, {}],
... [{'colspan': 2}, None]])
This is the format of your plot grid:
[ (1,1) xaxis1,yaxis1 ] [ (1,2) xaxis2,yaxis2 ]
[ (2,1) xaxis3,yaxis3 - ]
>>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=1, col=1) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=1, col=2) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=2, col=1) # doctest: +ELLIPSIS
Figure(...)
Example 4:
>>> # insets
>>> fig = make_subplots(insets=[{'cell': (1,1), 'l': 0.7, 'b': 0.3}])
This is the format of your plot grid:
[ (1,1) xaxis1,yaxis1 ]
With insets:
[ xaxis2,yaxis2 ] over [ (1,1) xaxis1,yaxis1 ]
>>> fig.add_scatter(x=[1,2,3], y=[2,1,1]) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_scatter(x=[1,2,3], y=[2,1,2], xaxis='x2', yaxis='y2') # doctest: +ELLIPSIS
Figure(...)
Example 5:
>>> # include subplot titles
>>> fig = make_subplots(rows=2, subplot_titles=('Plot 1','Plot 2'))
This is the format of your plot grid:
[ (1,1) x1,y1 ]
[ (2,1) x2,y2 ]
>>> fig.add_scatter(x=[1,2,3], y=[2,1,2], row=1, col=1) # doctest: +ELLIPSIS
Figure(...)
>>> fig.add_bar(x=[1,2,3], y=[2,1,2], row=2, col=1) # doctest: +ELLIPSIS
Figure(...)
Example 6:
Subplot with mixed subplot types
>>> fig = make_subplots(rows=2, cols=2,
... specs=[[{'type': 'xy'}, {'type': 'polar'}],
... [{'type': 'scene'}, {'type': 'ternary'}]])
>>> fig.add_traces(
... [go.Scatter(y=[2, 3, 1]),
... go.Scatterpolar(r=[1, 3, 2], theta=[0, 45, 90]),
... go.Scatter3d(x=[1, 2, 1], y=[2, 3, 1], z=[0, 3, 5]),
... go.Scatterternary(a=[0.1, 0.2, 0.1],
... b=[0.2, 0.3, 0.1],
... c=[0.7, 0.5, 0.8])],
... rows=[1, 1, 2, 2],
... cols=[1, 2, 1, 2]) # doctest: +ELLIPSIS
Figure(...)
"""
return _sub.make_subplots(
rows,
cols,
shared_xaxes,
shared_yaxes,
start_cell,
print_grid,
horizontal_spacing,
vertical_spacing,
subplot_titles,
column_widths,
row_heights,
specs,
insets,
column_titles,
row_titles,
x_title,
y_title,
figure,
**kwargs,
)
| subplots.make_subplots |
plotly.py | 75 | packages/python/plotly/plotly/tools.py | def make_subplots(
rows=1,
cols=1,
shared_xaxes=False,
shared_yaxes=False,
start_cell="top-left",
print_grid=None,
**kwargs,
):
"""Return an instance of plotly.graph_objs.Figure
with the subplots domain set in 'layout'.
Example 1:
# 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['data'] += [Scatter(x=[1,2,3], y=[2,1,2])]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], xaxis='x2', yaxis='y2')]
# or see Figure.append_trace
Example 2:
# subplots with shared x axes
fig = tools.make_subplots(rows=2, shared_xaxes=True)
This is the format of your plot grid:
[ (1,1) x1,y1 ]
[ (2,1) x1,y2 ]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2])]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], yaxis='y2')]
Example 3:
# irregular subplot layout (more examples below under 'specs')
fig = tools.make_subplots(rows=2, cols=2,
specs=[[{}, {}],
[{'colspan': 2}, None]])
This is the format of your plot grid!
[ (1,1) x1,y1 ] [ (1,2) x2,y2 ]
[ (2,1) x3,y3 - ]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2])]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], xaxis='x2', yaxis='y2')]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], xaxis='x3', yaxis='y3')]
Example 4:
# insets
fig = tools.make_subplots(insets=[{'cell': (1,1), 'l': 0.7, 'b': 0.3}])
This is the format of your plot grid!
[ (1,1) x1,y1 ]
With insets:
[ x2,y2 ] over [ (1,1) x1,y1 ]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2])]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], xaxis='x2', yaxis='y2')]
Example 5:
# include subplot titles
fig = tools.make_subplots(rows=2, subplot_titles=('Plot 1','Plot 2'))
This is the format of your plot grid:
[ (1,1) x1,y1 ]
[ (2,1) x2,y2 ]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2])]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], xaxis='x2', yaxis='y2')]
Example 6:
# Include subplot title on one plot (but not all)
fig = tools.make_subplots(insets=[{'cell': (1,1), 'l': 0.7, 'b': 0.3}],
subplot_titles=('','Inset'))
This is the format of your plot grid!
[ (1,1) x1,y1 ]
With insets:
[ x2,y2 ] over [ (1,1) x1,y1 ]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2])]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], xaxis='x2', yaxis='y2')]
Keywords arguments with constant defaults:
rows (kwarg, int greater than 0, default=1):
Number of rows in the subplot grid.
cols (kwarg, int greater than 0, default=1):
Number of columns in the subplot grid.
shared_xaxes (kwarg, boolean or list, default=False)
Assign shared x axes.
If True, subplots in the same grid column have one common
shared x-axis at the bottom of the gird.
To assign shared x axes per subplot grid cell (see 'specs'),
send list (or list of lists, one list per shared x axis)
of cell index tuples.
shared_yaxes (kwarg, boolean or list, default=False)
Assign shared y axes.
If True, subplots in the same grid row have one common
shared y-axis on the left-hand side of the gird.
To assign shared y axes per subplot grid cell (see 'specs'),
send list (or list of lists, one list per shared y axis)
of cell index tuples.
start_cell (kwarg, 'bottom-left' or 'top-left', default='top-left')
Choose the starting cell in the subplot grid used to set the
domains of the subplots.
print_grid (kwarg, boolean, default=True):
If True, prints a tab-delimited string representation of
your plot grid.
Keyword arguments with variable defaults:
horizontal_spacing (kwarg, float in [0,1], default=0.2 / cols):
Space between subplot columns.
Applies to all columns (use 'specs' subplot-dependents spacing)
vertical_spacing (kwarg, float in [0,1], default=0.3 / rows):
Space between subplot rows.
Applies to all rows (use 'specs' subplot-dependents spacing)
subplot_titles (kwarg, list of strings, default=empty list):
Title of each subplot.
"" can be included in the list if no subplot title is desired in
that space so that the titles are properly indexed.
specs (kwarg, list of lists of dictionaries):
Subplot specifications.
ex1: specs=[[{}, {}], [{'colspan': 2}, None]]
ex2: specs=[[{'rowspan': 2}, {}], [None, {}]]
- Indices of the outer list correspond to subplot grid rows
starting from the bottom. The number of rows in 'specs'
must be equal to 'rows'.
- Indices of the inner lists correspond to subplot grid columns
starting from the left. The number of columns in 'specs'
must be equal to 'cols'.
- Each item in the 'specs' list corresponds to one subplot
in a subplot grid. (N.B. The subplot grid has exactly 'rows'
times 'cols' cells.)
- Use None for blank a subplot cell (or to move pass a col/row span).
- Note that specs[0][0] has the specs of the 'start_cell' subplot.
- Each item in 'specs' is a dictionary.
The available keys are:
* is_3d (boolean, default=False): flag for 3d scenes
* colspan (int, default=1): number of subplot columns
for this subplot to span.
* rowspan (int, default=1): number of subplot rows
for this subplot to span.
* l (float, default=0.0): padding left of cell
* r (float, default=0.0): padding right of cell
* t (float, default=0.0): padding right of cell
* b (float, default=0.0): padding bottom of cell
- Use 'horizontal_spacing' and 'vertical_spacing' to adjust
the spacing in between the subplots.
insets (kwarg, list of dictionaries):
Inset specifications.
- Each item in 'insets' is a dictionary.
The available keys are:
* cell (tuple, default=(1,1)): (row, col) index of the
subplot cell to overlay inset axes onto.
* is_3d (boolean, default=False): flag for 3d scenes
* l (float, default=0.0): padding left of inset
in fraction of cell width
* w (float or 'to_end', default='to_end') inset width
in fraction of cell width ('to_end': to cell right edge)
* b (float, default=0.0): padding bottom of inset
in fraction of cell height
* h (float or 'to_end', default='to_end') inset height
in fraction of cell height ('to_end': to cell top edge)
column_width (kwarg, list of numbers)
Column_width specifications
- Functions similarly to `column_width` of `plotly.graph_objs.Table`.
Specify a list that contains numbers where the amount of numbers in
the list is equal to `cols`.
- The numbers in the list indicate the proportions that each column
domains take across the full horizontal domain excluding padding.
- For example, if columns_width=[3, 1], horizontal_spacing=0, and
cols=2, the domains for each column would be [0. 0.75] and [0.75, 1]
row_width (kwargs, list of numbers)
Row_width specifications
- Functions similarly to `column_width`. Specify a list that contains
numbers where the amount of numbers in the list is equal to `rows`.
- The numbers in the list indicate the proportions that each row
domains take along the full vertical domain excluding padding.
- For example, if row_width=[3, 1], vertical_spacing=0, and
cols=2, the domains for each row from top to botton would be
[0. 0.75] and [0.75, 1]
"""
| /usr/src/app/target_test_cases/failed_tests_tools.make_subplots.txt | def make_subplots(
rows=1,
cols=1,
shared_xaxes=False,
shared_yaxes=False,
start_cell="top-left",
print_grid=None,
**kwargs,
):
"""Return an instance of plotly.graph_objs.Figure
with the subplots domain set in 'layout'.
Example 1:
# 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['data'] += [Scatter(x=[1,2,3], y=[2,1,2])]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], xaxis='x2', yaxis='y2')]
# or see Figure.append_trace
Example 2:
# subplots with shared x axes
fig = tools.make_subplots(rows=2, shared_xaxes=True)
This is the format of your plot grid:
[ (1,1) x1,y1 ]
[ (2,1) x1,y2 ]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2])]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], yaxis='y2')]
Example 3:
# irregular subplot layout (more examples below under 'specs')
fig = tools.make_subplots(rows=2, cols=2,
specs=[[{}, {}],
[{'colspan': 2}, None]])
This is the format of your plot grid!
[ (1,1) x1,y1 ] [ (1,2) x2,y2 ]
[ (2,1) x3,y3 - ]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2])]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], xaxis='x2', yaxis='y2')]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], xaxis='x3', yaxis='y3')]
Example 4:
# insets
fig = tools.make_subplots(insets=[{'cell': (1,1), 'l': 0.7, 'b': 0.3}])
This is the format of your plot grid!
[ (1,1) x1,y1 ]
With insets:
[ x2,y2 ] over [ (1,1) x1,y1 ]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2])]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], xaxis='x2', yaxis='y2')]
Example 5:
# include subplot titles
fig = tools.make_subplots(rows=2, subplot_titles=('Plot 1','Plot 2'))
This is the format of your plot grid:
[ (1,1) x1,y1 ]
[ (2,1) x2,y2 ]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2])]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], xaxis='x2', yaxis='y2')]
Example 6:
# Include subplot title on one plot (but not all)
fig = tools.make_subplots(insets=[{'cell': (1,1), 'l': 0.7, 'b': 0.3}],
subplot_titles=('','Inset'))
This is the format of your plot grid!
[ (1,1) x1,y1 ]
With insets:
[ x2,y2 ] over [ (1,1) x1,y1 ]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2])]
fig['data'] += [Scatter(x=[1,2,3], y=[2,1,2], xaxis='x2', yaxis='y2')]
Keywords arguments with constant defaults:
rows (kwarg, int greater than 0, default=1):
Number of rows in the subplot grid.
cols (kwarg, int greater than 0, default=1):
Number of columns in the subplot grid.
shared_xaxes (kwarg, boolean or list, default=False)
Assign shared x axes.
If True, subplots in the same grid column have one common
shared x-axis at the bottom of the gird.
To assign shared x axes per subplot grid cell (see 'specs'),
send list (or list of lists, one list per shared x axis)
of cell index tuples.
shared_yaxes (kwarg, boolean or list, default=False)
Assign shared y axes.
If True, subplots in the same grid row have one common
shared y-axis on the left-hand side of the gird.
To assign shared y axes per subplot grid cell (see 'specs'),
send list (or list of lists, one list per shared y axis)
of cell index tuples.
start_cell (kwarg, 'bottom-left' or 'top-left', default='top-left')
Choose the starting cell in the subplot grid used to set the
domains of the subplots.
print_grid (kwarg, boolean, default=True):
If True, prints a tab-delimited string representation of
your plot grid.
Keyword arguments with variable defaults:
horizontal_spacing (kwarg, float in [0,1], default=0.2 / cols):
Space between subplot columns.
Applies to all columns (use 'specs' subplot-dependents spacing)
vertical_spacing (kwarg, float in [0,1], default=0.3 / rows):
Space between subplot rows.
Applies to all rows (use 'specs' subplot-dependents spacing)
subplot_titles (kwarg, list of strings, default=empty list):
Title of each subplot.
"" can be included in the list if no subplot title is desired in
that space so that the titles are properly indexed.
specs (kwarg, list of lists of dictionaries):
Subplot specifications.
ex1: specs=[[{}, {}], [{'colspan': 2}, None]]
ex2: specs=[[{'rowspan': 2}, {}], [None, {}]]
- Indices of the outer list correspond to subplot grid rows
starting from the bottom. The number of rows in 'specs'
must be equal to 'rows'.
- Indices of the inner lists correspond to subplot grid columns
starting from the left. The number of columns in 'specs'
must be equal to 'cols'.
- Each item in the 'specs' list corresponds to one subplot
in a subplot grid. (N.B. The subplot grid has exactly 'rows'
times 'cols' cells.)
- Use None for blank a subplot cell (or to move pass a col/row span).
- Note that specs[0][0] has the specs of the 'start_cell' subplot.
- Each item in 'specs' is a dictionary.
The available keys are:
* is_3d (boolean, default=False): flag for 3d scenes
* colspan (int, default=1): number of subplot columns
for this subplot to span.
* rowspan (int, default=1): number of subplot rows
for this subplot to span.
* l (float, default=0.0): padding left of cell
* r (float, default=0.0): padding right of cell
* t (float, default=0.0): padding right of cell
* b (float, default=0.0): padding bottom of cell
- Use 'horizontal_spacing' and 'vertical_spacing' to adjust
the spacing in between the subplots.
insets (kwarg, list of dictionaries):
Inset specifications.
- Each item in 'insets' is a dictionary.
The available keys are:
* cell (tuple, default=(1,1)): (row, col) index of the
subplot cell to overlay inset axes onto.
* is_3d (boolean, default=False): flag for 3d scenes
* l (float, default=0.0): padding left of inset
in fraction of cell width
* w (float or 'to_end', default='to_end') inset width
in fraction of cell width ('to_end': to cell right edge)
* b (float, default=0.0): padding bottom of inset
in fraction of cell height
* h (float or 'to_end', default='to_end') inset height
in fraction of cell height ('to_end': to cell top edge)
column_width (kwarg, list of numbers)
Column_width specifications
- Functions similarly to `column_width` of `plotly.graph_objs.Table`.
Specify a list that contains numbers where the amount of numbers in
the list is equal to `cols`.
- The numbers in the list indicate the proportions that each column
domains take across the full horizontal domain excluding padding.
- For example, if columns_width=[3, 1], horizontal_spacing=0, and
cols=2, the domains for each column would be [0. 0.75] and [0.75, 1]
row_width (kwargs, list of numbers)
Row_width specifications
- Functions similarly to `column_width`. Specify a list that contains
numbers where the amount of numbers in the list is equal to `rows`.
- The numbers in the list indicate the proportions that each row
domains take along the full vertical domain excluding padding.
- For example, if row_width=[3, 1], vertical_spacing=0, and
cols=2, the domains for each row from top to botton would be
[0. 0.75] and [0.75, 1]
"""
import plotly.subplots
warnings.warn(
"plotly.tools.make_subplots is deprecated, "
"please use plotly.subplots.make_subplots instead",
DeprecationWarning,
stacklevel=1,
)
return plotly.subplots.make_subplots(
rows=rows,
cols=cols,
shared_xaxes=shared_xaxes,
shared_yaxes=shared_yaxes,
start_cell=start_cell,
print_grid=print_grid,
**kwargs,
)
| tools.make_subplots |
sphinx | 0 | sphinx/application.py | def __init__(self, srcdir: str | os.PathLike[str], confdir: str | os.PathLike[str] | None,
outdir: str | os.PathLike[str], doctreedir: str | os.PathLike[str],
buildername: str, confoverrides: dict | None = None,
status: IO[str] | None = sys.stdout, warning: IO[str] | None = sys.stderr,
freshenv: bool = False, warningiserror: bool = False,
tags: Sequence[str] = (),
verbosity: int = 0, parallel: int = 0, keep_going: bool = False,
pdb: bool = False, exception_on_warning: bool = False) -> None:
"""Initialize the Sphinx application.
:param srcdir: The path to the source directory.
:param confdir: The path to the configuration directory.
If not given, it is assumed to be the same as ``srcdir``.
:param outdir: Directory for storing build documents.
:param doctreedir: Directory for caching pickled doctrees.
:param buildername: The name of the builder to use.
:param confoverrides: A dictionary of configuration settings that override the
settings in the configuration file.
:param status: A file-like object to write status messages to.
:param warning: A file-like object to write warnings to.
:param freshenv: If true, clear the cached environment.
:param warningiserror: If true, warnings become errors.
:param tags: A list of tags to apply.
:param verbosity: The verbosity level.
:param parallel: The maximum number of parallel jobs to use
when reading/writing documents.
:param keep_going: Unused.
:param pdb: If true, enable the Python debugger on an exception.
:param exception_on_warning: If true, raise an exception on warnings.
"""
| /usr/src/app/target_test_cases/failed_tests___init__.txt | def __init__(self, srcdir: str | os.PathLike[str], confdir: str | os.PathLike[str] | None,
outdir: str | os.PathLike[str], doctreedir: str | os.PathLike[str],
buildername: str, confoverrides: dict | None = None,
status: IO[str] | None = sys.stdout, warning: IO[str] | None = sys.stderr,
freshenv: bool = False, warningiserror: bool = False,
tags: Sequence[str] = (),
verbosity: int = 0, parallel: int = 0, keep_going: bool = False,
pdb: bool = False, exception_on_warning: bool = False) -> None:
"""Initialize the Sphinx application.
:param srcdir: The path to the source directory.
:param confdir: The path to the configuration directory.
If not given, it is assumed to be the same as ``srcdir``.
:param outdir: Directory for storing build documents.
:param doctreedir: Directory for caching pickled doctrees.
:param buildername: The name of the builder to use.
:param confoverrides: A dictionary of configuration settings that override the
settings in the configuration file.
:param status: A file-like object to write status messages to.
:param warning: A file-like object to write warnings to.
:param freshenv: If true, clear the cached environment.
:param warningiserror: If true, warnings become errors.
:param tags: A list of tags to apply.
:param verbosity: The verbosity level.
:param parallel: The maximum number of parallel jobs to use
when reading/writing documents.
:param keep_going: Unused.
:param pdb: If true, enable the Python debugger on an exception.
:param exception_on_warning: If true, raise an exception on warnings.
"""
self.phase = BuildPhase.INITIALIZATION
self.verbosity = verbosity
self._fresh_env_used: bool | None = None
self.extensions: dict[str, Extension] = {}
self.registry = SphinxComponentRegistry()
# validate provided directories
self.srcdir = _StrPath(srcdir).resolve()
self.outdir = _StrPath(outdir).resolve()
self.doctreedir = _StrPath(doctreedir).resolve()
if not path.isdir(self.srcdir):
raise ApplicationError(__('Cannot find source directory (%s)') %
self.srcdir)
if path.exists(self.outdir) and not path.isdir(self.outdir):
raise ApplicationError(__('Output directory (%s) is not a directory') %
self.outdir)
if self.srcdir == self.outdir:
raise ApplicationError(__('Source directory and destination '
'directory cannot be identical'))
self.parallel = parallel
if status is None:
self._status: IO[str] = StringIO()
self.quiet: bool = True
else:
self._status = status
self.quiet = False
if warning is None:
self._warning: IO[str] = StringIO()
else:
self._warning = warning
self._warncount = 0
self.keep_going = bool(warningiserror) # Unused
self._fail_on_warnings = bool(warningiserror)
self.pdb = pdb
self._exception_on_warning = exception_on_warning
logging.setup(self, self._status, self._warning)
self.events = EventManager(self)
# keep last few messages for traceback
# This will be filled by sphinx.util.logging.LastMessagesWriter
self.messagelog: deque[str] = deque(maxlen=10)
# say hello to the world
logger.info(bold(__('Running Sphinx v%s')), sphinx.__display_version__)
# status code for command-line application
self.statuscode = 0
# read config
self.tags = Tags(tags)
if confdir is None:
# set confdir to srcdir if -C given (!= no confdir); a few pieces
# of code expect a confdir to be set
self.confdir = self.srcdir
self.config = Config({}, confoverrides or {})
else:
self.confdir = _StrPath(confdir).resolve()
self.config = Config.read(self.confdir, confoverrides or {}, self.tags)
# set up translation infrastructure
self._init_i18n()
# check the Sphinx version if requested
if self.config.needs_sphinx and self.config.needs_sphinx > sphinx.__display_version__:
raise VersionRequirementError(
__('This project needs at least Sphinx v%s and therefore cannot '
'be built with this version.') % self.config.needs_sphinx)
# load all built-in extension modules, first-party extension modules,
# and first-party themes
for extension in builtin_extensions:
self.setup_extension(extension)
# load all user-given extension modules
for extension in self.config.extensions:
self.setup_extension(extension)
# preload builder module (before init config values)
self.preload_builder(buildername)
if not path.isdir(outdir):
with progress_message(__('making output directory')):
ensuredir(outdir)
# the config file itself can be an extension
if self.config.setup:
prefix = __('while setting up extension %s:') % "conf.py"
with prefixed_warnings(prefix):
if callable(self.config.setup):
self.config.setup(self)
else:
raise ConfigError(
__("'setup' as currently defined in conf.py isn't a Python callable. "
"Please modify its definition to make it a callable function. "
"This is needed for conf.py to behave as a Sphinx extension."),
)
# Report any warnings for overrides.
self.config._report_override_warnings()
self.events.emit('config-inited', self.config)
# create the project
self.project = Project(self.srcdir, self.config.source_suffix)
# set up the build environment
self.env = self._init_env(freshenv)
# create the builder
self.builder = self.create_builder(buildername)
# build environment post-initialisation, after creating the builder
self._post_init_env()
# set up the builder
self._init_builder()
| __init__ |
sphinx | 1 | sphinx/directives/__init__.py | def run(self) -> list[Node]:
"""
Main directive entry function, called by docutils upon encountering the
directive.
This directive is meant to be quite easily subclassable, so it delegates
to several additional methods. What it does:
* find out if called as a domain-specific directive, set self.domain
* create a `desc` node to fit all description inside
* parse standard options, currently `no-index`
* create an index node if needed as self.indexnode
* parse all given signatures (as returned by self.get_signatures())
using self.handle_signature(), which should either return a name
or raise ValueError
* add index entries using self.add_target_and_index()
* parse the content and handle doc fields in it
"""
| /usr/src/app/target_test_cases/failed_tests___init__.ObjectDescription.run.txt | def run(self) -> list[Node]:
"""
Main directive entry function, called by docutils upon encountering the
directive.
This directive is meant to be quite easily subclassable, so it delegates
to several additional methods. What it does:
* find out if called as a domain-specific directive, set self.domain
* create a `desc` node to fit all description inside
* parse standard options, currently `no-index`
* create an index node if needed as self.indexnode
* parse all given signatures (as returned by self.get_signatures())
using self.handle_signature(), which should either return a name
or raise ValueError
* add index entries using self.add_target_and_index()
* parse the content and handle doc fields in it
"""
if ':' in self.name:
self.domain, self.objtype = self.name.split(':', 1)
else:
self.domain, self.objtype = '', self.name
self.indexnode = addnodes.index(entries=[])
node = addnodes.desc()
node.document = self.state.document
source, line = self.get_source_info()
# If any options were specified to the directive,
# self.state.document.current_line will at this point be set to
# None. To ensure nodes created as part of the signature have a line
# number set, set the document's line number correctly.
#
# Note that we need to subtract one from the line number since
# note_source uses 0-based line numbers.
if line is not None:
line -= 1
self.state.document.note_source(source, line)
node['domain'] = self.domain
# 'desctype' is a backwards compatible attribute
node['objtype'] = node['desctype'] = self.objtype
# Copy old option names to new ones
# xref RemovedInSphinx90Warning
# deprecate noindex, noindexentry, and nocontentsentry in Sphinx 9.0
if 'no-index' not in self.options and 'noindex' in self.options:
self.options['no-index'] = self.options['noindex']
if 'no-index-entry' not in self.options and 'noindexentry' in self.options:
self.options['no-index-entry'] = self.options['noindexentry']
if 'no-contents-entry' not in self.options and 'nocontentsentry' in self.options:
self.options['no-contents-entry'] = self.options['nocontentsentry']
node['no-index'] = node['noindex'] = no_index = (
'no-index' in self.options
)
node['no-index-entry'] = node['noindexentry'] = (
'no-index-entry' in self.options
)
node['no-contents-entry'] = node['nocontentsentry'] = (
'no-contents-entry' in self.options
)
node['no-typesetting'] = ('no-typesetting' in self.options)
if self.domain:
node['classes'].append(self.domain)
node['classes'].append(node['objtype'])
self.names: list[ObjDescT] = []
signatures = self.get_signatures()
for sig in signatures:
# add a signature node for each signature in the current unit
# and add a reference target for it
signode = addnodes.desc_signature(sig, '')
self.set_source_info(signode)
node.append(signode)
try:
# name can also be a tuple, e.g. (classname, objname);
# this is strictly domain-specific (i.e. no assumptions may
# be made in this base class)
name = self.handle_signature(sig, signode)
except ValueError:
# signature parsing failed
signode.clear()
signode += addnodes.desc_name(sig, sig)
continue # we don't want an index entry here
finally:
# Private attributes for ToC generation. Will be modified or removed
# without notice.
if self.env.app.config.toc_object_entries:
signode['_toc_parts'] = self._object_hierarchy_parts(signode)
signode['_toc_name'] = self._toc_entry_name(signode)
else:
signode['_toc_parts'] = ()
signode['_toc_name'] = ''
if name not in self.names:
self.names.append(name)
if not no_index:
# only add target and index entry if this is the first
# description of the object with this name in this desc block
self.add_target_and_index(name, sig, signode)
if self.names:
# needed for association of version{added,changed} directives
self.env.temp_data['object'] = self.names[0]
self.before_content()
content_children = self.parse_content_to_nodes(allow_section_headings=True)
content_node = addnodes.desc_content('', *content_children)
node.append(content_node)
self.transform_content(content_node)
self.env.app.emit('object-description-transform',
self.domain, self.objtype, content_node)
DocFieldTransformer(self).transform_all(content_node)
self.env.temp_data['object'] = None
self.after_content()
if node['no-typesetting']:
# Attempt to return the index node, and a new target node
# containing all the ids of this node and its children.
# If ``:no-index:`` is set, or there are no ids on the node
# or any of its children, then just return the index node,
# as Docutils expects a target node to have at least one id.
if node_ids := [node_id for el in node.findall(nodes.Element) # type: ignore[var-annotated]
for node_id in el.get('ids', ())]:
target_node = nodes.target(ids=node_ids)
self.set_source_info(target_node)
return [self.indexnode, target_node]
return [self.indexnode]
return [self.indexnode, node]
| __init__.ObjectDescription.run |
sphinx | 2 | sphinx/ext/napoleon/__init__.py | def _process_docstring(app: Sphinx, what: str, name: str, obj: Any,
options: Any, lines: list[str]) -> None:
"""Process the docstring for a given python object.
Called when autodoc has read and processed a docstring. `lines` is a list
of docstring lines that `_process_docstring` modifies in place to change
what Sphinx outputs.
The following settings in conf.py control what styles of docstrings will
be parsed:
* ``napoleon_google_docstring`` -- parse Google style docstrings
* ``napoleon_numpy_docstring`` -- parse NumPy style docstrings
Parameters
----------
app : sphinx.application.Sphinx
Application object representing the Sphinx process.
what : str
A string specifying the type of the object to which the docstring
belongs. Valid values: "module", "class", "exception", "function",
"method", "attribute".
name : str
The fully qualified name of the object.
obj : module, class, exception, function, method, or attribute
The object to which the docstring belongs.
options : sphinx.ext.autodoc.Options
The options given to the directive: an object with attributes
inherited_members, undoc_members, show_inheritance and no_index that
are True if the flag option of same name was given to the auto
directive.
lines : list of str
The lines of the docstring, see above.
.. note:: `lines` is modified *in place*
"""
| /usr/src/app/target_test_cases/failed_tests__process_docstring.txt | def _process_docstring(app: Sphinx, what: str, name: str, obj: Any,
options: Any, lines: list[str]) -> None:
"""Process the docstring for a given python object.
Called when autodoc has read and processed a docstring. `lines` is a list
of docstring lines that `_process_docstring` modifies in place to change
what Sphinx outputs.
The following settings in conf.py control what styles of docstrings will
be parsed:
* ``napoleon_google_docstring`` -- parse Google style docstrings
* ``napoleon_numpy_docstring`` -- parse NumPy style docstrings
Parameters
----------
app : sphinx.application.Sphinx
Application object representing the Sphinx process.
what : str
A string specifying the type of the object to which the docstring
belongs. Valid values: "module", "class", "exception", "function",
"method", "attribute".
name : str
The fully qualified name of the object.
obj : module, class, exception, function, method, or attribute
The object to which the docstring belongs.
options : sphinx.ext.autodoc.Options
The options given to the directive: an object with attributes
inherited_members, undoc_members, show_inheritance and no_index that
are True if the flag option of same name was given to the auto
directive.
lines : list of str
The lines of the docstring, see above.
.. note:: `lines` is modified *in place*
"""
result_lines = lines
docstring: GoogleDocstring
if app.config.napoleon_numpy_docstring:
docstring = NumpyDocstring(result_lines, app.config, app, what, name,
obj, options)
result_lines = docstring.lines()
if app.config.napoleon_google_docstring:
docstring = GoogleDocstring(result_lines, app.config, app, what, name,
obj, options)
result_lines = docstring.lines()
lines[:] = result_lines.copy()
| __init__._process_docstring |
sphinx | 3 | sphinx/ext/napoleon/__init__.py | def _skip_member(app: Sphinx, what: str, name: str, obj: Any,
skip: bool, options: Any) -> bool | None:
"""Determine if private and special class members are included in docs.
The following settings in conf.py determine if private and special class
members or init methods are included in the generated documentation:
* ``napoleon_include_init_with_doc`` --
include init methods if they have docstrings
* ``napoleon_include_private_with_doc`` --
include private members if they have docstrings
* ``napoleon_include_special_with_doc`` --
include special members if they have docstrings
Parameters
----------
app : sphinx.application.Sphinx
Application object representing the Sphinx process
what : str
A string specifying the type of the object to which the member
belongs. Valid values: "module", "class", "exception", "function",
"method", "attribute".
name : str
The name of the member.
obj : module, class, exception, function, method, or attribute.
For example, if the member is the __init__ method of class A, then
`obj` will be `A.__init__`.
skip : bool
A boolean indicating if autodoc will skip this member if `_skip_member`
does not override the decision
options : sphinx.ext.autodoc.Options
The options given to the directive: an object with attributes
inherited_members, undoc_members, show_inheritance and no_index that
are True if the flag option of same name was given to the auto
directive.
Returns
-------
bool
True if the member should be skipped during creation of the docs,
False if it should be included in the docs.
"""
| /usr/src/app/target_test_cases/failed_tests__skip_member.txt | def _skip_member(app: Sphinx, what: str, name: str, obj: Any,
skip: bool, options: Any) -> bool | None:
"""Determine if private and special class members are included in docs.
The following settings in conf.py determine if private and special class
members or init methods are included in the generated documentation:
* ``napoleon_include_init_with_doc`` --
include init methods if they have docstrings
* ``napoleon_include_private_with_doc`` --
include private members if they have docstrings
* ``napoleon_include_special_with_doc`` --
include special members if they have docstrings
Parameters
----------
app : sphinx.application.Sphinx
Application object representing the Sphinx process
what : str
A string specifying the type of the object to which the member
belongs. Valid values: "module", "class", "exception", "function",
"method", "attribute".
name : str
The name of the member.
obj : module, class, exception, function, method, or attribute.
For example, if the member is the __init__ method of class A, then
`obj` will be `A.__init__`.
skip : bool
A boolean indicating if autodoc will skip this member if `_skip_member`
does not override the decision
options : sphinx.ext.autodoc.Options
The options given to the directive: an object with attributes
inherited_members, undoc_members, show_inheritance and no_index that
are True if the flag option of same name was given to the auto
directive.
Returns
-------
bool
True if the member should be skipped during creation of the docs,
False if it should be included in the docs.
"""
has_doc = getattr(obj, '__doc__', False)
is_member = what in ('class', 'exception', 'module')
if name != '__weakref__' and has_doc and is_member:
cls_is_owner = False
if what in ('class', 'exception'):
qualname = getattr(obj, '__qualname__', '')
cls_path, _, _ = qualname.rpartition('.')
if cls_path:
try:
if '.' in cls_path:
import functools
import importlib
mod = importlib.import_module(obj.__module__)
mod_path = cls_path.split('.')
cls = functools.reduce(getattr, mod_path, mod)
else:
cls = inspect.unwrap(obj).__globals__[cls_path]
except Exception:
cls_is_owner = False
else:
cls_is_owner = (cls and hasattr(cls, name) and # type: ignore[assignment]
name in cls.__dict__)
else:
cls_is_owner = False
if what == 'module' or cls_is_owner:
is_init = (name == '__init__')
is_special = (not is_init and name.startswith('__') and
name.endswith('__'))
is_private = (not is_init and not is_special and
name.startswith('_'))
inc_init = app.config.napoleon_include_init_with_doc
inc_special = app.config.napoleon_include_special_with_doc
inc_private = app.config.napoleon_include_private_with_doc
if ((is_special and inc_special) or
(is_private and inc_private) or
(is_init and inc_init)):
return False
return None
| __init__._skip_member |
sphinx | 4 | sphinx/ext/napoleon/__init__.py | def setup(app: Sphinx) -> ExtensionMetadata:
"""Sphinx extension setup function.
When the extension is loaded, Sphinx imports this module and executes
the ``setup()`` function, which in turn notifies Sphinx of everything
the extension offers.
Parameters
----------
app : sphinx.application.Sphinx
Application object representing the Sphinx process
See Also
--------
`The Sphinx documentation on Extensions
<https://www.sphinx-doc.org/extensions.html>`_
`The Extension Tutorial <https://www.sphinx-doc.org/extdev/tutorial.html>`_
`The Extension API <https://www.sphinx-doc.org/extdev/appapi.html>`_
"""
| /usr/src/app/target_test_cases/failed_tests_setup.txt | def setup(app: Sphinx) -> ExtensionMetadata:
"""Sphinx extension setup function.
When the extension is loaded, Sphinx imports this module and executes
the ``setup()`` function, which in turn notifies Sphinx of everything
the extension offers.
Parameters
----------
app : sphinx.application.Sphinx
Application object representing the Sphinx process
See Also
--------
`The Sphinx documentation on Extensions
<https://www.sphinx-doc.org/extensions.html>`_
`The Extension Tutorial <https://www.sphinx-doc.org/extdev/tutorial.html>`_
`The Extension API <https://www.sphinx-doc.org/extdev/appapi.html>`_
"""
if not isinstance(app, Sphinx):
# probably called by tests
return {'version': sphinx.__display_version__, 'parallel_read_safe': True}
_patch_python_domain()
app.setup_extension('sphinx.ext.autodoc')
app.connect('autodoc-process-docstring', _process_docstring)
app.connect('autodoc-skip-member', _skip_member)
for name, (default, rebuild) in Config._config_values.items():
app.add_config_value(name, default, rebuild)
return {'version': sphinx.__display_version__, 'parallel_read_safe': True}
| __init__.setup |
sphinx | 5 | sphinx/ext/coverage.py | def _determine_py_coverage_modules(
coverage_modules: Sequence[str],
seen_modules: Set[str],
ignored_module_exps: Iterable[re.Pattern[str]],
py_undoc: dict[str, dict[str, Any]],
) -> list[str]:
"""Return a sorted list of modules to check for coverage.
Figure out which of the two operating modes to use:
- If 'coverage_modules' is not specified, we check coverage for all modules
seen in the documentation tree. Any objects found in these modules that are
not documented will be noted. This will therefore only identify missing
objects, but it requires no additional configuration.
- If 'coverage_modules' is specified, we check coverage for all modules
specified in this configuration value. Any objects found in these modules
that are not documented will be noted. In addition, any objects from other
modules that are documented will be noted. This will therefore identify both
missing modules and missing objects, but it requires manual configuration.
"""
| /usr/src/app/target_test_cases/failed_tests__determine_py_coverage_modules.txt | def _determine_py_coverage_modules(
coverage_modules: Sequence[str],
seen_modules: Set[str],
ignored_module_exps: Iterable[re.Pattern[str]],
py_undoc: dict[str, dict[str, Any]],
) -> list[str]:
"""Return a sorted list of modules to check for coverage.
Figure out which of the two operating modes to use:
- If 'coverage_modules' is not specified, we check coverage for all modules
seen in the documentation tree. Any objects found in these modules that are
not documented will be noted. This will therefore only identify missing
objects, but it requires no additional configuration.
- If 'coverage_modules' is specified, we check coverage for all modules
specified in this configuration value. Any objects found in these modules
that are not documented will be noted. In addition, any objects from other
modules that are documented will be noted. This will therefore identify both
missing modules and missing objects, but it requires manual configuration.
"""
if not coverage_modules:
return sorted(seen_modules)
modules: set[str] = set()
for mod_name in coverage_modules:
try:
modules |= _load_modules(mod_name, ignored_module_exps)
except ImportError as err:
# TODO(stephenfin): Define a subtype for all logs in this module
logger.warning(__('module %s could not be imported: %s'), mod_name, err)
py_undoc[mod_name] = {'error': err}
continue
# if there are additional modules then we warn but continue scanning
if additional_modules := seen_modules - modules:
logger.warning(
__('the following modules are documented but were not specified '
'in coverage_modules: %s'),
', '.join(additional_modules),
)
# likewise, if there are missing modules we warn but continue scanning
if missing_modules := modules - seen_modules:
logger.warning(
__('the following modules are specified in coverage_modules '
'but were not documented'),
', '.join(missing_modules),
)
return sorted(modules)
| _determine_py_coverage_modules |
sphinx | 6 | sphinx/util/nodes.py | def _make_id(string: str) -> str:
"""Convert `string` into an identifier and return it.
This function is a modified version of ``docutils.nodes.make_id()`` of
docutils-0.16.
Changes:
* Allow to use capital alphabet characters
* Allow to use dots (".") and underscores ("_") for an identifier
without a leading character.
# Author: David Goodger <[email protected]>
# Maintainer: [email protected]
# Copyright: This module has been placed in the public domain.
"""
| /usr/src/app/target_test_cases/failed_tests__make_id.txt | def _make_id(string: str) -> str:
"""Convert `string` into an identifier and return it.
This function is a modified version of ``docutils.nodes.make_id()`` of
docutils-0.16.
Changes:
* Allow to use capital alphabet characters
* Allow to use dots (".") and underscores ("_") for an identifier
without a leading character.
# Author: David Goodger <[email protected]>
# Maintainer: [email protected]
# Copyright: This module has been placed in the public domain.
"""
id = string.translate(_non_id_translate_digraphs)
id = id.translate(_non_id_translate)
# get rid of non-ascii characters.
# 'ascii' lowercase to prevent problems with turkish locale.
id = unicodedata.normalize('NFKD', id).encode('ascii', 'ignore').decode('ascii')
# shrink runs of whitespace and replace by hyphen
id = _non_id_chars.sub('-', ' '.join(id.split()))
id = _non_id_at_ends.sub('', id)
return str(id)
| _make_id |
sphinx | 7 | sphinx/ext/intersphinx/_load.py | def _read_from_url(url: str, *, config: Config) -> HTTPResponse:
"""Reads data from *url* with an HTTP *GET*.
This function supports fetching from resources which use basic HTTP auth as
laid out by RFC1738 § 3.1. See § 5 for grammar definitions for URLs.
.. seealso:
https://www.ietf.org/rfc/rfc1738.txt
:param url: URL of an HTTP resource
:type url: ``str``
:return: data read from resource described by *url*
:rtype: ``file``-like object
"""
| /usr/src/app/target_test_cases/failed_tests__read_from_url.txt | def _read_from_url(url: str, *, config: Config) -> HTTPResponse:
"""Reads data from *url* with an HTTP *GET*.
This function supports fetching from resources which use basic HTTP auth as
laid out by RFC1738 § 3.1. See § 5 for grammar definitions for URLs.
.. seealso:
https://www.ietf.org/rfc/rfc1738.txt
:param url: URL of an HTTP resource
:type url: ``str``
:return: data read from resource described by *url*
:rtype: ``file``-like object
"""
r = requests.get(url, stream=True, timeout=config.intersphinx_timeout,
_user_agent=config.user_agent,
_tls_info=(config.tls_verify, config.tls_cacerts))
r.raise_for_status()
# For inv_location / new_inv_location
r.raw.url = r.url # type: ignore[union-attr]
# Decode content-body based on the header.
# xref: https://github.com/psf/requests/issues/2155
r.raw.decode_content = True
return r.raw
| _read_from_url |
sphinx | 8 | sphinx/environment/adapters/toctree.py | def _resolve_toctree(
env: BuildEnvironment, docname: str, builder: Builder, toctree: addnodes.toctree, *,
prune: bool = True, maxdepth: int = 0, titles_only: bool = False,
collapse: bool = False, includehidden: bool = False,
) -> Element | None:
"""Resolve a *toctree* node into individual bullet lists with titles
as items, returning None (if no containing titles are found) or
a new node.
If *prune* is True, the tree is pruned to *maxdepth*, or if that is 0,
to the value of the *maxdepth* option on the *toctree* node.
If *titles_only* is True, only toplevel document titles will be in the
resulting tree.
If *collapse* is True, all branches not containing docname will
be collapsed.
"""
| /usr/src/app/target_test_cases/failed_tests_toctree._resolve_toctree.txt | def _resolve_toctree(
env: BuildEnvironment, docname: str, builder: Builder, toctree: addnodes.toctree, *,
prune: bool = True, maxdepth: int = 0, titles_only: bool = False,
collapse: bool = False, includehidden: bool = False,
) -> Element | None:
"""Resolve a *toctree* node into individual bullet lists with titles
as items, returning None (if no containing titles are found) or
a new node.
If *prune* is True, the tree is pruned to *maxdepth*, or if that is 0,
to the value of the *maxdepth* option on the *toctree* node.
If *titles_only* is True, only toplevel document titles will be in the
resulting tree.
If *collapse* is True, all branches not containing docname will
be collapsed.
"""
if toctree.get('hidden', False) and not includehidden:
return None
# For reading the following two helper function, it is useful to keep
# in mind the node structure of a toctree (using HTML-like node names
# for brevity):
#
# <ul>
# <li>
# <p><a></p>
# <p><a></p>
# ...
# <ul>
# ...
# </ul>
# </li>
# </ul>
#
# The transformation is made in two passes in order to avoid
# interactions between marking and pruning the tree (see bug #1046).
toctree_ancestors = _get_toctree_ancestors(env.toctree_includes, docname)
included = Matcher(env.config.include_patterns)
excluded = Matcher(env.config.exclude_patterns)
maxdepth = maxdepth or toctree.get('maxdepth', -1)
if not titles_only and toctree.get('titlesonly', False):
titles_only = True
if not includehidden and toctree.get('includehidden', False):
includehidden = True
tocentries = _entries_from_toctree(
env,
prune,
titles_only,
collapse,
includehidden,
builder.tags,
toctree_ancestors,
included,
excluded,
toctree,
[],
)
if not tocentries:
return None
newnode = addnodes.compact_paragraph('', '')
if caption := toctree.attributes.get('caption'):
caption_node = nodes.title(caption, '', *[nodes.Text(caption)])
caption_node.line = toctree.line
caption_node.source = toctree.source
caption_node.rawsource = toctree['rawcaption']
if hasattr(toctree, 'uid'):
# move uid to caption_node to translate it
caption_node.uid = toctree.uid # type: ignore[attr-defined]
del toctree.uid
newnode.append(caption_node)
newnode.extend(tocentries)
newnode['toctree'] = True
# prune the tree to maxdepth, also set toc depth and current classes
_toctree_add_classes(newnode, 1, docname)
newnode = _toctree_copy(newnode, 1, maxdepth if prune else 0, collapse, builder.tags)
if isinstance(newnode[-1], nodes.Element) and len(newnode[-1]) == 0: # No titles found
return None
# set the target paths in the toctrees (they are not known at TOC
# generation time)
for refnode in newnode.findall(nodes.reference):
if url_re.match(refnode['refuri']) is None:
rel_uri = builder.get_relative_uri(docname, refnode['refuri'])
refnode['refuri'] = rel_uri + refnode['anchorname']
return newnode
| _resolve_toctree |
sphinx | 9 | sphinx/ext/autosummary/generate.py | def _split_full_qualified_name(name: str) -> tuple[str | None, str]:
"""Split full qualified name to a pair of modname and qualname.
A qualname is an abbreviation for "Qualified name" introduced at PEP-3155
(https://peps.python.org/pep-3155/). It is a dotted path name
from the module top-level.
A "full" qualified name means a string containing both module name and
qualified name.
.. note:: This function actually imports the module to check its existence.
Therefore you need to mock 3rd party modules if needed before
calling this function.
"""
| /usr/src/app/target_test_cases/failed_tests__split_full_qualified_name.txt | def _split_full_qualified_name(name: str) -> tuple[str | None, str]:
"""Split full qualified name to a pair of modname and qualname.
A qualname is an abbreviation for "Qualified name" introduced at PEP-3155
(https://peps.python.org/pep-3155/). It is a dotted path name
from the module top-level.
A "full" qualified name means a string containing both module name and
qualified name.
.. note:: This function actually imports the module to check its existence.
Therefore you need to mock 3rd party modules if needed before
calling this function.
"""
parts = name.split('.')
for i, _part in enumerate(parts, 1):
try:
modname = '.'.join(parts[:i])
importlib.import_module(modname)
except ImportError:
if parts[: i - 1]:
return '.'.join(parts[: i - 1]), '.'.join(parts[i - 1 :])
else:
return None, '.'.join(parts)
except IndexError:
pass
return name, ''
| _split_full_qualified_name |
sphinx | 10 | sphinx/application.py | def add_autodocumenter(self, cls: type[Documenter], override: bool = False) -> None:
"""Register a new documenter class for the autodoc extension.
Add *cls* as a new documenter class for the :mod:`sphinx.ext.autodoc`
extension. It must be a subclass of
:class:`sphinx.ext.autodoc.Documenter`. This allows auto-documenting
new types of objects. See the source of the autodoc module for
examples on how to subclass :class:`~sphinx.ext.autodoc.Documenter`.
If *override* is True, the given *cls* is forcedly installed even if
a documenter having the same name is already installed.
See :ref:`autodoc_ext_tutorial`.
.. versionadded:: 0.6
.. versionchanged:: 2.2
Add *override* keyword.
"""
| /usr/src/app/target_test_cases/failed_tests_add_autodocumenter.txt | def add_autodocumenter(self, cls: type[Documenter], override: bool = False) -> None:
"""Register a new documenter class for the autodoc extension.
Add *cls* as a new documenter class for the :mod:`sphinx.ext.autodoc`
extension. It must be a subclass of
:class:`sphinx.ext.autodoc.Documenter`. This allows auto-documenting
new types of objects. See the source of the autodoc module for
examples on how to subclass :class:`~sphinx.ext.autodoc.Documenter`.
If *override* is True, the given *cls* is forcedly installed even if
a documenter having the same name is already installed.
See :ref:`autodoc_ext_tutorial`.
.. versionadded:: 0.6
.. versionchanged:: 2.2
Add *override* keyword.
"""
logger.debug('[app] adding autodocumenter: %r', cls)
from sphinx.ext.autodoc.directive import AutodocDirective
self.registry.add_documenter(cls.objtype, cls)
self.add_directive('auto' + cls.objtype, AutodocDirective, override=override)
| add_autodocumenter |
sphinx | 11 | sphinx/application.py | def add_crossref_type(
self, directivename: str, rolename: str, indextemplate: str = '',
ref_nodeclass: type[nodes.TextElement] | None = None, objname: str = '',
override: bool = False,
) -> None:
"""Register a new crossref object type.
This method is very similar to :meth:`~Sphinx.add_object_type` except that the
directive it generates must be empty, and will produce no output.
That means that you can add semantic targets to your sources, and refer
to them using custom roles instead of generic ones (like
:rst:role:`ref`). Example call::
app.add_crossref_type('topic', 'topic', 'single: %s',
docutils.nodes.emphasis)
Example usage::
.. topic:: application API
The application API
-------------------
Some random text here.
See also :topic:`this section <application API>`.
(Of course, the element following the ``topic`` directive needn't be a
section.)
:param override: If false, do not install it if another cross-reference type
is already installed as the same name
If true, unconditionally install the cross-reference type.
.. versionchanged:: 1.8
Add *override* keyword.
"""
| /usr/src/app/target_test_cases/failed_tests_add_crossref_type.txt | def add_crossref_type(
self, directivename: str, rolename: str, indextemplate: str = '',
ref_nodeclass: type[nodes.TextElement] | None = None, objname: str = '',
override: bool = False,
) -> None:
"""Register a new crossref object type.
This method is very similar to :meth:`~Sphinx.add_object_type` except that the
directive it generates must be empty, and will produce no output.
That means that you can add semantic targets to your sources, and refer
to them using custom roles instead of generic ones (like
:rst:role:`ref`). Example call::
app.add_crossref_type('topic', 'topic', 'single: %s',
docutils.nodes.emphasis)
Example usage::
.. topic:: application API
The application API
-------------------
Some random text here.
See also :topic:`this section <application API>`.
(Of course, the element following the ``topic`` directive needn't be a
section.)
:param override: If false, do not install it if another cross-reference type
is already installed as the same name
If true, unconditionally install the cross-reference type.
.. versionchanged:: 1.8
Add *override* keyword.
"""
self.registry.add_crossref_type(directivename, rolename,
indextemplate, ref_nodeclass, objname,
override=override)
| add_crossref_type |
sphinx | 12 | sphinx/application.py | def add_directive(self, name: str, cls: type[Directive], override: bool = False) -> None:
"""Register a Docutils directive.
:param name: The name of the directive
:param cls: A directive class
:param override: If false, do not install it if another directive
is already installed as the same name
If true, unconditionally install the directive.
For example, a custom directive named ``my-directive`` would be added
like this:
.. code-block:: python
from docutils.parsers.rst import Directive, directives
class MyDirective(Directive):
has_content = True
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {
'class': directives.class_option,
'name': directives.unchanged,
}
def run(self):
...
def setup(app):
app.add_directive('my-directive', MyDirective)
For more details, see `the Docutils docs
<https://docutils.sourceforge.io/docs/howto/rst-directives.html>`__ .
.. versionchanged:: 0.6
Docutils 0.5-style directive classes are now supported.
.. deprecated:: 1.8
Docutils 0.4-style (function based) directives support is deprecated.
.. versionchanged:: 1.8
Add *override* keyword.
"""
| /usr/src/app/target_test_cases/failed_tests_add_directive.txt | def add_directive(self, name: str, cls: type[Directive], override: bool = False) -> None:
"""Register a Docutils directive.
:param name: The name of the directive
:param cls: A directive class
:param override: If false, do not install it if another directive
is already installed as the same name
If true, unconditionally install the directive.
For example, a custom directive named ``my-directive`` would be added
like this:
.. code-block:: python
from docutils.parsers.rst import Directive, directives
class MyDirective(Directive):
has_content = True
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {
'class': directives.class_option,
'name': directives.unchanged,
}
def run(self):
...
def setup(app):
app.add_directive('my-directive', MyDirective)
For more details, see `the Docutils docs
<https://docutils.sourceforge.io/docs/howto/rst-directives.html>`__ .
.. versionchanged:: 0.6
Docutils 0.5-style directive classes are now supported.
.. deprecated:: 1.8
Docutils 0.4-style (function based) directives support is deprecated.
.. versionchanged:: 1.8
Add *override* keyword.
"""
logger.debug('[app] adding directive: %r', (name, cls))
if not override and docutils.is_directive_registered(name):
logger.warning(__('directive %r is already registered, it will be overridden'),
name, type='app', subtype='add_directive')
docutils.register_directive(name, cls)
| add_directive |
sphinx | 13 | sphinx/application.py | def add_js_file(self, filename: str | None, priority: int = 500,
loading_method: str | None = None, **kwargs: Any) -> None:
"""Register a JavaScript file to include in the HTML output.
:param filename: The name of a JavaScript file that the default HTML
template will include. It must be relative to the HTML
static path, or a full URI with scheme, or ``None`` .
The ``None`` value is used to create an inline
``<script>`` tag. See the description of *kwargs*
below.
:param priority: Files are included in ascending order of priority. If
multiple JavaScript files have the same priority,
those files will be included in order of registration.
See list of "priority range for JavaScript files" below.
:param loading_method: The loading method for the JavaScript file.
Either ``'async'`` or ``'defer'`` are allowed.
:param kwargs: Extra keyword arguments are included as attributes of the
``<script>`` tag. If the special keyword argument
``body`` is given, its value will be added as the content
of the ``<script>`` tag.
Example::
app.add_js_file('example.js')
# => <script src="_static/example.js"></script>
app.add_js_file('example.js', loading_method="async")
# => <script src="_static/example.js" async="async"></script>
app.add_js_file(None, body="var myVariable = 'foo';")
# => <script>var myVariable = 'foo';</script>
.. list-table:: priority range for JavaScript files
:widths: 20,80
* - Priority
- Main purpose in Sphinx
* - 200
- default priority for built-in JavaScript files
* - 500
- default priority for extensions
* - 800
- default priority for :confval:`html_js_files`
A JavaScript file can be added to the specific HTML page when an extension
calls this method on :event:`html-page-context` event.
.. versionadded:: 0.5
.. versionchanged:: 1.8
Renamed from ``app.add_javascript()``.
And it allows keyword arguments as attributes of script tag.
.. versionchanged:: 3.5
Take priority argument. Allow to add a JavaScript file to the specific page.
.. versionchanged:: 4.4
Take loading_method argument. Allow to change the loading method of the
JavaScript file.
"""
| /usr/src/app/target_test_cases/failed_tests_add_js_file.txt | def add_js_file(self, filename: str | None, priority: int = 500,
loading_method: str | None = None, **kwargs: Any) -> None:
"""Register a JavaScript file to include in the HTML output.
:param filename: The name of a JavaScript file that the default HTML
template will include. It must be relative to the HTML
static path, or a full URI with scheme, or ``None`` .
The ``None`` value is used to create an inline
``<script>`` tag. See the description of *kwargs*
below.
:param priority: Files are included in ascending order of priority. If
multiple JavaScript files have the same priority,
those files will be included in order of registration.
See list of "priority range for JavaScript files" below.
:param loading_method: The loading method for the JavaScript file.
Either ``'async'`` or ``'defer'`` are allowed.
:param kwargs: Extra keyword arguments are included as attributes of the
``<script>`` tag. If the special keyword argument
``body`` is given, its value will be added as the content
of the ``<script>`` tag.
Example::
app.add_js_file('example.js')
# => <script src="_static/example.js"></script>
app.add_js_file('example.js', loading_method="async")
# => <script src="_static/example.js" async="async"></script>
app.add_js_file(None, body="var myVariable = 'foo';")
# => <script>var myVariable = 'foo';</script>
.. list-table:: priority range for JavaScript files
:widths: 20,80
* - Priority
- Main purpose in Sphinx
* - 200
- default priority for built-in JavaScript files
* - 500
- default priority for extensions
* - 800
- default priority for :confval:`html_js_files`
A JavaScript file can be added to the specific HTML page when an extension
calls this method on :event:`html-page-context` event.
.. versionadded:: 0.5
.. versionchanged:: 1.8
Renamed from ``app.add_javascript()``.
And it allows keyword arguments as attributes of script tag.
.. versionchanged:: 3.5
Take priority argument. Allow to add a JavaScript file to the specific page.
.. versionchanged:: 4.4
Take loading_method argument. Allow to change the loading method of the
JavaScript file.
"""
if loading_method == 'async':
kwargs['async'] = 'async'
elif loading_method == 'defer':
kwargs['defer'] = 'defer'
self.registry.add_js_file(filename, priority=priority, **kwargs)
with contextlib.suppress(AttributeError):
self.builder.add_js_file( # type: ignore[attr-defined]
filename, priority=priority, **kwargs,
)
| add_js_file |
sphinx | 14 | sphinx/application.py | def add_node(self, node: type[Element], override: bool = False,
**kwargs: tuple[Callable, Callable | None]) -> None:
"""Register a Docutils node class.
This is necessary for Docutils internals. It may also be used in the
future to validate nodes in the parsed documents.
:param node: A node class
:param kwargs: Visitor functions for each builder (see below)
:param override: If true, install the node forcedly even if another node is already
installed as the same name
Node visitor functions for the Sphinx HTML, LaTeX, text and manpage
writers can be given as keyword arguments: the keyword should be one or
more of ``'html'``, ``'latex'``, ``'text'``, ``'man'``, ``'texinfo'``
or any other supported translators, the value a 2-tuple of ``(visit,
depart)`` methods. ``depart`` can be ``None`` if the ``visit``
function raises :exc:`docutils.nodes.SkipNode`. Example:
.. code-block:: python
class math(docutils.nodes.Element): pass
def visit_math_html(self, node):
self.body.append(self.starttag(node, 'math'))
def depart_math_html(self, node):
self.body.append('</math>')
app.add_node(math, html=(visit_math_html, depart_math_html))
Obviously, translators for which you don't specify visitor methods will
choke on the node when encountered in a document to translate.
.. versionchanged:: 0.5
Added the support for keyword arguments giving visit functions.
"""
| /usr/src/app/target_test_cases/failed_tests_add_node.txt | def add_node(self, node: type[Element], override: bool = False,
**kwargs: tuple[Callable, Callable | None]) -> None:
"""Register a Docutils node class.
This is necessary for Docutils internals. It may also be used in the
future to validate nodes in the parsed documents.
:param node: A node class
:param kwargs: Visitor functions for each builder (see below)
:param override: If true, install the node forcedly even if another node is already
installed as the same name
Node visitor functions for the Sphinx HTML, LaTeX, text and manpage
writers can be given as keyword arguments: the keyword should be one or
more of ``'html'``, ``'latex'``, ``'text'``, ``'man'``, ``'texinfo'``
or any other supported translators, the value a 2-tuple of ``(visit,
depart)`` methods. ``depart`` can be ``None`` if the ``visit``
function raises :exc:`docutils.nodes.SkipNode`. Example:
.. code-block:: python
class math(docutils.nodes.Element): pass
def visit_math_html(self, node):
self.body.append(self.starttag(node, 'math'))
def depart_math_html(self, node):
self.body.append('</math>')
app.add_node(math, html=(visit_math_html, depart_math_html))
Obviously, translators for which you don't specify visitor methods will
choke on the node when encountered in a document to translate.
.. versionchanged:: 0.5
Added the support for keyword arguments giving visit functions.
"""
logger.debug('[app] adding node: %r', (node, kwargs))
if not override and docutils.is_node_registered(node):
logger.warning(__('node class %r is already registered, '
'its visitors will be overridden'),
node.__name__, type='app', subtype='add_node')
docutils.register_node(node)
self.registry.add_translation_handlers(node, **kwargs)
| add_node |
sphinx | 15 | sphinx/application.py | def add_object_type(self, directivename: str, rolename: str, indextemplate: str = '',
parse_node: Callable | None = None,
ref_nodeclass: type[nodes.TextElement] | None = None,
objname: str = '', doc_field_types: Sequence = (),
override: bool = False,
) -> None:
"""Register a new object type.
This method is a very convenient way to add a new :term:`object` type
that can be cross-referenced. It will do this:
- Create a new directive (called *directivename*) for documenting an
object. It will automatically add index entries if *indextemplate*
is nonempty; if given, it must contain exactly one instance of
``%s``. See the example below for how the template will be
interpreted.
- Create a new role (called *rolename*) to cross-reference to these
object descriptions.
- If you provide *parse_node*, it must be a function that takes a
string and a docutils node, and it must populate the node with
children parsed from the string. It must then return the name of the
item to be used in cross-referencing and index entries. See the
:file:`conf.py` file in the source for this documentation for an
example.
- The *objname* (if not given, will default to *directivename*) names
the type of object. It is used when listing objects, e.g. in search
results.
For example, if you have this call in a custom Sphinx extension::
app.add_object_type('directive', 'dir', 'pair: %s; directive')
you can use this markup in your documents::
.. rst:directive:: function
Document a function.
<...>
See also the :rst:dir:`function` directive.
For the directive, an index entry will be generated as if you had prepended ::
.. index:: pair: function; directive
The reference node will be of class ``literal`` (so it will be rendered
in a proportional font, as appropriate for code) unless you give the
*ref_nodeclass* argument, which must be a docutils node class. Most
useful are ``docutils.nodes.emphasis`` or ``docutils.nodes.strong`` --
you can also use ``docutils.nodes.generated`` if you want no further
text decoration. If the text should be treated as literal (e.g. no
smart quote replacement), but not have typewriter styling, use
``sphinx.addnodes.literal_emphasis`` or
``sphinx.addnodes.literal_strong``.
For the role content, you have the same syntactical possibilities as
for standard Sphinx roles (see :ref:`xref-syntax`).
If *override* is True, the given object_type is forcedly installed even if
an object_type having the same name is already installed.
.. versionchanged:: 1.8
Add *override* keyword.
"""
| /usr/src/app/target_test_cases/failed_tests_add_object_type.txt | def add_object_type(self, directivename: str, rolename: str, indextemplate: str = '',
parse_node: Callable | None = None,
ref_nodeclass: type[nodes.TextElement] | None = None,
objname: str = '', doc_field_types: Sequence = (),
override: bool = False,
) -> None:
"""Register a new object type.
This method is a very convenient way to add a new :term:`object` type
that can be cross-referenced. It will do this:
- Create a new directive (called *directivename*) for documenting an
object. It will automatically add index entries if *indextemplate*
is nonempty; if given, it must contain exactly one instance of
``%s``. See the example below for how the template will be
interpreted.
- Create a new role (called *rolename*) to cross-reference to these
object descriptions.
- If you provide *parse_node*, it must be a function that takes a
string and a docutils node, and it must populate the node with
children parsed from the string. It must then return the name of the
item to be used in cross-referencing and index entries. See the
:file:`conf.py` file in the source for this documentation for an
example.
- The *objname* (if not given, will default to *directivename*) names
the type of object. It is used when listing objects, e.g. in search
results.
For example, if you have this call in a custom Sphinx extension::
app.add_object_type('directive', 'dir', 'pair: %s; directive')
you can use this markup in your documents::
.. rst:directive:: function
Document a function.
<...>
See also the :rst:dir:`function` directive.
For the directive, an index entry will be generated as if you had prepended ::
.. index:: pair: function; directive
The reference node will be of class ``literal`` (so it will be rendered
in a proportional font, as appropriate for code) unless you give the
*ref_nodeclass* argument, which must be a docutils node class. Most
useful are ``docutils.nodes.emphasis`` or ``docutils.nodes.strong`` --
you can also use ``docutils.nodes.generated`` if you want no further
text decoration. If the text should be treated as literal (e.g. no
smart quote replacement), but not have typewriter styling, use
``sphinx.addnodes.literal_emphasis`` or
``sphinx.addnodes.literal_strong``.
For the role content, you have the same syntactical possibilities as
for standard Sphinx roles (see :ref:`xref-syntax`).
If *override* is True, the given object_type is forcedly installed even if
an object_type having the same name is already installed.
.. versionchanged:: 1.8
Add *override* keyword.
"""
self.registry.add_object_type(directivename, rolename, indextemplate, parse_node,
ref_nodeclass, objname, doc_field_types,
override=override)
| add_object_type |
sphinx | 16 | sphinx/application.py | def add_role(self, name: str, role: Any, override: bool = False) -> None:
"""Register a Docutils role.
:param name: The name of role
:param role: A role function
:param override: If false, do not install it if another role
is already installed as the same name
If true, unconditionally install the role.
For more details about role functions, see `the Docutils docs
<https://docutils.sourceforge.io/docs/howto/rst-roles.html>`__ .
.. versionchanged:: 1.8
Add *override* keyword.
"""
| /usr/src/app/target_test_cases/failed_tests_add_role.txt | def add_role(self, name: str, role: Any, override: bool = False) -> None:
"""Register a Docutils role.
:param name: The name of role
:param role: A role function
:param override: If false, do not install it if another role
is already installed as the same name
If true, unconditionally install the role.
For more details about role functions, see `the Docutils docs
<https://docutils.sourceforge.io/docs/howto/rst-roles.html>`__ .
.. versionchanged:: 1.8
Add *override* keyword.
"""
logger.debug('[app] adding role: %r', (name, role))
if not override and docutils.is_role_registered(name):
logger.warning(__('role %r is already registered, it will be overridden'),
name, type='app', subtype='add_role')
docutils.register_role(name, role)
| add_role |
sphinx | 17 | sphinx/cmd/quickstart.py | def ask_user(d: dict[str, Any]) -> None:
"""Ask the user for quickstart values missing from *d*.
Values are:
* path: root path
* sep: separate source and build dirs (bool)
* dot: replacement for dot in _templates etc.
* project: project name
* author: author names
* version: version of project
* release: release of project
* language: document language
* suffix: source file suffix
* master: master document name
* extensions: extensions to use (list)
* makefile: make Makefile
* batchfile: make command file
"""
| /usr/src/app/target_test_cases/failed_tests_ask_user.txt | def ask_user(d: dict[str, Any]) -> None:
"""Ask the user for quickstart values missing from *d*.
Values are:
* path: root path
* sep: separate source and build dirs (bool)
* dot: replacement for dot in _templates etc.
* project: project name
* author: author names
* version: version of project
* release: release of project
* language: document language
* suffix: source file suffix
* master: master document name
* extensions: extensions to use (list)
* makefile: make Makefile
* batchfile: make command file
"""
print(bold(__('Welcome to the Sphinx %s quickstart utility.')) % __display_version__)
print()
print(__('Please enter values for the following settings (just press Enter to\n'
'accept a default value, if one is given in brackets).'))
if 'path' in d:
print()
print(bold(__('Selected root path: %s')) % d['path'])
else:
print()
print(__('Enter the root path for documentation.'))
d['path'] = do_prompt(__('Root path for the documentation'), '.', is_path)
while path.isfile(path.join(d['path'], 'conf.py')) or \
path.isfile(path.join(d['path'], 'source', 'conf.py')):
print()
print(bold(__('Error: an existing conf.py has been found in the '
'selected root path.')))
print(__('sphinx-quickstart will not overwrite existing Sphinx projects.'))
print()
d['path'] = do_prompt(__('Please enter a new root path (or just Enter to exit)'),
'', is_path_or_empty)
if not d['path']:
raise SystemExit(1)
if 'sep' not in d:
print()
print(__('You have two options for placing the build directory for Sphinx output.\n'
'Either, you use a directory "_build" within the root path, or you separate\n'
'"source" and "build" directories within the root path.'))
d['sep'] = do_prompt(__('Separate source and build directories (y/n)'), 'n', boolean)
if 'dot' not in d:
print()
print(__('Inside the root directory, two more directories will be created; "_templates"\n' # NoQA: E501
'for custom HTML templates and "_static" for custom stylesheets and other static\n' # NoQA: E501
'files. You can enter another prefix (such as ".") to replace the underscore.')) # NoQA: E501
d['dot'] = do_prompt(__('Name prefix for templates and static dir'), '_', ok)
if 'project' not in d:
print()
print(__('The project name will occur in several places in the built documentation.'))
d['project'] = do_prompt(__('Project name'))
if 'author' not in d:
d['author'] = do_prompt(__('Author name(s)'))
if 'version' not in d:
print()
print(__('Sphinx has the notion of a "version" and a "release" for the\n'
'software. Each version can have multiple releases. For example, for\n'
'Python the version is something like 2.5 or 3.0, while the release is\n'
"something like 2.5.1 or 3.0a1. If you don't need this dual structure,\n"
'just set both to the same value.'))
d['version'] = do_prompt(__('Project version'), '', allow_empty)
if 'release' not in d:
d['release'] = do_prompt(__('Project release'), d['version'], allow_empty)
if 'language' not in d:
print()
print(__(
'If the documents are to be written in a language other than English,\n'
'you can select a language here by its language code. Sphinx will then\n'
'translate text that it generates into that language.\n'
'\n'
'For a list of supported codes, see\n'
'https://www.sphinx-doc.org/en/master/usage/configuration.html#confval-language.',
))
d['language'] = do_prompt(__('Project language'), 'en')
if d['language'] == 'en':
d['language'] = None
if 'suffix' not in d:
print()
print(__('The file name suffix for source files. Commonly, this is either ".txt"\n'
'or ".rst". Only files with this suffix are considered documents.'))
d['suffix'] = do_prompt(__('Source file suffix'), '.rst', suffix)
if 'master' not in d:
print()
print(__('One document is special in that it is considered the top node of the\n'
'"contents tree", that is, it is the root of the hierarchical structure\n'
'of the documents. Normally, this is "index", but if your "index"\n'
'document is a custom template, you can also set this to another filename.'))
d['master'] = do_prompt(__('Name of your master document (without suffix)'), 'index')
while path.isfile(path.join(d['path'], d['master'] + d['suffix'])) or \
path.isfile(path.join(d['path'], 'source', d['master'] + d['suffix'])):
print()
print(bold(__('Error: the master file %s has already been found in the '
'selected root path.') % (d['master'] + d['suffix'])))
print(__('sphinx-quickstart will not overwrite the existing file.'))
print()
d['master'] = do_prompt(__('Please enter a new file name, or rename the '
'existing file and press Enter'), d['master'])
if 'extensions' not in d:
print(__('Indicate which of the following Sphinx extensions should be enabled:'))
d['extensions'] = []
for name, description in EXTENSIONS.items():
if do_prompt(f'{name}: {description} (y/n)', 'n', boolean):
d['extensions'].append('sphinx.ext.%s' % name)
# Handle conflicting options
if {'sphinx.ext.imgmath', 'sphinx.ext.mathjax'}.issubset(d['extensions']):
print(__('Note: imgmath and mathjax cannot be enabled at the same time. '
'imgmath has been deselected.'))
d['extensions'].remove('sphinx.ext.imgmath')
if 'makefile' not in d:
print()
print(__('A Makefile and a Windows command file can be generated for you so that you\n'
"only have to run e.g. `make html' instead of invoking sphinx-build\n"
'directly.'))
d['makefile'] = do_prompt(__('Create Makefile? (y/n)'), 'y', boolean)
if 'batchfile' not in d:
d['batchfile'] = do_prompt(__('Create Windows command file? (y/n)'), 'y', boolean)
print()
| ask_user |