language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 538784, "end": 540018 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("contributions", "repository") contributions = sgqlc.types.Field( sgqlc.types.non_null(CreatedPullRequestReviewContributionConnection), graphql_name="contributions", args=sgqlc.types.ArgDict( ( ("after", sgqlc.types.Arg(String, graphql_name="after", default=None)), ( "before", sgqlc.types.Arg(String, graphql_name="before", default=None), ), ("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)), ("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)), ( "order_by", sgqlc.types.Arg( ContributionOrder, graphql_name="orderBy", default={"direction": "DESC"}, ), ), ) ), ) repository = sgqlc.types.Field( sgqlc.types.non_null("Repository"), graphql_name="repository" )
PullRequestReviewContributionsByRepository
python
hyperopt__hyperopt
hyperopt/tests/unit/test_randint.py
{ "start": 780, "end": 3332 }
class ____(unittest.TestCase): # test that that a space with a randint in it is # (a) accepted for each algo (random, tpe) # and # (b) handled correctly in fmin, finding the solution in the constrained space # def setUp(self): self.space = hp.randint("t", 2, 100) self.trials = Trials() def objective(self, a): # an objective function with roots at 3, 10, 50 return abs(np.poly1d([1, -63, 680, -1500])(a)) def test_random_runs(self): max_evals = 150 fmin( self.objective, space=self.space, trials=self.trials, algo=rand.suggest, rstate=np.random.default_rng(4), max_evals=max_evals, ) values = [t["misc"]["vals"]["t"][0] for t in self.trials.trials] counts = np.bincount(values, minlength=100) assert counts[:2].sum() == 0 def test_tpe_runs(self): max_evals = 100 fmin( self.objective, space=self.space, trials=self.trials, algo=partial(tpe.suggest, n_startup_jobs=10), rstate=np.random.default_rng(4), max_evals=max_evals, ) values = [t["misc"]["vals"]["t"][0] for t in self.trials.trials] counts = np.bincount(values, minlength=100) assert counts[:2].sum() == 0 def test_random_finds_constrained_solution(self): max_evals = 150 # (2, 7), (2, 30), (2, 100), (5, 30), (5, 100), (20, 100) for lower, upper in zip([2, 2, 2, 5, 5, 20], [7, 30, 100, 30, 100, 100]): best = fmin( self.objective, space=hp.randint("t", lower, upper), algo=rand.suggest, rstate=np.random.default_rng(4), max_evals=max_evals, ) expected = [i for i in [3, 10, 50] if lower <= i < upper] assert best["t"] in expected def test_tpe_finds_constrained_solution(self): max_evals = 150 # (2, 7), (2, 30), (2, 100), (5, 30), (5, 100), (20, 100) for lower, upper in zip([2, 2, 2, 5, 5, 20], [7, 30, 100, 30, 100, 100]): best = fmin( self.objective, space=hp.randint("t", lower, upper), algo=tpe.suggest, rstate=np.random.default_rng(4), max_evals=max_evals, ) expected = [i for i in [3, 10, 50] if lower <= i < upper] assert best["t"] in expected
TestSimpleFMin
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_bigtable.py
{ "start": 31207, "end": 39085 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.bigtable.BigtableHook") def test_create_execute(self, mock_hook): op = BigtableCreateTableOperator( project_id=PROJECT_ID, instance_id=INSTANCE_ID, table_id=TABLE_ID, initial_split_keys=INITIAL_SPLIT_KEYS, column_families=EMPTY_COLUMN_FAMILIES, task_id="id", gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) instance = mock_hook.return_value.get_instance.return_value = mock.Mock(Instance) op.execute(context={"ti": mock.MagicMock(), "task": mock.MagicMock()}) mock_hook.assert_called_once_with( gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) mock_hook.return_value.create_table.assert_called_once_with( instance=instance, table_id=TABLE_ID, initial_split_keys=INITIAL_SPLIT_KEYS, column_families=EMPTY_COLUMN_FAMILIES, ) @pytest.mark.parametrize( ("missing_attribute", "project_id", "instance_id", "table_id"), [ ("instance_id", PROJECT_ID, "", TABLE_ID), ("table_id", PROJECT_ID, INSTANCE_ID, ""), ], ) @mock.patch("airflow.providers.google.cloud.operators.bigtable.BigtableHook") def test_empty_attribute(self, mock_hook, missing_attribute, project_id, instance_id, table_id): with pytest.raises(AirflowException) as ctx: BigtableCreateTableOperator( project_id=project_id, instance_id=instance_id, table_id=table_id, task_id="id", gcp_conn_id=GCP_CONN_ID, ) err = ctx.value assert str(err) == f"Empty parameter: {missing_attribute}" mock_hook.assert_not_called() @mock.patch("airflow.providers.google.cloud.operators.bigtable.BigtableHook") def test_instance_not_exists(self, mock_hook): op = BigtableCreateTableOperator( project_id=PROJECT_ID, instance_id=INSTANCE_ID, table_id=TABLE_ID, initial_split_keys=INITIAL_SPLIT_KEYS, column_families=EMPTY_COLUMN_FAMILIES, task_id="id", gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) mock_hook.return_value.get_instance.return_value = None with pytest.raises(AirflowException) as ctx: op.execute(None) err = ctx.value assert str(err) == f"Dependency: instance '{INSTANCE_ID}' does not exist in project '{PROJECT_ID}'." mock_hook.assert_called_once_with( gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) @mock.patch("airflow.providers.google.cloud.operators.bigtable.BigtableHook") def test_creating_table_that_exists(self, mock_hook): op = BigtableCreateTableOperator( project_id=PROJECT_ID, instance_id=INSTANCE_ID, table_id=TABLE_ID, initial_split_keys=INITIAL_SPLIT_KEYS, column_families=EMPTY_COLUMN_FAMILIES, task_id="id", gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) mock_hook.return_value.get_column_families_for_table.return_value = EMPTY_COLUMN_FAMILIES instance = mock_hook.return_value.get_instance.return_value = mock.Mock(Instance) mock_hook.return_value.create_table.side_effect = mock.Mock( side_effect=google.api_core.exceptions.AlreadyExists("Table already exists.") ) op.execute(None) mock_hook.assert_called_once_with( gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) mock_hook.return_value.create_table.assert_called_once_with( instance=instance, table_id=TABLE_ID, initial_split_keys=INITIAL_SPLIT_KEYS, column_families=EMPTY_COLUMN_FAMILIES, ) @mock.patch("airflow.providers.google.cloud.operators.bigtable.BigtableHook") def test_creating_table_that_exists_empty_project_id(self, mock_hook): op = BigtableCreateTableOperator( instance_id=INSTANCE_ID, table_id=TABLE_ID, initial_split_keys=INITIAL_SPLIT_KEYS, column_families=EMPTY_COLUMN_FAMILIES, task_id="id", gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) mock_hook.return_value.get_column_families_for_table.return_value = EMPTY_COLUMN_FAMILIES instance = mock_hook.return_value.get_instance.return_value = mock.Mock(Instance) mock_hook.return_value.create_table.side_effect = mock.Mock( side_effect=google.api_core.exceptions.AlreadyExists("Table already exists.") ) op.execute(None) mock_hook.assert_called_once_with( gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) mock_hook.return_value.create_table.assert_called_once_with( instance=instance, table_id=TABLE_ID, initial_split_keys=INITIAL_SPLIT_KEYS, column_families=EMPTY_COLUMN_FAMILIES, ) @mock.patch("airflow.providers.google.cloud.operators.bigtable.BigtableHook") def test_creating_table_that_exists_with_different_column_families_ids_in_the_table(self, mock_hook): op = BigtableCreateTableOperator( project_id=PROJECT_ID, instance_id=INSTANCE_ID, table_id=TABLE_ID, initial_split_keys=INITIAL_SPLIT_KEYS, column_families=EMPTY_COLUMN_FAMILIES, task_id="id", gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) mock_hook.return_value.get_column_families_for_table.return_value = {"existing_family": None} mock_hook.return_value.create_table.side_effect = mock.Mock( side_effect=google.api_core.exceptions.AlreadyExists("Table already exists.") ) with pytest.raises(AirflowException) as ctx: op.execute(None) err = ctx.value assert str(err) == f"Table '{TABLE_ID}' already exists with different Column Families." mock_hook.assert_called_once_with( gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) @mock.patch("airflow.providers.google.cloud.operators.bigtable.BigtableHook") def test_creating_table_that_exists_with_different_column_families_gc_rule_in__table(self, mock_hook): op = BigtableCreateTableOperator( project_id=PROJECT_ID, instance_id=INSTANCE_ID, table_id=TABLE_ID, initial_split_keys=INITIAL_SPLIT_KEYS, column_families={"cf-id": MaxVersionsGCRule(1)}, task_id="id", gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) cf_mock = mock.Mock() cf_mock.gc_rule = mock.Mock(return_value=MaxVersionsGCRule(2)) mock_hook.return_value.get_column_families_for_table.return_value = {"cf-id": cf_mock} mock_hook.return_value.create_table.side_effect = mock.Mock( side_effect=google.api_core.exceptions.AlreadyExists("Table already exists.") ) with pytest.raises(AirflowException) as ctx: op.execute(None) err = ctx.value assert str(err) == f"Table '{TABLE_ID}' already exists with different Column Families." mock_hook.assert_called_once_with( gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, )
TestBigtableTableCreate
python
pyparsing__pyparsing
tests/test_simple_unit.py
{ "start": 6300, "end": 7036 }
class ____(PyparsingExpressionTestCase): tests = [ PyparsingTest( desc="Parsing real numbers - fail, parsed numbers are in pieces", expr=(pp.Word(pp.nums) + "." + pp.Word(pp.nums))[...], text="1.2 2.3 3.1416 98.6", # fmt: off expected_list=["1", ".", "2", "2", ".", "3", "3", ".", "1416", "98", ".", "6"], # fmt: on ), PyparsingTest( desc="Parsing real numbers - better, use Combine to combine multiple tokens into one", expr=pp.Combine(pp.Word(pp.nums) + "." + pp.Word(pp.nums))[...], text="1.2 2.3 3.1416 98.6", expected_list=["1.2", "2.3", "3.1416", "98.6"], ), ]
TestCombine
python
django__django
tests/utils_tests/test_os_utils.py
{ "start": 846, "end": 1207 }
class ____(unittest.TestCase): def test_to_path(self): for path in ("/tmp/some_file.txt", Path("/tmp/some_file.txt")): with self.subTest(path): self.assertEqual(to_path(path), Path("/tmp/some_file.txt")) def test_to_path_invalid_value(self): with self.assertRaises(TypeError): to_path(42)
ToPathTests
python
doocs__leetcode
solution/1200-1299/1238.Circular Permutation in Binary Representation/Solution2.py
{ "start": 0, "end": 145 }
class ____: def circularPermutation(self, n: int, start: int) -> List[int]: return [i ^ (i >> 1) ^ start for i in range(1 << n)]
Solution
python
django__django
tests/basic/tests.py
{ "start": 1006, "end": 8265 }
class ____(TestCase): def test_object_is_not_written_to_database_until_save_was_called(self): a = Article( id=None, headline="Parrot programs in Python", pub_date=datetime(2005, 7, 28), ) self.assertIsNone(a.id) self.assertEqual(Article.objects.count(), 0) # Save it into the database. You have to call save() explicitly. a.save() self.assertIsNotNone(a.id) self.assertEqual(Article.objects.count(), 1) def test_can_initialize_model_instance_using_positional_arguments(self): """ You can initialize a model instance using positional arguments, which should match the field order as defined in the model. """ a = Article(None, "Second article", datetime(2005, 7, 29)) a.save() self.assertEqual(a.headline, "Second article") self.assertEqual(a.pub_date, datetime(2005, 7, 29, 0, 0)) def test_can_create_instance_using_kwargs(self): a = Article( id=None, headline="Third article", pub_date=datetime(2005, 7, 30), ) a.save() self.assertEqual(a.headline, "Third article") self.assertEqual(a.pub_date, datetime(2005, 7, 30, 0, 0)) def test_autofields_generate_different_values_for_each_instance(self): a1 = Article.objects.create( headline="First", pub_date=datetime(2005, 7, 30, 0, 0) ) a2 = Article.objects.create( headline="First", pub_date=datetime(2005, 7, 30, 0, 0) ) a3 = Article.objects.create( headline="First", pub_date=datetime(2005, 7, 30, 0, 0) ) self.assertNotEqual(a3.id, a1.id) self.assertNotEqual(a3.id, a2.id) def test_can_mix_and_match_position_and_kwargs(self): # You can also mix and match position and keyword arguments, but # be sure not to duplicate field information. a = Article(None, "Fourth article", pub_date=datetime(2005, 7, 31)) a.save() self.assertEqual(a.headline, "Fourth article") def test_positional_and_keyword_args_for_the_same_field(self): msg = "Article() got both positional and keyword arguments for field '%s'." with self.assertRaisesMessage(TypeError, msg % "headline"): Article(None, "Fifth article", headline="Other headline.") with self.assertRaisesMessage(TypeError, msg % "headline"): Article(None, "Sixth article", headline="") with self.assertRaisesMessage(TypeError, msg % "pub_date"): Article(None, "Seventh article", datetime(2021, 3, 1), pub_date=None) def test_cannot_create_instance_with_invalid_kwargs(self): msg = "Article() got unexpected keyword arguments: 'foo'" with self.assertRaisesMessage(TypeError, msg): Article( id=None, headline="Some headline", pub_date=datetime(2005, 7, 31), foo="bar", ) msg = "Article() got unexpected keyword arguments: 'foo', 'bar'" with self.assertRaisesMessage(TypeError, msg): Article( id=None, headline="Some headline", pub_date=datetime(2005, 7, 31), foo="bar", bar="baz", ) def test_can_leave_off_value_for_autofield_and_it_gets_value_on_save(self): """ You can leave off the value for an AutoField when creating an object, because it'll get filled in automatically when you save(). """ a = Article(headline="Article 5", pub_date=datetime(2005, 7, 31)) a.save() self.assertEqual(a.headline, "Article 5") self.assertIsNotNone(a.id) def test_leaving_off_a_field_with_default_set_the_default_will_be_saved(self): a = Article(pub_date=datetime(2005, 7, 31)) a.save() self.assertEqual(a.headline, "Default headline") def test_for_datetimefields_saves_as_much_precision_as_was_given(self): """as much precision in *seconds*""" a1 = Article( headline="Article 7", pub_date=datetime(2005, 7, 31, 12, 30), ) a1.save() self.assertEqual( Article.objects.get(id__exact=a1.id).pub_date, datetime(2005, 7, 31, 12, 30) ) a2 = Article( headline="Article 8", pub_date=datetime(2005, 7, 31, 12, 30, 45), ) a2.save() self.assertEqual( Article.objects.get(id__exact=a2.id).pub_date, datetime(2005, 7, 31, 12, 30, 45), ) def test_saving_an_object_again_does_not_create_a_new_object(self): a = Article(headline="original", pub_date=datetime(2014, 5, 16)) a.save() current_id = a.id a.save() self.assertEqual(a.id, current_id) a.headline = "Updated headline" a.save() self.assertEqual(a.id, current_id) def test_querysets_checking_for_membership(self): headlines = ["Parrot programs in Python", "Second article", "Third article"] some_pub_date = datetime(2014, 5, 16, 12, 1) for headline in headlines: Article(headline=headline, pub_date=some_pub_date).save() a = Article(headline="Some headline", pub_date=some_pub_date) a.save() # You can use 'in' to test for membership... self.assertIn(a, Article.objects.all()) # ... but there will often be more efficient ways if that is all you # need: self.assertTrue(Article.objects.filter(id=a.id).exists()) def test_save_primary_with_default(self): # An UPDATE attempt is skipped when a primary key has default. with self.assertNumQueries(1): PrimaryKeyWithDefault().save() def test_save_primary_with_default_force_update(self): # An UPDATE attempt is made if explicitly requested. obj = PrimaryKeyWithDefault.objects.create() with self.assertNumQueries(1): PrimaryKeyWithDefault(uuid=obj.pk).save(force_update=True) def test_save_primary_with_db_default(self): # An UPDATE attempt is skipped when a primary key has db_default. with self.assertNumQueries(1): PrimaryKeyWithDbDefault().save() def test_save_parent_primary_with_default(self): # An UPDATE attempt is skipped when an inherited primary key has # default. with self.assertNumQueries(2): ChildPrimaryKeyWithDefault().save() def test_save_primary_with_falsey_default(self): with self.assertNumQueries(1): PrimaryKeyWithFalseyDefault().save() def test_save_primary_with_falsey_db_default(self): with self.assertNumQueries(1): PrimaryKeyWithFalseyDbDefault().save() def test_auto_field_with_value_refreshed(self): """ An auto field must be refreshed by Model.save() even when a value is set because the database may return a value of a different type. """ a = Article.objects.create(pk="123456", pub_date=datetime(2025, 9, 16)) self.assertEqual(a.pk, 123456)
ModelInstanceCreationTests
python
doocs__leetcode
solution/0700-0799/0790.Domino and Tromino Tiling/Solution.py
{ "start": 0, "end": 357 }
class ____: def numTilings(self, n: int) -> int: f = [1, 0, 0, 0] mod = 10**9 + 7 for i in range(1, n + 1): g = [0] * 4 g[0] = (f[0] + f[1] + f[2] + f[3]) % mod g[1] = (f[2] + f[3]) % mod g[2] = (f[1] + f[3]) % mod g[3] = f[0] f = g return f[0]
Solution
python
encode__django-rest-framework
tests/test_permissions.py
{ "start": 21911, "end": 32454 }
class ____(TestCase): def setUp(self): self.username = 'john' self.email = 'lennon@thebeatles.com' self.password = 'password' self.user = User.objects.create_user( self.username, self.email, self.password ) self.client.login(username=self.username, password=self.password) def test_and_false(self): request = factory.get('/1', format='json') request.user = AnonymousUser() composed_perm = permissions.IsAuthenticated & permissions.AllowAny assert composed_perm().has_permission(request, None) is False def test_and_true(self): request = factory.get('/1', format='json') request.user = self.user composed_perm = permissions.IsAuthenticated & permissions.AllowAny assert composed_perm().has_permission(request, None) is True def test_or_false(self): request = factory.get('/1', format='json') request.user = AnonymousUser() composed_perm = permissions.IsAuthenticated | permissions.AllowAny assert composed_perm().has_permission(request, None) is True def test_or_true(self): request = factory.get('/1', format='json') request.user = self.user composed_perm = permissions.IsAuthenticated | permissions.AllowAny assert composed_perm().has_permission(request, None) is True def test_not_false(self): request = factory.get('/1', format='json') request.user = AnonymousUser() composed_perm = ~permissions.IsAuthenticated assert composed_perm().has_permission(request, None) is True def test_not_true(self): request = factory.get('/1', format='json') request.user = self.user composed_perm = ~permissions.AllowAny assert composed_perm().has_permission(request, None) is False def test_several_levels_without_negation(self): request = factory.get('/1', format='json') request.user = self.user composed_perm = ( permissions.IsAuthenticated & permissions.IsAuthenticated & permissions.IsAuthenticated & permissions.IsAuthenticated ) assert composed_perm().has_permission(request, None) is True def test_several_levels_and_precedence_with_negation(self): request = factory.get('/1', format='json') request.user = self.user composed_perm = ( permissions.IsAuthenticated & ~ permissions.IsAdminUser & permissions.IsAuthenticated & ~(permissions.IsAdminUser & permissions.IsAdminUser) ) assert composed_perm().has_permission(request, None) is True def test_several_levels_and_precedence(self): request = factory.get('/1', format='json') request.user = self.user composed_perm = ( permissions.IsAuthenticated & permissions.IsAuthenticated | permissions.IsAuthenticated & permissions.IsAuthenticated ) assert composed_perm().has_permission(request, None) is True def test_or_laziness(self): request = factory.get('/1', format='json') request.user = AnonymousUser() with mock.patch.object(permissions.AllowAny, 'has_permission', return_value=True) as mock_allow: with mock.patch.object(permissions.IsAuthenticated, 'has_permission', return_value=False) as mock_deny: composed_perm = (permissions.AllowAny | permissions.IsAuthenticated) hasperm = composed_perm().has_permission(request, None) assert hasperm is True assert mock_allow.call_count == 1 mock_deny.assert_not_called() with mock.patch.object(permissions.AllowAny, 'has_permission', return_value=True) as mock_allow: with mock.patch.object(permissions.IsAuthenticated, 'has_permission', return_value=False) as mock_deny: composed_perm = (permissions.IsAuthenticated | permissions.AllowAny) hasperm = composed_perm().has_permission(request, None) assert hasperm is True assert mock_deny.call_count == 1 assert mock_allow.call_count == 1 def test_object_or_laziness(self): request = factory.get('/1', format='json') request.user = AnonymousUser() with mock.patch.object(permissions.AllowAny, 'has_object_permission', return_value=True) as mock_allow: with mock.patch.object(permissions.IsAuthenticated, 'has_object_permission', return_value=False) as mock_deny: composed_perm = (permissions.AllowAny | permissions.IsAuthenticated) hasperm = composed_perm().has_object_permission(request, None, None) assert hasperm is True assert mock_allow.call_count == 1 mock_deny.assert_not_called() with mock.patch.object(permissions.AllowAny, 'has_object_permission', return_value=True) as mock_allow: with mock.patch.object(permissions.IsAuthenticated, 'has_object_permission', return_value=False) as mock_deny: composed_perm = (permissions.IsAuthenticated | permissions.AllowAny) hasperm = composed_perm().has_object_permission(request, None, None) assert hasperm is True assert mock_deny.call_count == 0 assert mock_allow.call_count == 1 def test_and_laziness(self): request = factory.get('/1', format='json') request.user = AnonymousUser() with mock.patch.object(permissions.AllowAny, 'has_permission', return_value=True) as mock_allow: with mock.patch.object(permissions.IsAuthenticated, 'has_permission', return_value=False) as mock_deny: composed_perm = (permissions.AllowAny & permissions.IsAuthenticated) hasperm = composed_perm().has_permission(request, None) assert hasperm is False assert mock_allow.call_count == 1 assert mock_deny.call_count == 1 with mock.patch.object(permissions.AllowAny, 'has_permission', return_value=True) as mock_allow: with mock.patch.object(permissions.IsAuthenticated, 'has_permission', return_value=False) as mock_deny: composed_perm = (permissions.IsAuthenticated & permissions.AllowAny) hasperm = composed_perm().has_permission(request, None) assert hasperm is False assert mock_deny.call_count == 1 mock_allow.assert_not_called() def test_object_and_laziness(self): request = factory.get('/1', format='json') request.user = AnonymousUser() with mock.patch.object(permissions.AllowAny, 'has_object_permission', return_value=True) as mock_allow: with mock.patch.object(permissions.IsAuthenticated, 'has_object_permission', return_value=False) as mock_deny: composed_perm = (permissions.AllowAny & permissions.IsAuthenticated) hasperm = composed_perm().has_object_permission(request, None, None) assert hasperm is False assert mock_allow.call_count == 1 assert mock_deny.call_count == 1 with mock.patch.object(permissions.AllowAny, 'has_object_permission', return_value=True) as mock_allow: with mock.patch.object(permissions.IsAuthenticated, 'has_object_permission', return_value=False) as mock_deny: composed_perm = (permissions.IsAuthenticated & permissions.AllowAny) hasperm = composed_perm().has_object_permission(request, None, None) assert hasperm is False assert mock_deny.call_count == 1 mock_allow.assert_not_called() def test_unimplemented_has_object_permission(self): "test for issue 6402 https://github.com/encode/django-rest-framework/issues/6402" request = factory.get('/1', format='json') request.user = AnonymousUser() class IsAuthenticatedUserOwner(permissions.IsAuthenticated): def has_object_permission(self, request, view, obj): return True composed_perm = (IsAuthenticatedUserOwner | permissions.IsAdminUser) hasperm = composed_perm().has_object_permission(request, None, None) assert hasperm is False def test_operand_holder_is_hashable(self): assert hash(permissions.IsAuthenticated & permissions.IsAdminUser) def test_operand_holder_hash_same_for_same_operands_and_operator(self): first_operand_holder = ( permissions.IsAuthenticated & permissions.IsAdminUser ) second_operand_holder = ( permissions.IsAuthenticated & permissions.IsAdminUser ) assert hash(first_operand_holder) == hash(second_operand_holder) def test_operand_holder_hash_differs_for_different_operands(self): first_operand_holder = ( permissions.IsAuthenticated & permissions.IsAdminUser ) second_operand_holder = ( permissions.AllowAny & permissions.IsAdminUser ) third_operand_holder = ( permissions.IsAuthenticated & permissions.AllowAny ) assert hash(first_operand_holder) != hash(second_operand_holder) assert hash(first_operand_holder) != hash(third_operand_holder) assert hash(second_operand_holder) != hash(third_operand_holder) def test_operand_holder_hash_differs_for_different_operators(self): first_operand_holder = ( permissions.IsAuthenticated & permissions.IsAdminUser ) second_operand_holder = ( permissions.IsAuthenticated | permissions.IsAdminUser ) assert hash(first_operand_holder) != hash(second_operand_holder) def test_filtering_permissions(self): unfiltered_permissions = [ permissions.IsAuthenticated & permissions.IsAdminUser, permissions.IsAuthenticated & permissions.IsAdminUser, permissions.AllowAny, ] expected_permissions = [ permissions.IsAuthenticated & permissions.IsAdminUser, permissions.AllowAny, ] filtered_permissions = [ perm for perm in dict.fromkeys(unfiltered_permissions) ] assert filtered_permissions == expected_permissions
PermissionsCompositionTests
python
sphinx-doc__sphinx
sphinx/domains/cpp/_ast.py
{ "start": 24330, "end": 25223 }
class ____(ASTPostfixOp): def __init__(self, expr: ASTExpression) -> None: self.expr = expr def __eq__(self, other: object) -> bool: if not isinstance(other, ASTPostfixArray): return NotImplemented return self.expr == other.expr def __hash__(self) -> int: return hash(self.expr) def _stringify(self, transform: StringifyTransform) -> str: return '[' + transform(self.expr) + ']' def get_id(self, idPrefix: str, version: int) -> str: return 'ix' + idPrefix + self.expr.get_id(version) def describe_signature( self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol ) -> None: signode += addnodes.desc_sig_punctuation('[', '[') self.expr.describe_signature(signode, mode, env, symbol) signode += addnodes.desc_sig_punctuation(']', ']')
ASTPostfixArray
python
Netflix__metaflow
metaflow/packaging_sys/__init__.py
{ "start": 978, "end": 19755 }
class ____: """ Base class for all Metaflow code packages (non user code). A Metaflow code package, at a minimum, contains: - a special INFO file (containing a bunch of metadata about the Metaflow environment) - a special CONFIG file (containing user configurations for the flow) Declare all other MetaflowCodeContent subclasses (versions) here to handle just the functions that are not implemented here. In a *separate* file, declare any other function for that specific version. NOTE: This file must remain as dependency-free as possible as it is loaded *very* early on. This is why you must decleare a *separate* class implementing what you want the Metaflow code package (non user) to do. """ _cached_mfcontent_info = {} _mappings = {} @classmethod def get_info(cls) -> Optional[Dict[str, Any]]: """ Get the content of the special INFO file on the local filesystem after the code package has been expanded. Returns ------- Optional[Dict[str, Any]] The content of the INFO file -- None if there is no such file. """ mfcontent_info = cls._extract_mfcontent_info() handling_cls = cls._get_mfcontent_class(mfcontent_info) return handling_cls.get_info_impl(mfcontent_info) @classmethod def get_config(cls) -> Optional[Dict[str, Any]]: """ Get the content of the special CONFIG file on the local filesystem after the code package has been expanded. Returns ------- Optional[Dict[str, Any]] The content of the CONFIG file -- None if there is no such file. """ mfcontent_info = cls._extract_mfcontent_info() handling_cls = cls._get_mfcontent_class(mfcontent_info) return handling_cls.get_config_impl(mfcontent_info) @classmethod def get_filename(cls, filename: str, content_type: ContentType) -> Optional[str]: """ Get the path to a file extracted from the archive. The filename is the filename passed in when creating the archive and content_type is the type of the content. This function will return the local path where the file can be found after the package has been extracted. Parameters ---------- filename: str The name of the file on the filesystem. content_type: ContentType Returns ------- str The path to the file on the local filesystem or None if not found. """ mfcontent_info = cls._extract_mfcontent_info() handling_cls = cls._get_mfcontent_class(mfcontent_info) return handling_cls.get_filename_impl(mfcontent_info, filename, content_type) @classmethod def get_env_vars_for_packaged_metaflow(cls, dest_dir: str) -> Dict[str, str]: """ Get the environment variables that are needed to run Metaflow when it is packaged. This is typically used to set the PYTHONPATH to include the directory where the Metaflow code package has been extracted. Returns ------- Dict[str, str] The environment variables that are needed to run Metaflow when it is packaged it present. """ mfcontent_info = cls._extract_mfcontent_info(dest_dir) if mfcontent_info is None: # No MFCONTENT_MARKER file found -- this is not a packaged Metaflow code # package so no environment variables to set. return {} handling_cls = cls._get_mfcontent_class(mfcontent_info) v = handling_cls.get_post_extract_env_vars_impl(dest_dir) v["METAFLOW_EXTRACTED_ROOT:"] = dest_dir return v @classmethod def get_archive_info( cls, archive: Any, packaging_backend: Type[PackagingBackend] = TarPackagingBackend, ) -> Optional[Dict[str, Any]]: """ Get the content of the special INFO file in the archive. Returns ------- Optional[Dict[str, Any]] The content of the INFO file -- None if there is no such file. """ mfcontent_info = cls._extract_archive_mfcontent_info(archive, packaging_backend) handling_cls = cls._get_mfcontent_class(mfcontent_info) return handling_cls.get_archive_info_impl( mfcontent_info, archive, packaging_backend ) @classmethod def get_archive_config( cls, archive: Any, packaging_backend: Type[PackagingBackend] = TarPackagingBackend, ) -> Optional[Dict[str, Any]]: """ Get the content of the special CONFIG file in the archive. Returns ------- Optional[Dict[str, Any]] The content of the CONFIG file -- None if there is no such file. """ mfcontent_info = cls._extract_archive_mfcontent_info(archive, packaging_backend) handling_cls = cls._get_mfcontent_class(mfcontent_info) return handling_cls.get_archive_config_impl( mfcontent_info, archive, packaging_backend ) @classmethod def get_archive_filename( cls, archive: Any, filename: str, content_type: ContentType, packaging_backend: Type[PackagingBackend] = TarPackagingBackend, ) -> Optional[str]: """ Get the filename of the archive. This does not do any extraction but simply returns where, in the archive, the file is located. This is the equivalent of get_filename but for files not extracted yet. Parameters ---------- archive: Any The archive to get the filename from. filename: str The name of the file in the archive. content_type: ContentType The type of the content (e.g., code, other, etc.). packaging_backend: Type[PackagingBackend], default TarPackagingBackend The packaging backend to use. Returns ------- str The filename of the archive or None if not found. """ mfcontent_info = cls._extract_archive_mfcontent_info(archive, packaging_backend) handling_cls = cls._get_mfcontent_class(mfcontent_info) return handling_cls.get_archive_filename_impl( mfcontent_info, archive, filename, content_type, packaging_backend ) @classmethod def get_archive_content_members( cls, archive: Any, content_types: Optional[int] = None, packaging_backend: Type[PackagingBackend] = TarPackagingBackend, ) -> List[Any]: mfcontent_info = cls._extract_archive_mfcontent_info(archive, packaging_backend) handling_cls = cls._get_mfcontent_class(mfcontent_info) return handling_cls.get_archive_content_members_impl( mfcontent_info, archive, content_types, packaging_backend ) @classmethod def get_distribution_finder( cls, ) -> Optional["metaflow.extension_support.metadata.DistributionFinder"]: """ Get the distribution finder for the Metaflow code package (if applicable). Some packages will include distribution information to "pretend" that some packages are actually distributions even if we just include them in the code package. Returns ------- Optional["metaflow.extension_support.metadata.DistributionFinder"] The distribution finder for the Metaflow code package -- None if there is no such finder. """ mfcontent_info = cls._extract_mfcontent_info() handling_cls = cls._get_mfcontent_class(mfcontent_info) return handling_cls.get_distribution_finder_impl(mfcontent_info) @classmethod def get_post_extract_env_vars( cls, version_id: int, dest_dir: str = "." ) -> Dict[str, str]: """ Get the post-extract environment variables that are needed to access the content that has been extracted into dest_dir. This will typically involve setting PYTHONPATH. Parameters ---------- version_id: int The version of MetaflowCodeContent for this package. dest_dir: str, default "." The directory where the content has been extracted to. Returns ------- Dict[str, str] The post-extract environment variables that are needed to access the content that has been extracted into extracted_dir. """ if version_id not in cls._mappings: raise ValueError( "Invalid package -- unknown version %s in info: %s" % (version_id, cls._mappings) ) v = cls._mappings[version_id].get_post_extract_env_vars_impl(dest_dir) v["METAFLOW_EXTRACTED_ROOT:"] = dest_dir return v # Implement the _impl methods in the base subclass (in this file). These need to # happen with as few imports as possible to prevent circular dependencies. @classmethod def get_info_impl( cls, mfcontent_info: Optional[Dict[str, Any]] ) -> Optional[Dict[str, Any]]: raise NotImplementedError("get_info_impl not implemented") @classmethod def get_config_impl( cls, mfcontent_info: Optional[Dict[str, Any]] ) -> Optional[Dict[str, Any]]: raise NotImplementedError("get_config_impl not implemented") @classmethod def get_filename_impl( cls, mfcontent_info: Optional[Dict[str, Any]], filename: str, content_type: ContentType, ) -> Optional[str]: raise NotImplementedError("get_filename_impl not implemented") @classmethod def get_distribution_finder_impl( cls, mfcontent_info: Optional[Dict[str, Any]] ) -> Optional["metaflow.extension_support.metadata.DistributionFinder"]: raise NotImplementedError("get_distribution_finder_impl not implemented") @classmethod def get_archive_info_impl( cls, mfcontent_info: Optional[Dict[str, Any]], archive: Any, packaging_backend: Type[PackagingBackend] = TarPackagingBackend, ) -> Optional[Dict[str, Any]]: raise NotImplementedError("get_archive_info_impl not implemented") @classmethod def get_archive_config_impl( cls, mfcontent_info: Optional[Dict[str, Any]], archive: Any, packaging_backend: Type[PackagingBackend] = TarPackagingBackend, ) -> Optional[Dict[str, Any]]: raise NotImplementedError("get_archive_config_impl not implemented") @classmethod def get_archive_filename_impl( cls, mfcontent_info: Optional[Dict[str, Any]], archive: Any, filename: str, content_type: ContentType, packaging_backend: Type[PackagingBackend] = TarPackagingBackend, ) -> Optional[str]: raise NotImplementedError("get_archive_filename_impl not implemented") @classmethod def get_archive_content_members_impl( cls, mfcontent_info: Optional[Dict[str, Any]], archive: Any, content_types: Optional[int] = None, packaging_backend: Type[PackagingBackend] = TarPackagingBackend, ) -> List[Any]: raise NotImplementedError("get_archive_content_members_impl not implemented") @classmethod def get_post_extract_env_vars_impl(cls, dest_dir: str) -> Dict[str, str]: raise NotImplementedError("get_post_extract_env_vars_impl not implemented") def __init_subclass__(cls, version_id, **kwargs) -> None: super().__init_subclass__(**kwargs) if version_id in MetaflowCodeContent._mappings: raise ValueError( "Version ID %s already exists in MetaflowCodeContent mappings " "-- this is a bug in Metaflow." % str(version_id) ) MetaflowCodeContent._mappings[version_id] = cls cls._version_id = version_id # Implement these methods in sub-classes of the base sub-classes. These methods # are called later and can have more dependencies and so can live in other files. def get_excluded_tl_entries(self) -> List[str]: """ When packaging Metaflow from within an executing Metaflow flow, we need to exclude the files that are inserted by this content from being packaged (possibly). Use this function to return these files or top-level directories. Returns ------- List[str] Files or directories to exclude """ return [] def content_names( self, content_types: Optional[int] = None ) -> Generator[Tuple[str, str], None, None]: """ Detailed list of the content of this MetaflowCodeContent. This will list all files (or non files -- for the INFO or CONFIG data for example) present in the archive. Parameters ---------- content_types : Optional[int] The type of content to get the names of. If None, all content is returned. Yields ------ Generator[Tuple[str, str], None, None] Path on the filesystem and the name in the archive """ raise NotImplementedError("content_names not implemented") def contents( self, content_types: Optional[int] = None ) -> Generator[Tuple[Union[bytes, str], str], None, None]: """ Very similar to content_names but returns the content of the non-files as well as bytes. For files, identical output as content_names Parameters ---------- content_types : Optional[int] The type of content to get the content of. If None, all content is returned. Yields ------ Generator[Tuple[Union[str, bytes], str], None, None] Content of the MF content """ raise NotImplementedError("content not implemented") def show(self) -> str: """ Returns a more human-readable string representation of the content of this MetaflowCodeContent. This will not, for example, list all files but summarize what is included at a more high level. Returns ------- str A human-readable string representation of the content of this MetaflowCodeContent """ raise NotImplementedError("show not implemented") def add_info(self, info: Dict[str, Any]) -> None: """ Add the content of the INFO file to the Metaflow content Parameters ---------- info: Dict[str, Any] The content of the INFO file """ raise NotImplementedError("add_info not implemented") def add_config(self, config: Dict[str, Any]) -> None: """ Add the content of the CONFIG file to the Metaflow content Parameters ---------- config: Dict[str, Any] The content of the CONFIG file """ raise NotImplementedError("add_config not implemented") def add_module(self, module_path: ModuleType) -> None: """ Add a python module to the Metaflow content Parameters ---------- module_path: ModuleType The module to add """ raise NotImplementedError("add_module not implemented") def add_code_file(self, file_path: str, file_name: str) -> None: """ Add a code file to the Metaflow content Parameters ---------- file_path: str The path to the code file to add (on the filesystem) file_name: str The path in the archive to add the code file to """ raise NotImplementedError("add_code_file not implemented") def add_other_file(self, file_path: str, file_name: str) -> None: """ Add a non-python file to the Metaflow content Parameters ---------- file_path: str The path to the file to add (on the filesystem) file_name: str The path in the archive to add the file to """ raise NotImplementedError("add_other_file not implemented") @classmethod def _get_mfcontent_class( cls, info: Optional[Dict[str, Any]] ) -> Type["MetaflowCodeContent"]: if info is None: return MetaflowCodeContentV0 if "version" not in info: raise ValueError("Invalid package -- missing version in info: %s" % info) version = info["version"] if version not in cls._mappings: raise ValueError( "Invalid package -- unknown version %s in info: %s" % (version, info) ) return cls._mappings[version] @classmethod def _extract_archive_mfcontent_info( cls, archive: Any, packaging_backend: Type[PackagingBackend] = TarPackagingBackend, ) -> Optional[Dict[str, Any]]: if id(archive) in cls._cached_mfcontent_info: return cls._cached_mfcontent_info[id(archive)] mfcontent_info = None # type: Optional[Dict[str, Any]] # Here we need to extract the information from the archive if packaging_backend.cls_has_member(archive, MFCONTENT_MARKER): # The MFCONTENT_MARKER file is present in the archive # We can extract the information from it extracted_info = packaging_backend.cls_get_member(archive, MFCONTENT_MARKER) if extracted_info: mfcontent_info = json.loads(extracted_info) cls._cached_mfcontent_info[id(archive)] = mfcontent_info return mfcontent_info @classmethod def _extract_mfcontent_info( cls, target_dir: Optional[str] = None ) -> Optional[Dict[str, Any]]: target_dir = target_dir or "_local" if target_dir in cls._cached_mfcontent_info: return cls._cached_mfcontent_info[target_dir] mfcontent_info = None # type: Optional[Dict[str, Any]] if target_dir == "_local": root = os.environ.get("METAFLOW_EXTRACTED_ROOT", get_metaflow_root()) else: root = target_dir if os.path.exists(os.path.join(root, MFCONTENT_MARKER)): with open(os.path.join(root, MFCONTENT_MARKER), "r", encoding="utf-8") as f: mfcontent_info = json.load(f) cls._cached_mfcontent_info[target_dir] = mfcontent_info return mfcontent_info def get_package_version(self) -> int: """ Get the version of MetaflowCodeContent for this package. """ # _version_id is set in __init_subclass__ when the subclass is created return self._version_id
MetaflowCodeContent
python
huggingface__transformers
tests/models/mpt/test_modeling_mpt.py
{ "start": 12978, "end": 13651 }
class ____(ConfigTester): def __init__(self, parent, config_class=None, has_text_modality=True, common_properties=None, **kwargs): super().__init__(parent, config_class, has_text_modality, common_properties, **kwargs) def test_attn_config_as_dict(self): config = self.config_class(**self.inputs_dict, attn_config={"attn_impl": "flash", "softmax_scale": None}) self.parent.assertTrue(config.attn_config.attn_impl == "flash") self.parent.assertTrue(config.attn_config.softmax_scale is None) def run_common_tests(self): self.test_attn_config_as_dict() return super().run_common_tests() @require_torch
MptConfigTester
python
pypa__hatch
tests/cli/fmt/test_fmt.py
{ "start": 1707, "end": 7142 }
class ____: def test_fix(self, hatch, helpers, temp_dir, config_file, env_run, mocker, platform, defaults_file_stable): config_file.model.template.plugins["default"]["tests"] = False config_file.save() project_name = "My.App" with temp_dir.as_cwd(): result = hatch("new", project_name) assert result.exit_code == 0, result.output project_path = temp_dir / "my-app" data_path = temp_dir / "data" data_path.mkdir() config_dir = data_path / "env" / ".internal" / "hatch-static-analysis" / ".config" / project_path.id default_config = config_dir / "ruff_defaults.toml" user_config = config_dir / "pyproject.toml" user_config_path = platform.join_command_args([str(user_config)]) with project_path.as_cwd(env_vars={ConfigEnvVars.DATA: str(data_path)}): result = hatch("fmt") assert result.exit_code == 0, result.output assert result.output == helpers.dedent( f""" cmd [1] | ruff check --config {user_config_path} --fix . cmd [2] | ruff format --config {user_config_path} . """ ) assert env_run.call_args_list == [ mocker.call(f"ruff check --config {user_config_path} --fix .", shell=True), mocker.call(f"ruff format --config {user_config_path} .", shell=True), ] assert default_config.read_text() == defaults_file_stable old_contents = (project_path / "pyproject.toml").read_text() config_path = str(default_config).replace("\\", "\\\\") assert ( user_config.read_text() == f"""\ {old_contents} [tool.ruff] extend = "{config_path}\"""" ) def test_check(self, hatch, helpers, temp_dir, config_file, env_run, mocker, platform, defaults_file_stable): config_file.model.template.plugins["default"]["tests"] = False config_file.save() project_name = "My.App" with temp_dir.as_cwd(): result = hatch("new", project_name) assert result.exit_code == 0, result.output project_path = temp_dir / "my-app" data_path = temp_dir / "data" data_path.mkdir() config_dir = data_path / "env" / ".internal" / "hatch-static-analysis" / ".config" / project_path.id default_config = config_dir / "ruff_defaults.toml" user_config = config_dir / "pyproject.toml" user_config_path = platform.join_command_args([str(user_config)]) with project_path.as_cwd(env_vars={ConfigEnvVars.DATA: str(data_path)}): result = hatch("fmt", "--check") assert result.exit_code == 0, result.output assert result.output == helpers.dedent( f""" cmd [1] | ruff check --config {user_config_path} . cmd [2] | ruff format --config {user_config_path} --check --diff . """ ) assert env_run.call_args_list == [ mocker.call(f"ruff check --config {user_config_path} .", shell=True), mocker.call(f"ruff format --config {user_config_path} --check --diff .", shell=True), ] assert default_config.read_text() == defaults_file_stable old_contents = (project_path / "pyproject.toml").read_text() config_path = str(default_config).replace("\\", "\\\\") assert ( user_config.read_text() == f"""\ {old_contents} [tool.ruff] extend = "{config_path}\"""" ) def test_existing_config( self, hatch, helpers, temp_dir, config_file, env_run, mocker, platform, defaults_file_stable ): config_file.model.template.plugins["default"]["tests"] = False config_file.save() project_name = "My.App" with temp_dir.as_cwd(): result = hatch("new", project_name) assert result.exit_code == 0, result.output project_path = temp_dir / "my-app" data_path = temp_dir / "data" data_path.mkdir() config_dir = data_path / "env" / ".internal" / "hatch-static-analysis" / ".config" / project_path.id default_config = config_dir / "ruff_defaults.toml" user_config = config_dir / "pyproject.toml" user_config_path = platform.join_command_args([str(user_config)]) project_file = project_path / "pyproject.toml" old_contents = project_file.read_text() project_file.write_text(f"[tool.ruff]\n{old_contents}") with project_path.as_cwd(env_vars={ConfigEnvVars.DATA: str(data_path)}): result = hatch("fmt", "--check") assert result.exit_code == 0, result.output assert result.output == helpers.dedent( f""" cmd [1] | ruff check --config {user_config_path} . cmd [2] | ruff format --config {user_config_path} --check --diff . """ ) assert env_run.call_args_list == [ mocker.call(f"ruff check --config {user_config_path} .", shell=True), mocker.call(f"ruff format --config {user_config_path} --check --diff .", shell=True), ] assert default_config.read_text() == defaults_file_stable config_path = str(default_config).replace("\\", "\\\\") assert ( user_config.read_text() == f"""\ [tool.ruff] extend = "{config_path}\" {old_contents.rstrip()}""" )
TestDefaults
python
zarr-developers__zarr-python
src/zarr/core/dtype/npy/bytes.py
{ "start": 620, "end": 998 }
class ____(TypedDict): """ A configuration for a data type that takes a ``length_bytes`` parameter. Attributes ---------- length_bytes : int The length in bytes of the data associated with this configuration. Examples -------- ```python { "length_bytes": 12 } ``` """ length_bytes: int
FixedLengthBytesConfig
python
getsentry__sentry
src/sentry/sentry_apps/api/parsers/servicehook.py
{ "start": 112, "end": 711 }
class ____(serializers.Serializer): url = serializers.URLField(required=True) events = serializers.ListField(child=serializers.CharField(max_length=255), required=False) version = serializers.ChoiceField(choices=((0, "0"),), required=False, default=0) isActive = serializers.BooleanField(required=False, default=True) def validate_events(self, value): if value: for event in value: if event not in SERVICE_HOOK_EVENTS: raise serializers.ValidationError(f"Invalid event name: {event}") return value
ServiceHookValidator
python
redis__redis-py
redis/commands/search/reducers.py
{ "start": 476, "end": 696 }
class ____(FieldOnlyReducer): """ Calculates the sum of all the values in the given fields within the group """ NAME = "SUM" def __init__(self, field: str) -> None: super().__init__(field)
sum
python
numpy__numpy
benchmarks/benchmarks/bench_shape_base.py
{ "start": 2536, "end": 4310 }
class ____(Benchmark): """This benchmark concatenates an array of size ``(5n)^3``""" # Having copy as a `mode` of the block3D # allows us to directly compare the benchmark of block # to that of a direct memory copy into new buffers with # the ASV framework. # block and copy will be plotted on the same graph # as opposed to being displayed as separate benchmarks params = [[1, 10, 100], ['block', 'copy']] param_names = ['n', 'mode'] def setup(self, n, mode): # Slow setup method: hence separated from the others above self.a000 = np.ones((2 * n, 2 * n, 2 * n), int) * 1 self.a100 = np.ones((3 * n, 2 * n, 2 * n), int) * 2 self.a010 = np.ones((2 * n, 3 * n, 2 * n), int) * 3 self.a001 = np.ones((2 * n, 2 * n, 3 * n), int) * 4 self.a011 = np.ones((2 * n, 3 * n, 3 * n), int) * 5 self.a101 = np.ones((3 * n, 2 * n, 3 * n), int) * 6 self.a110 = np.ones((3 * n, 3 * n, 2 * n), int) * 7 self.a111 = np.ones((3 * n, 3 * n, 3 * n), int) * 8 self.block = [ [ [self.a000, self.a001], [self.a010, self.a011], ], [ [self.a100, self.a101], [self.a110, self.a111], ] ] self.arr_list = [a for two_d in self.block for one_d in two_d for a in one_d] def time_3d(self, n, mode): if mode == 'block': np.block(self.block) else: # mode == 'copy' [arr.copy() for arr in self.arr_list] # Retain old benchmark name for backward compat time_3d.benchmark_name = "bench_shape_base.Block.time_3d"
Block3D
python
matplotlib__matplotlib
lib/matplotlib/collections.py
{ "start": 1114, "end": 41554 }
class ____(mcolorizer.ColorizingArtist): r""" Base class for Collections. Must be subclassed to be usable. A Collection represents a sequence of `.Patch`\es that can be drawn more efficiently together than individually. For example, when a single path is being drawn repeatedly at different offsets, the renderer can typically execute a ``draw_marker()`` call much more efficiently than a series of repeated calls to ``draw_path()`` with the offsets put in one-by-one. Most properties of a collection can be configured per-element. Therefore, Collections have "plural" versions of many of the properties of a `.Patch` (e.g. `.Collection.get_paths` instead of `.Patch.get_path`). Exceptions are the *zorder*, *hatch*, *pickradius*, *capstyle* and *joinstyle* properties, which can only be set globally for the whole collection. Besides these exceptions, all properties can be specified as single values (applying to all elements) or sequences of values. The property of the ``i``\th element of the collection is:: prop[i % len(prop)] Each Collection can optionally be used as its own `.ScalarMappable` by passing the *norm* and *cmap* parameters to its constructor. If the Collection's `.ScalarMappable` matrix ``_A`` has been set (via a call to `.Collection.set_array`), then at draw time this internal scalar mappable will be used to set the ``facecolors`` and ``edgecolors``, ignoring those that were manually passed in. """ #: Either a list of 3x3 arrays or an Nx3x3 array (representing N #: transforms), suitable for the `all_transforms` argument to #: `~matplotlib.backend_bases.RendererBase.draw_path_collection`; #: each 3x3 array is used to initialize an #: `~matplotlib.transforms.Affine2D` object. #: Each kind of collection defines this based on its arguments. _transforms = np.empty((0, 3, 3)) # Whether to draw an edge by default. Set on a # subclass-by-subclass basis. _edge_default = False @_docstring.interpd def __init__(self, *, edgecolors=None, facecolors=None, hatchcolors=None, linewidths=None, linestyles='solid', capstyle=None, joinstyle=None, antialiaseds=None, offsets=None, offset_transform=None, norm=None, # optional for ScalarMappable cmap=None, # ditto colorizer=None, pickradius=5.0, hatch=None, urls=None, zorder=1, **kwargs ): """ Parameters ---------- edgecolors : :mpltype:`color` or list of colors, default: :rc:`patch.edgecolor` Edge color for each patch making up the collection. The special value 'face' can be passed to make the edgecolor match the facecolor. facecolors : :mpltype:`color` or list of colors, default: :rc:`patch.facecolor` Face color for each patch making up the collection. hatchcolors : :mpltype:`color` or list of colors, default: :rc:`hatch.color` Hatch color for each patch making up the collection. The color can be set to the special value 'edge' to make the hatchcolor match the edgecolor. linewidths : float or list of floats, default: :rc:`patch.linewidth` Line width for each patch making up the collection. linestyles : str or tuple or list thereof, default: 'solid' Valid strings are ['solid', 'dashed', 'dashdot', 'dotted', '-', '--', '-.', ':']. Dash tuples should be of the form:: (offset, onoffseq), where *onoffseq* is an even length tuple of on and off ink lengths in points. For examples, see :doc:`/gallery/lines_bars_and_markers/linestyles`. capstyle : `.CapStyle`-like, default: 'butt' Style to use for capping lines for all paths in the collection. Allowed values are %(CapStyle)s. joinstyle : `.JoinStyle`-like, default: 'round' Style to use for joining lines for all paths in the collection. Allowed values are %(JoinStyle)s. antialiaseds : bool or list of bool, default: :rc:`patch.antialiased` Whether each patch in the collection should be drawn with antialiasing. offsets : (float, float) or list thereof, default: (0, 0) A vector by which to translate each patch after rendering (default is no translation). The translation is performed in screen (pixel) coordinates (i.e. after the Artist's transform is applied). offset_transform : `~.Transform`, default: `.IdentityTransform` A single transform which will be applied to each *offsets* vector before it is used. cmap, norm Data normalization and colormapping parameters. See `.ScalarMappable` for a detailed description. hatch : str, optional Hatching pattern to use in filled paths, if any. Valid strings are ['/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*']. See :doc:`/gallery/shapes_and_collections/hatch_style_reference` for the meaning of each hatch type. pickradius : float, default: 5.0 If ``pickradius <= 0``, then `.Collection.contains` will return ``True`` whenever the test point is inside of one of the polygons formed by the control points of a Path in the Collection. On the other hand, if it is greater than 0, then we instead check if the test point is contained in a stroke of width ``2*pickradius`` following any of the Paths in the Collection. urls : list of str, default: None A URL for each patch to link to once drawn. Currently only works for the SVG backend. See :doc:`/gallery/misc/hyperlinks_sgskip` for examples. zorder : float, default: 1 The drawing order, shared by all Patches in the Collection. See :doc:`/gallery/misc/zorder_demo` for all defaults and examples. **kwargs Remaining keyword arguments will be used to set properties as ``Collection.set_{key}(val)`` for each key-value pair in *kwargs*. """ super().__init__(self._get_colorizer(cmap, norm, colorizer)) # list of un-scaled dash patterns # this is needed scaling the dash pattern by linewidth self._us_linestyles = [(0, None)] # list of dash patterns self._linestyles = [(0, None)] # list of unbroadcast/scaled linewidths self._us_lw = [0] self._linewidths = [0] self._gapcolor = None # Currently only used by LineCollection. # Flags set by _set_mappable_flags: are colors from mapping an array? self._face_is_mapped = None self._edge_is_mapped = None self._mapped_colors = None # calculated in update_scalarmappable self._hatch_linewidth = mpl.rcParams['hatch.linewidth'] self.set_facecolor(facecolors) self.set_edgecolor(edgecolors) self.set_linewidth(linewidths) self.set_linestyle(linestyles) self.set_antialiased(antialiaseds) self.set_pickradius(pickradius) self.set_urls(urls) self.set_hatch(hatch) self.set_hatchcolor(hatchcolors) self.set_zorder(zorder) if capstyle: self.set_capstyle(capstyle) else: self._capstyle = None if joinstyle: self.set_joinstyle(joinstyle) else: self._joinstyle = None if offsets is not None: offsets = np.asanyarray(offsets, float) # Broadcast (2,) -> (1, 2) but nothing else. if offsets.shape == (2,): offsets = offsets[None, :] self._offsets = offsets self._offset_transform = offset_transform self._path_effects = None self._internal_update(kwargs) self._paths = None def get_paths(self): return self._paths def set_paths(self, paths): self._paths = paths self.stale = True def get_transforms(self): return self._transforms def get_offset_transform(self): """Return the `.Transform` instance used by this artist offset.""" if self._offset_transform is None: self._offset_transform = transforms.IdentityTransform() elif (not isinstance(self._offset_transform, transforms.Transform) and hasattr(self._offset_transform, '_as_mpl_transform')): self._offset_transform = \ self._offset_transform._as_mpl_transform(self.axes) return self._offset_transform def set_offset_transform(self, offset_transform): """ Set the artist offset transform. Parameters ---------- offset_transform : `.Transform` """ self._offset_transform = offset_transform def get_datalim(self, transData): # Calculate the data limits and return them as a `.Bbox`. # # This operation depends on the transforms for the data in the # collection and whether the collection has offsets: # # 1. offsets = None, transform child of transData: use the paths for # the automatic limits (i.e. for LineCollection in streamline). # 2. offsets != None: offset_transform is child of transData: # # a. transform is child of transData: use the path + offset for # limits (i.e for bar). # b. transform is not a child of transData: just use the offsets # for the limits (i.e. for scatter) # # 3. otherwise return a null Bbox. transform = self.get_transform() offset_trf = self.get_offset_transform() if not (isinstance(offset_trf, transforms.IdentityTransform) or offset_trf.contains_branch(transData)): # if the offsets are in some coords other than data, # then don't use them for autoscaling. return transforms.Bbox.null() paths = self.get_paths() if not len(paths): # No paths to transform return transforms.Bbox.null() if not transform.is_affine: paths = [transform.transform_path_non_affine(p) for p in paths] # Don't convert transform to transform.get_affine() here because # we may have transform.contains_branch(transData) but not # transforms.get_affine().contains_branch(transData). But later, # be careful to only apply the affine part that remains. offsets = self.get_offsets() if any(transform.contains_branch_separately(transData)): # collections that are just in data units (like quiver) # can properly have the axes limits set by their shape + # offset. LineCollections that have no offsets can # also use this algorithm (like streamplot). if isinstance(offsets, np.ma.MaskedArray): offsets = offsets.filled(np.nan) # get_path_collection_extents handles nan but not masked arrays return mpath.get_path_collection_extents( transform.get_affine() - transData, paths, self.get_transforms(), offset_trf.transform_non_affine(offsets), offset_trf.get_affine().frozen()) # NOTE: None is the default case where no offsets were passed in if self._offsets is not None: # this is for collections that have their paths (shapes) # in physical, axes-relative, or figure-relative units # (i.e. like scatter). We can't uniquely set limits based on # those shapes, so we just set the limits based on their # location. offsets = (offset_trf - transData).transform(offsets) # note A-B means A B^{-1} offsets = np.ma.masked_invalid(offsets) if not offsets.mask.all(): bbox = transforms.Bbox.null() bbox.update_from_data_xy(offsets) return bbox return transforms.Bbox.null() def get_window_extent(self, renderer=None): # TODO: check to ensure that this does not fail for # cases other than scatter plot legend return self.get_datalim(transforms.IdentityTransform()) def _prepare_points(self): # Helper for drawing and hit testing. transform = self.get_transform() offset_trf = self.get_offset_transform() offsets = self.get_offsets() paths = self.get_paths() if self.have_units(): paths = [] for path in self.get_paths(): vertices = path.vertices xs, ys = vertices[:, 0], vertices[:, 1] xs = self.convert_xunits(xs) ys = self.convert_yunits(ys) paths.append(mpath.Path(np.column_stack([xs, ys]), path.codes)) xs = self.convert_xunits(offsets[:, 0]) ys = self.convert_yunits(offsets[:, 1]) offsets = np.ma.column_stack([xs, ys]) if not transform.is_affine: paths = [transform.transform_path_non_affine(path) for path in paths] transform = transform.get_affine() if not offset_trf.is_affine: offsets = offset_trf.transform_non_affine(offsets) # This might have changed an ndarray into a masked array. offset_trf = offset_trf.get_affine() if isinstance(offsets, np.ma.MaskedArray): offsets = offsets.filled(np.nan) # Changing from a masked array to nan-filled ndarray # is probably most efficient at this point. return transform, offset_trf, offsets, paths @artist.allow_rasterization def draw(self, renderer): if not self.get_visible(): return renderer.open_group(self.__class__.__name__, self.get_gid()) self.update_scalarmappable() transform, offset_trf, offsets, paths = self._prepare_points() gc = renderer.new_gc() self._set_gc_clip(gc) gc.set_snap(self.get_snap()) if self._hatch: gc.set_hatch(self._hatch) gc.set_hatch_linewidth(self._hatch_linewidth) if self.get_sketch_params() is not None: gc.set_sketch_params(*self.get_sketch_params()) if self.get_path_effects(): from matplotlib.patheffects import PathEffectRenderer renderer = PathEffectRenderer(self.get_path_effects(), renderer) # If the collection is made up of a single shape/color/stroke, # it can be rendered once and blitted multiple times, using # `draw_markers` rather than `draw_path_collection`. This is # *much* faster for Agg, and results in smaller file sizes in # PDF/SVG/PS. trans = self.get_transforms() facecolors = self.get_facecolor() edgecolors = self.get_edgecolor() do_single_path_optimization = False if (len(paths) == 1 and len(trans) <= 1 and len(facecolors) == 1 and len(edgecolors) == 1 and len(self._linewidths) == 1 and all(ls[1] is None for ls in self._linestyles) and len(self._antialiaseds) == 1 and len(self._urls) == 1 and self.get_hatch() is None): if len(trans): combined_transform = transforms.Affine2D(trans[0]) + transform else: combined_transform = transform extents = paths[0].get_extents(combined_transform) if (extents.width < self.get_figure(root=True).bbox.width and extents.height < self.get_figure(root=True).bbox.height): do_single_path_optimization = True if self._joinstyle: gc.set_joinstyle(self._joinstyle) if self._capstyle: gc.set_capstyle(self._capstyle) if do_single_path_optimization: gc.set_foreground(tuple(edgecolors[0])) gc.set_linewidth(self._linewidths[0]) gc.set_dashes(*self._linestyles[0]) gc.set_antialiased(self._antialiaseds[0]) gc.set_url(self._urls[0]) renderer.draw_markers( gc, paths[0], combined_transform.frozen(), mpath.Path(offsets), offset_trf, tuple(facecolors[0])) else: # The current new API of draw_path_collection() is provisional # and will be changed in a future PR. # Find whether renderer.draw_path_collection() takes hatchcolor parameter. # Since third-party implementations of draw_path_collection() may not be # introspectable, e.g. with inspect.signature, the only way is to try and # call this with the hatchcolors parameter. hatchcolors_arg_supported = True try: renderer.draw_path_collection( gc, transform.frozen(), [], self.get_transforms(), offsets, offset_trf, self.get_facecolor(), self.get_edgecolor(), self._linewidths, self._linestyles, self._antialiaseds, self._urls, "screen", hatchcolors=self.get_hatchcolor() ) except TypeError: # If the renderer does not support the hatchcolors argument, # it will raise a TypeError. In this case, we will # iterate over all paths and draw them one by one. hatchcolors_arg_supported = False # If the hatchcolors argument is not needed or not passed # then we can skip the iteration over paths in case the # argument is not supported by the renderer. hatchcolors_not_needed = (self.get_hatch() is None or self._original_hatchcolor is None) if self._gapcolor is not None: # First draw paths within the gaps. ipaths, ilinestyles = self._get_inverse_paths_linestyles() args = [offsets, offset_trf, [mcolors.to_rgba("none")], self._gapcolor, self._linewidths, ilinestyles, self._antialiaseds, self._urls, "screen"] if hatchcolors_arg_supported: renderer.draw_path_collection(gc, transform.frozen(), ipaths, self.get_transforms(), *args, hatchcolors=self.get_hatchcolor()) else: if hatchcolors_not_needed: renderer.draw_path_collection(gc, transform.frozen(), ipaths, self.get_transforms(), *args) else: path_ids = renderer._iter_collection_raw_paths( transform.frozen(), ipaths, self.get_transforms()) for xo, yo, path_id, gc0, rgbFace in renderer._iter_collection( gc, list(path_ids), *args, hatchcolors=self.get_hatchcolor(), ): path, transform = path_id if xo != 0 or yo != 0: transform = transform.frozen() transform.translate(xo, yo) renderer.draw_path(gc0, path, transform, rgbFace) args = [offsets, offset_trf, self.get_facecolor(), self.get_edgecolor(), self._linewidths, self._linestyles, self._antialiaseds, self._urls, "screen"] if hatchcolors_arg_supported: renderer.draw_path_collection(gc, transform.frozen(), paths, self.get_transforms(), *args, hatchcolors=self.get_hatchcolor()) else: if hatchcolors_not_needed: renderer.draw_path_collection(gc, transform.frozen(), paths, self.get_transforms(), *args) else: path_ids = renderer._iter_collection_raw_paths( transform.frozen(), paths, self.get_transforms()) for xo, yo, path_id, gc0, rgbFace in renderer._iter_collection( gc, list(path_ids), *args, hatchcolors=self.get_hatchcolor(), ): path, transform = path_id if xo != 0 or yo != 0: transform = transform.frozen() transform.translate(xo, yo) renderer.draw_path(gc0, path, transform, rgbFace) gc.restore() renderer.close_group(self.__class__.__name__) self.stale = False def set_pickradius(self, pickradius): """ Set the pick radius used for containment tests. Parameters ---------- pickradius : float Pick radius, in points. """ if not isinstance(pickradius, Real): raise ValueError( f"pickradius must be a real-valued number, not {pickradius!r}") self._pickradius = pickradius def get_pickradius(self): return self._pickradius def contains(self, mouseevent): """ Test whether the mouse event occurred in the collection. Returns ``bool, dict(ind=itemlist)``, where every item in itemlist contains the event. """ if self._different_canvas(mouseevent) or not self.get_visible(): return False, {} pickradius = ( float(self._picker) if isinstance(self._picker, Number) and self._picker is not True # the bool, not just nonzero or 1 else self._pickradius) if self.axes: self.axes._unstale_viewLim() transform, offset_trf, offsets, paths = self._prepare_points() # Tests if the point is contained on one of the polygons formed # by the control points of each of the paths. A point is considered # "on" a path if it would lie within a stroke of width 2*pickradius # following the path. If pickradius <= 0, then we instead simply check # if the point is *inside* of the path instead. ind = _path.point_in_path_collection( mouseevent.x, mouseevent.y, pickradius, transform.frozen(), paths, self.get_transforms(), offsets, offset_trf, pickradius <= 0) return len(ind) > 0, dict(ind=ind) def set_urls(self, urls): """ Parameters ---------- urls : list of str or None Notes ----- URLs are currently only implemented by the SVG backend. They are ignored by all other backends. """ self._urls = urls if urls is not None else [None] self.stale = True def get_urls(self): """ Return a list of URLs, one for each element of the collection. The list contains *None* for elements without a URL. See :doc:`/gallery/misc/hyperlinks_sgskip` for an example. """ return self._urls def set_hatch(self, hatch): r""" Set the hatching pattern *hatch* can be one of:: / - diagonal hatching \ - back diagonal | - vertical - - horizontal + - crossed x - crossed diagonal o - small circle O - large circle . - dots * - stars Letters can be combined, in which case all the specified hatchings are done. If same letter repeats, it increases the density of hatching of that pattern. Unlike other properties such as linewidth and colors, hatching can only be specified for the collection as a whole, not separately for each member. Parameters ---------- hatch : {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'} """ # Use validate_hatch(list) after deprecation. mhatch._validate_hatch_pattern(hatch) self._hatch = hatch self.stale = True def get_hatch(self): """Return the current hatching pattern.""" return self._hatch def set_hatch_linewidth(self, lw): """Set the hatch linewidth.""" self._hatch_linewidth = lw def get_hatch_linewidth(self): """Return the hatch linewidth.""" return self._hatch_linewidth def set_offsets(self, offsets): """ Set the offsets for the collection. Parameters ---------- offsets : (N, 2) or (2,) array-like """ offsets = np.asanyarray(offsets) if offsets.shape == (2,): # Broadcast (2,) -> (1, 2) but nothing else. offsets = offsets[None, :] cstack = (np.ma.column_stack if isinstance(offsets, np.ma.MaskedArray) else np.column_stack) self._offsets = cstack( (np.asanyarray(self.convert_xunits(offsets[:, 0]), float), np.asanyarray(self.convert_yunits(offsets[:, 1]), float))) self.stale = True def get_offsets(self): """Return the offsets for the collection.""" # Default to zeros in the no-offset (None) case return np.zeros((1, 2)) if self._offsets is None else self._offsets def _get_default_linewidth(self): # This may be overridden in a subclass. return mpl.rcParams['patch.linewidth'] # validated as float def set_linewidth(self, lw): """ Set the linewidth(s) for the collection. *lw* can be a scalar or a sequence; if it is a sequence the patches will cycle through the sequence Parameters ---------- lw : float or list of floats """ if lw is None: lw = self._get_default_linewidth() # get the un-scaled/broadcast lw self._us_lw = np.atleast_1d(lw) # scale all of the dash patterns. self._linewidths, self._linestyles = self._bcast_lwls( self._us_lw, self._us_linestyles) self.stale = True def set_linestyle(self, ls): """ Set the linestyle(s) for the collection. =========================== ================= linestyle description =========================== ================= ``'-'`` or ``'solid'`` solid line ``'--'`` or ``'dashed'`` dashed line ``'-.'`` or ``'dashdot'`` dash-dotted line ``':'`` or ``'dotted'`` dotted line =========================== ================= Alternatively a dash tuple of the following form can be provided:: (offset, onoffseq), where ``onoffseq`` is an even length tuple of on and off ink in points. Parameters ---------- ls : str or tuple or list thereof Valid values for individual linestyles include {'-', '--', '-.', ':', '', (offset, on-off-seq)}. See `.Line2D.set_linestyle` for a complete description. """ # get the list of raw 'unscaled' dash patterns self._us_linestyles = mlines._get_dash_patterns(ls) # broadcast and scale the lw and dash patterns self._linewidths, self._linestyles = self._bcast_lwls( self._us_lw, self._us_linestyles) @_docstring.interpd def set_capstyle(self, cs): """ Set the `.CapStyle` for the collection (for all its elements). Parameters ---------- cs : `.CapStyle` or %(CapStyle)s """ self._capstyle = CapStyle(cs) @_docstring.interpd def get_capstyle(self): """ Return the cap style for the collection (for all its elements). Returns ------- %(CapStyle)s or None """ return self._capstyle.name if self._capstyle else None @_docstring.interpd def set_joinstyle(self, js): """ Set the `.JoinStyle` for the collection (for all its elements). Parameters ---------- js : `.JoinStyle` or %(JoinStyle)s """ self._joinstyle = JoinStyle(js) @_docstring.interpd def get_joinstyle(self): """ Return the join style for the collection (for all its elements). Returns ------- %(JoinStyle)s or None """ return self._joinstyle.name if self._joinstyle else None @staticmethod def _bcast_lwls(linewidths, dashes): """ Internal helper function to broadcast + scale ls/lw In the collection drawing code, the linewidth and linestyle are cycled through as circular buffers (via ``v[i % len(v)]``). Thus, if we are going to scale the dash pattern at set time (not draw time) we need to do the broadcasting now and expand both lists to be the same length. Parameters ---------- linewidths : list line widths of collection dashes : list dash specification (offset, (dash pattern tuple)) Returns ------- linewidths, dashes : list Will be the same length, dashes are scaled by paired linewidth """ if mpl.rcParams['_internal.classic_mode']: return linewidths, dashes # make sure they are the same length so we can zip them if len(dashes) != len(linewidths): l_dashes = len(dashes) l_lw = len(linewidths) gcd = math.gcd(l_dashes, l_lw) dashes = list(dashes) * (l_lw // gcd) linewidths = list(linewidths) * (l_dashes // gcd) # scale the dash patterns dashes = [mlines._scale_dashes(o, d, lw) for (o, d), lw in zip(dashes, linewidths)] return linewidths, dashes def get_antialiased(self): """ Get the antialiasing state for rendering. Returns ------- array of bools """ return self._antialiaseds def set_antialiased(self, aa): """ Set the antialiasing state for rendering. Parameters ---------- aa : bool or list of bools """ if aa is None: aa = self._get_default_antialiased() self._antialiaseds = np.atleast_1d(np.asarray(aa, bool)) self.stale = True def _get_default_antialiased(self): # This may be overridden in a subclass. return mpl.rcParams['patch.antialiased'] def set_color(self, c): """ Set the edgecolor, facecolor and hatchcolor. .. versionchanged:: 3.11 Now sets the hatchcolor as well. Parameters ---------- c : :mpltype:`color` or list of RGBA tuples See Also -------- Collection.set_facecolor, Collection.set_edgecolor, Collection.set_hatchcolor For setting the facecolor, edgecolor, and hatchcolor individually. """ self.set_facecolor(c) self.set_edgecolor(c) self.set_hatchcolor(c) def _get_default_facecolor(self): # This may be overridden in a subclass. return mpl.rcParams['patch.facecolor'] def _set_facecolor(self, c): if c is None: c = self._get_default_facecolor() self._facecolors = mcolors.to_rgba_array(c, self._alpha) self.stale = True def set_facecolor(self, c): """ Set the facecolor(s) of the collection. *c* can be a color (all patches have same color), or a sequence of colors; if it is a sequence the patches will cycle through the sequence. If *c* is 'none', the patch will not be filled. Parameters ---------- c : :mpltype:`color` or list of :mpltype:`color` """ if isinstance(c, str) and c.lower() in ("none", "face"): c = c.lower() self._original_facecolor = c self._set_facecolor(c) def get_facecolor(self): return self._facecolors def get_edgecolor(self): if cbook._str_equal(self._edgecolors, 'face'): return self.get_facecolor() else: return self._edgecolors def _get_default_edgecolor(self): # This may be overridden in a subclass. return mpl.rcParams['patch.edgecolor'] def get_hatchcolor(self): if cbook._str_equal(self._hatchcolors, 'edge'): if len(self.get_edgecolor()) == 0: return mpl.colors.to_rgba_array(self._get_default_edgecolor(), self._alpha) return self.get_edgecolor() return self._hatchcolors def _set_edgecolor(self, c): if c is None: if (mpl.rcParams['patch.force_edgecolor'] or self._edge_default or cbook._str_equal(self._original_facecolor, 'none')): c = self._get_default_edgecolor() else: c = 'none' if cbook._str_lower_equal(c, 'face'): self._edgecolors = 'face' self.stale = True return self._edgecolors = mcolors.to_rgba_array(c, self._alpha) self.stale = True def set_edgecolor(self, c): """ Set the edgecolor(s) of the collection. Parameters ---------- c : :mpltype:`color` or list of :mpltype:`color` or 'face' The collection edgecolor(s). If a sequence, the patches cycle through it. If 'face', match the facecolor. """ # We pass through a default value for use in LineCollection. # This allows us to maintain None as the default indicator in # _original_edgecolor. if isinstance(c, str) and c.lower() in ("none", "face"): c = c.lower() self._original_edgecolor = c self._set_edgecolor(c) def _set_hatchcolor(self, c): c = mpl._val_or_rc(c, 'hatch.color') if cbook._str_equal(c, 'edge'): self._hatchcolors = 'edge' else: self._hatchcolors = mcolors.to_rgba_array(c, self._alpha) self.stale = True def set_hatchcolor(self, c): """ Set the hatchcolor(s) of the collection. Parameters ---------- c : :mpltype:`color` or list of :mpltype:`color` or 'edge' The collection hatchcolor(s). If a sequence, the patches cycle through it. """ self._original_hatchcolor = c self._set_hatchcolor(c) def set_alpha(self, alpha): """ Set the transparency of the collection. Parameters ---------- alpha : float or array of float or None If not None, *alpha* values must be between 0 and 1, inclusive. If an array is provided, its length must match the number of elements in the collection. Masked values and nans are not supported. """ artist.Artist._set_alpha_for_array(self, alpha) self._set_facecolor(self._original_facecolor) self._set_edgecolor(self._original_edgecolor) self._set_hatchcolor(self._original_hatchcolor) set_alpha.__doc__ = artist.Artist._set_alpha_for_array.__doc__ def get_linewidth(self): return self._linewidths def get_linestyle(self): return self._linestyles def _set_mappable_flags(self): """ Determine whether edges and/or faces are color-mapped. This is a helper for update_scalarmappable. It sets Boolean flags '_edge_is_mapped' and '_face_is_mapped'. Returns ------- mapping_change : bool True if either flag is True, or if a flag has changed. """ # The flags are initialized to None to ensure this returns True # the first time it is called. edge0 = self._edge_is_mapped face0 = self._face_is_mapped # After returning, the flags must be Booleans, not None. self._edge_is_mapped = False self._face_is_mapped = False if self._A is not None: if not cbook._str_equal(self._original_facecolor, 'none'): self._face_is_mapped = True if cbook._str_equal(self._original_edgecolor, 'face'): self._edge_is_mapped = True else: if self._original_edgecolor is None: self._edge_is_mapped = True mapped = self._face_is_mapped or self._edge_is_mapped changed = (edge0 is None or face0 is None or self._edge_is_mapped != edge0 or self._face_is_mapped != face0) return mapped or changed def update_scalarmappable(self): """ Update colors from the scalar mappable array, if any. Assign colors to edges and faces based on the array and/or colors that were directly set, as appropriate. """ if not self._set_mappable_flags(): return # Allow possibility to call 'self.set_array(None)'. if self._A is not None: # QuadMesh can map 2d arrays (but pcolormesh supplies 1d array) if self._A.ndim > 1 and not isinstance(self, _MeshData): raise ValueError('Collections can only map rank 1 arrays') if np.iterable(self._alpha): if self._alpha.size != self._A.size: raise ValueError( f'Data array shape, {self._A.shape} ' 'is incompatible with alpha array shape, ' f'{self._alpha.shape}. ' 'This can occur with the deprecated ' 'behavior of the "flat" shading option, ' 'in which a row and/or column of the data ' 'array is dropped.') # pcolormesh, scatter, maybe others flatten their _A self._alpha = self._alpha.reshape(self._A.shape) self._mapped_colors = self.to_rgba(self._A, self._alpha) if self._face_is_mapped: self._facecolors = self._mapped_colors else: self._set_facecolor(self._original_facecolor) if self._edge_is_mapped: self._edgecolors = self._mapped_colors else: self._set_edgecolor(self._original_edgecolor) self.stale = True def get_fill(self): """Return whether face is colored.""" return not cbook._str_lower_equal(self._original_facecolor, "none") def update_from(self, other): """Copy properties from other to self.""" artist.Artist.update_from(self, other) self._antialiaseds = other._antialiaseds self._mapped_colors = other._mapped_colors self._edge_is_mapped = other._edge_is_mapped self._original_edgecolor = other._original_edgecolor self._edgecolors = other._edgecolors self._face_is_mapped = other._face_is_mapped self._original_facecolor = other._original_facecolor self._facecolors = other._facecolors self._linewidths = other._linewidths self._linestyles = other._linestyles self._us_linestyles = other._us_linestyles self._pickradius = other._pickradius self._hatch = other._hatch self._hatchcolors = other._hatchcolors # update_from for scalarmappable self._A = other._A self.norm = other.norm self.cmap = other.cmap self.stale = True
Collection
python
pytorch__pytorch
test/inductor/test_benchmark_fusion.py
{ "start": 1035, "end": 1503 }
class ____(InductorTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls._stack = contextlib.ExitStack() cls._stack.enter_context( config.patch( { "benchmark_kernel": True, "benchmark_fusion": True, } ) ) @classmethod def tearDownClass(cls): cls._stack.close() super().tearDownClass()
TestCase
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta/beta_tool_search_tool_bm25_20251119_param.py
{ "start": 350, "end": 1060 }
class ____(TypedDict, total=False): name: Required[Literal["tool_search_tool_bm25"]] """Name of the tool. This is how the tool will be called by the model and in `tool_use` blocks. """ type: Required[Literal["tool_search_tool_bm25_20251119", "tool_search_tool_bm25"]] allowed_callers: List[Literal["direct", "code_execution_20250825"]] cache_control: Optional[BetaCacheControlEphemeralParam] """Create a cache control breakpoint at this content block.""" defer_loading: bool """If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search. """ strict: bool
BetaToolSearchToolBm25_20251119Param
python
Textualize__textual
src/textual/command.py
{ "start": 1706, "end": 3061 }
class ____: """Holds the details of a single command search hit.""" score: float """The score of the command hit. The value should be between 0 (no match) and 1 (complete match). """ match_display: VisualType """A string or Rich renderable representation of the hit.""" command: IgnoreReturnCallbackType """The function to call when the command is chosen.""" text: str | None = None """The command text associated with the hit, as plain text. If `match_display` is not simple text, this attribute should be provided by the [Provider][textual.command.Provider] object. """ help: str | None = None """Optional help text for the command.""" @property def prompt(self) -> VisualType: """The prompt to use when displaying the hit in the command palette.""" return self.match_display def __lt__(self, other: object) -> bool: if isinstance(other, Hit): return self.score < other.score return NotImplemented def __eq__(self, other: object) -> bool: if isinstance(other, Hit): return self.score == other.score return NotImplemented def __post_init__(self) -> None: """Ensure 'text' is populated.""" if self.text is None: self.text = str(self.match_display) @dataclass
Hit
python
pytorch__pytorch
torch/__init__.py
{ "start": 72089, "end": 72311 }
class ____(_LegacyStorage): @classproperty def dtype(self): _warn_typed_storage_removal(stacklevel=3) return self._dtype @classproperty def _dtype(self): return torch.bool
BoolStorage
python
apache__airflow
helm-tests/tests/helm_tests/other/test_git_sync_webserver.py
{ "start": 914, "end": 9477 }
class ____: """Test git sync webserver.""" def test_should_add_dags_volume_to_the_webserver_if_git_sync_and_persistence_is_enabled(self): docs = render_chart( values={ "airflowVersion": "1.10.14", "dags": {"gitSync": {"enabled": True}, "persistence": {"enabled": True}}, }, show_only=["templates/webserver/webserver-deployment.yaml"], ) assert jmespath.search("spec.template.spec.volumes[1].name", docs[0]) == "dags" def test_should_add_dags_volume_to_the_webserver_if_git_sync_is_enabled_and_persistence_is_disabled(self): docs = render_chart( values={ "airflowVersion": "1.10.14", "dags": {"gitSync": {"enabled": True}, "persistence": {"enabled": False}}, }, show_only=["templates/webserver/webserver-deployment.yaml"], ) assert jmespath.search("spec.template.spec.volumes[1].name", docs[0]) == "dags" def test_should_add_git_sync_container_to_webserver_if_persistence_is_not_enabled_but_git_sync_is(self): docs = render_chart( values={ "airflowVersion": "1.10.14", "dags": { "gitSync": {"enabled": True, "containerName": "git-sync"}, "persistence": {"enabled": False}, }, }, show_only=["templates/webserver/webserver-deployment.yaml"], ) assert jmespath.search("spec.template.spec.containers[1].name", docs[0]) == "git-sync" def test_should_have_service_account_defined(self): docs = render_chart( values={ "airflowVersion": "2.10.0", "dags": {"gitSync": {"enabled": True}, "persistence": {"enabled": True}}, }, show_only=["templates/webserver/webserver-deployment.yaml"], ) assert ( jmespath.search("spec.template.spec.serviceAccountName", docs[0]) == "release-name-airflow-webserver" ) @pytest.mark.parametrize( ("airflow_version", "exclude_webserver"), [ ("2.0.0", True), ("2.0.2", True), ("1.10.14", False), ("1.9.0", False), ("2.1.0", True), ], ) def test_git_sync_with_different_airflow_versions(self, airflow_version, exclude_webserver): """If Airflow >= 2.0.0 - git sync related containers, volume mounts & volumes are not created.""" docs = render_chart( values={ "airflowVersion": airflow_version, "dags": { "gitSync": { "enabled": True, }, "persistence": {"enabled": False}, }, }, show_only=["templates/webserver/webserver-deployment.yaml"], ) containers_names = [ container["name"] for container in jmespath.search("spec.template.spec.containers", docs[0]) ] volume_mount_names = [ vm["name"] for vm in jmespath.search("spec.template.spec.containers[0].volumeMounts", docs[0]) ] volume_names = [volume["name"] for volume in jmespath.search("spec.template.spec.volumes", docs[0])] if exclude_webserver: assert "git-sync" not in containers_names assert "dags" not in volume_mount_names assert "dags" not in volume_names else: assert "git-sync" in containers_names assert "dags" in volume_mount_names assert "dags" in volume_names def test_should_add_env(self): docs = render_chart( values={ "airflowVersion": "1.10.14", "dags": { "gitSync": { "enabled": True, "env": [{"name": "FOO", "value": "bar"}], } }, }, show_only=["templates/webserver/webserver-deployment.yaml"], ) assert {"name": "FOO", "value": "bar"} in jmespath.search( "spec.template.spec.containers[1].env", docs[0] ) def test_resources_are_configurable(self): docs = render_chart( values={ "airflowVersion": "1.10.14", "dags": { "gitSync": { "enabled": True, "resources": { "limits": {"cpu": "200m", "memory": "128Mi"}, "requests": {"cpu": "300m", "memory": "169Mi"}, }, }, }, }, show_only=["templates/webserver/webserver-deployment.yaml"], ) assert jmespath.search("spec.template.spec.containers[1].resources.limits.memory", docs[0]) == "128Mi" assert ( jmespath.search("spec.template.spec.containers[1].resources.requests.memory", docs[0]) == "169Mi" ) assert jmespath.search("spec.template.spec.containers[1].resources.requests.cpu", docs[0]) == "300m" def test_validate_sshkeysecret_not_added_when_persistence_is_enabled(self): docs = render_chart( values={ "airflowVersion": "2.10.4", "dags": { "gitSync": { "enabled": True, "containerName": "git-sync-test", "sshKeySecret": "ssh-secret", "knownHosts": None, "branch": "test-branch", }, "persistence": {"enabled": True}, }, }, show_only=["templates/webserver/webserver-deployment.yaml"], ) assert "git-sync-ssh-key" not in jmespath.search("spec.template.spec.volumes[].name", docs[0]) def test_validate_if_ssh_params_are_added_with_git_ssh_key(self): docs = render_chart( values={ "airflowVersion": "1.10.14", "dags": { "gitSync": { "enabled": True, "sshKey": "dummy-ssh-key", }, "persistence": {"enabled": False}, }, }, show_only=["templates/webserver/webserver-deployment.yaml"], ) assert { "name": "git-sync-ssh-key", "secret": {"secretName": "release-name-ssh-secret", "defaultMode": 288}, } in jmespath.search("spec.template.spec.volumes", docs[0]) def test_liveliness_and_readiness_probes_are_configurable(self): """If Airflow < 2.0.0 - test git sync related containers, volume mounts & volumes are created.""" livenessProbe = { "failureThreshold": 10, "exec": {"command": ["/bin/true"]}, "initialDelaySeconds": 0, "periodSeconds": 1, "successThreshold": 1, "timeoutSeconds": 5, } readinessProbe = { "failureThreshold": 10, "exec": {"command": ["/bin/true"]}, "initialDelaySeconds": 0, "periodSeconds": 1, "successThreshold": 1, "timeoutSeconds": 5, } docs = render_chart( values={ "airflowVersion": "1.10.14", "dags": { "gitSync": { "enabled": True, "livenessProbe": livenessProbe, "readinessProbe": readinessProbe, }, }, }, show_only=["templates/webserver/webserver-deployment.yaml"], ) container_search_result = jmespath.search( "spec.template.spec.containers[?name == 'git-sync']", docs[0] ) init_container_search_result = jmespath.search( "spec.template.spec.initContainers[?name == 'git-sync-init']", docs[0] ) assert "livenessProbe" in container_search_result[0] assert "readinessProbe" in container_search_result[0] assert "readinessProbe" not in init_container_search_result[0] assert "readinessProbe" not in init_container_search_result[0] assert livenessProbe == container_search_result[0]["livenessProbe"] assert readinessProbe == container_search_result[0]["readinessProbe"]
TestGitSyncWebserver
python
PrefectHQ__prefect
src/prefect/_vendor/croniter/croniter.py
{ "start": 4252, "end": 4592 }
class ____(CroniterBadCronError): """Valid cron syntax, but likely to produce inaccurate results""" # Extending CroniterBadCronError, which may be contridatory, but this allows # catching both errors with a single exception. From a user perspective # these will likely be handled the same way.
CroniterUnsupportedSyntaxError
python
huggingface__transformers
src/transformers/models/moonshine/modular_moonshine.py
{ "start": 12560, "end": 17458 }
class ____(GlmAttention): def __init__( self, config: MoonshineConfig, layer_idx: int, is_causal: bool, num_attention_heads: int, num_key_value_heads: int, ): config.update({"num_attention_heads": num_attention_heads, "num_key_value_heads": num_key_value_heads}) super().__init__(config, layer_idx) self.is_causal = is_causal self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) # Pad head dimension to the next specified multiple. if self.config.pad_head_dim_to_multiple_of is not None: target_multiple = self.config.pad_head_dim_to_multiple_of target_head_dim = target_multiple * ((self.head_dim + target_multiple - 1) // target_multiple) self.head_dim_padding = target_head_dim - self.head_dim else: self.head_dim_padding = 0 def forward( self, hidden_states: torch.Tensor, position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, attention_mask: Optional[torch.Tensor] = None, past_key_values: Optional[Cache] = None, cache_position: Optional[torch.LongTensor] = None, key_value_states: Optional[torch.Tensor] = None, **kwargs: Unpack[FlashAttentionKwargs], ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]: bsz, q_len = hidden_states.shape[:-1] query_states = ( self.q_proj(hidden_states).view(bsz, q_len, self.config.num_key_value_heads, self.head_dim).transpose(1, 2) ) is_cross_attention = key_value_states is not None if past_key_values is not None: is_updated = past_key_values.is_updated.get(self.layer_idx) if is_cross_attention: # after the first generated id, we can subsequently re-use all key/value_states from cache past_key_values.is_updated[self.layer_idx] = True past_key_values = past_key_values.cross_attention_cache else: past_key_values = past_key_values.self_attention_cache # use key_value_states if cross attention current_states = key_value_states if key_value_states is not None else hidden_states if is_cross_attention and past_key_values and is_updated: key_states = past_key_values.layers[self.layer_idx].keys value_states = past_key_values.layers[self.layer_idx].values else: key_states = ( self.k_proj(current_states) .view(bsz, -1, self.config.num_key_value_heads, self.head_dim) .transpose(1, 2) ) value_states = ( self.v_proj(current_states) .view(bsz, -1, self.config.num_key_value_heads, self.head_dim) .transpose(1, 2) ) if is_cross_attention and past_key_values is not None: key_states, value_states = past_key_values.update( key_states, value_states, self.layer_idx, {"cache_position": cache_position} ) if not is_cross_attention: cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) if past_key_values is not None: cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} key_states, value_states = past_key_values.update( key_states, value_states, self.layer_idx, cache_kwargs ) attention_interface: Callable = eager_attention_forward if self.config._attn_implementation != "eager": attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation] is_causal = self.is_causal and attention_mask is None and q_len > 1 if self.head_dim_padding > 0: query_states = torch.nn.functional.pad(query_states, (0, self.head_dim_padding)) key_states = torch.nn.functional.pad(key_states, (0, self.head_dim_padding)) value_states = torch.nn.functional.pad(value_states, (0, self.head_dim_padding)) attn_output, attn_weights = attention_interface( self, query_states, key_states, value_states, attention_mask, dropout=0.0 if not self.training else self.attention_dropout, scaling=self.scaling, is_causal=is_causal, **kwargs, ) if self.head_dim_padding > 0: attn_output = attn_output[..., : -self.head_dim_padding] attn_output = attn_output.reshape(bsz, q_len, -1).contiguous() attn_output = self.o_proj(attn_output) return attn_output, attn_weights
MoonshineAttention
python
pyqtgraph__pyqtgraph
pyqtgraph/examples/relativity/relativity.py
{ "start": 11211, "end": 14921 }
class ____(object): nClocks = 0 def __init__(self, x0=0.0, y0=0.0, m0=1.0, v0=0.0, t0=0.0, color=None, prog=None, size=0.5): Clock.nClocks += 1 self.pen = pg.mkPen(color) self.brush = pg.mkBrush(color) self.y0 = y0 self.x0 = x0 self.v0 = v0 self.m0 = m0 self.t0 = t0 self.prog = prog self.size = size def init(self, nPts): ## Keep records of object from inertial frame as well as reference frame self.inertData = np.empty(nPts, dtype=[('x', float), ('t', float), ('v', float), ('pt', float), ('m', float), ('f', float)]) self.refData = np.empty(nPts, dtype=[('x', float), ('t', float), ('v', float), ('pt', float), ('m', float), ('f', float)]) ## Inertial frame variables self.x = self.x0 self.v = self.v0 self.m = self.m0 self.t = 0.0 ## reference clock always starts at 0 self.pt = self.t0 ## proper time starts at t0 ## reference frame variables self.refx = None self.refv = None self.refm = None self.reft = None self.recordFrame(0) def recordFrame(self, i): f = self.force() self.inertData[i] = (self.x, self.t, self.v, self.pt, self.m, f) self.refData[i] = (self.refx, self.reft, self.refv, self.pt, self.refm, f) def force(self, t=None): if len(self.prog) == 0: return 0.0 if t is None: t = self.pt ret = 0.0 for t1,f in self.prog: if t >= t1: ret = f return ret def acceleration(self, t=None): return self.force(t) / self.m0 def accelLimits(self): ## return the proper time values which bound the current acceleration command if len(self.prog) == 0: return -np.inf, np.inf t = self.pt ind = -1 for i, v in enumerate(self.prog): t1,f = v if t >= t1: ind = i if ind == -1: return -np.inf, self.prog[0][0] elif ind == len(self.prog)-1: return self.prog[-1][0], np.inf else: return self.prog[ind][0], self.prog[ind+1][0] def getCurve(self, ref=True): if ref is False: data = self.inertData else: data = self.refData[1:] x = data['x'] y = data['t'] curve = pg.PlotCurveItem(x=x, y=y, pen=self.pen) #x = self.data['x'] - ref.data['x'] #y = self.data['t'] step = 1.0 #mod = self.data['pt'] % step #inds = np.argwhere(abs(mod[1:] - mod[:-1]) > step*0.9) inds = [0] pt = data['pt'] for i in range(1,len(pt)): diff = pt[i] - pt[inds[-1]] if abs(diff) >= step: inds.append(i) inds = np.array(inds) #t = self.data['t'][inds] #x = self.data['x'][inds] pts = [] for i in inds: x = data['x'][i] y = data['t'][i] if i+1 < len(data): dpt = data['pt'][i+1]-data['pt'][i] dt = data['t'][i+1]-data['t'][i] else: dpt = 1 if dpt > 0: c = pg.mkBrush((0,0,0)) else: c = pg.mkBrush((200,200,200)) pts.append({'pos': (x, y), 'brush': c}) points = pg.ScatterPlotItem(pts, pen=self.pen, size=7) return curve, points
Clock
python
Farama-Foundation__Gymnasium
gymnasium/envs/registration.py
{ "start": 1735, "end": 8873 }
class ____: """A specification for creating environments with :meth:`gymnasium.make`. * **id**: The string used to create the environment with :meth:`gymnasium.make` * **entry_point**: A string for the environment location, ``(import path):(environment name)`` or a function that creates the environment. * **reward_threshold**: The reward threshold for completing the environment. * **nondeterministic**: If the observation of an environment cannot be repeated with the same initial state, random number generator state and actions. * **max_episode_steps**: The max number of steps that the environment can take before truncation * **order_enforce**: If to enforce the order of :meth:`gymnasium.Env.reset` before :meth:`gymnasium.Env.step` and :meth:`gymnasium.Env.render` functions * **disable_env_checker**: If to disable the environment checker wrapper in :meth:`gymnasium.make`, by default False (runs the environment checker) * **kwargs**: Additional keyword arguments passed to the environment during initialisation * **additional_wrappers**: A tuple of additional wrappers applied to the environment (WrapperSpec) * **vector_entry_point**: The location of the vectorized environment to create from Changelogs: v1.0.0 - Autoreset attribute removed """ id: str entry_point: EnvCreator | str | None = field(default=None) # Environment attributes reward_threshold: float | None = field(default=None) nondeterministic: bool = field(default=False) # Wrappers max_episode_steps: int | None = field(default=None) order_enforce: bool = field(default=True) disable_env_checker: bool = field(default=False) # Environment arguments kwargs: dict = field(default_factory=dict) # post-init attributes namespace: str | None = field(init=False) name: str = field(init=False) version: int | None = field(init=False) # applied wrappers additional_wrappers: tuple[WrapperSpec, ...] = field(default_factory=tuple) # Vectorized environment entry point vector_entry_point: VectorEnvCreator | str | None = field(default=None) def __post_init__(self): """Calls after the spec is created to extract the namespace, name and version from the environment id.""" self.namespace, self.name, self.version = parse_env_id(self.id) def make(self, **kwargs: Any) -> Env: """Calls ``make`` using the environment spec and any keyword arguments.""" return make(self, **kwargs) def to_json(self) -> str: """Converts the environment spec into a json compatible string. Returns: A jsonifyied string for the environment spec """ env_spec_dict = dataclasses.asdict(self) # As the namespace, name and version are initialised after `init` then we remove the attributes env_spec_dict.pop("namespace") env_spec_dict.pop("name") env_spec_dict.pop("version") # To check that the environment spec can be transformed to a json compatible type self._check_can_jsonify(env_spec_dict) return json.dumps(env_spec_dict) @staticmethod def _check_can_jsonify(env_spec: dict[str, Any]): """Warns the user about serialisation failing if the spec contains a callable. Args: env_spec: An environment or wrapper specification. Returns: The specification with lambda functions converted to strings. """ spec_name = env_spec["name"] if "name" in env_spec else env_spec["id"] for key, value in env_spec.items(): if callable(value): raise ValueError( f"Callable found in {spec_name} for {key} attribute with value={value}. Currently, Gymnasium does not support serialising callables." ) @staticmethod def from_json(json_env_spec: str) -> EnvSpec: """Converts a JSON string into a specification stack. Args: json_env_spec: A JSON string representing the env specification. Returns: An environment spec """ parsed_env_spec = json.loads(json_env_spec) applied_wrapper_specs: list[WrapperSpec] = [] for wrapper_spec_json in parsed_env_spec.pop("additional_wrappers"): try: applied_wrapper_specs.append(WrapperSpec(**wrapper_spec_json)) except Exception as e: raise ValueError( f"An issue occurred when trying to make {wrapper_spec_json} a WrapperSpec" ) from e try: env_spec = EnvSpec(**parsed_env_spec) env_spec.additional_wrappers = tuple(applied_wrapper_specs) except Exception as e: raise ValueError( f"An issue occurred when trying to make {parsed_env_spec} an EnvSpec" ) from e return env_spec def pprint( self, disable_print: bool = False, include_entry_points: bool = False, print_all: bool = False, ) -> str | None: """Pretty prints the environment spec. Args: disable_print: If to disable print and return the output include_entry_points: If to include the entry_points in the output print_all: If to print all information, including variables with default values Returns: If ``disable_print is True`` a string otherwise ``None`` """ output = f"id={self.id}" if print_all or include_entry_points: output += f"\nentry_point={self.entry_point}" if print_all or self.reward_threshold is not None: output += f"\nreward_threshold={self.reward_threshold}" if print_all or self.nondeterministic is not False: output += f"\nnondeterministic={self.nondeterministic}" if print_all or self.max_episode_steps is not None: output += f"\nmax_episode_steps={self.max_episode_steps}" if print_all or self.order_enforce is not True: output += f"\norder_enforce={self.order_enforce}" if print_all or self.disable_env_checker is not False: output += f"\ndisable_env_checker={self.disable_env_checker}" if print_all or self.additional_wrappers: wrapper_output: list[str] = [] for wrapper_spec in self.additional_wrappers: if include_entry_points: wrapper_output.append( f"\n\tname={wrapper_spec.name}, entry_point={wrapper_spec.entry_point}, kwargs={wrapper_spec.kwargs}" ) else: wrapper_output.append( f"\n\tname={wrapper_spec.name}, kwargs={wrapper_spec.kwargs}" ) if len(wrapper_output) == 0: output += "\nadditional_wrappers=[]" else: output += f"\nadditional_wrappers=[{','.join(wrapper_output)}\n]" if disable_print: return output else: print(output)
EnvSpec
python
pydantic__pydantic
pydantic/v1/types.py
{ "start": 27114, "end": 28411 }
class ____(SecretField): min_length: OptionalInt = None max_length: OptionalInt = None @classmethod def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: update_not_none( field_schema, type='string', writeOnly=True, format='password', minLength=cls.min_length, maxLength=cls.max_length, ) @classmethod def __get_validators__(cls) -> 'CallableGenerator': yield cls.validate yield constr_length_validator @classmethod def validate(cls, value: Any) -> 'SecretBytes': if isinstance(value, cls): return value value = bytes_validator(value) return cls(value) def __init__(self, value: bytes): self._secret_value = value def __repr__(self) -> str: return f"SecretBytes(b'{self}')" def __len__(self) -> int: return len(self._secret_value) def display(self) -> str: warnings.warn('`secret_bytes.display()` is deprecated, use `str(secret_bytes)` instead', DeprecationWarning) return str(self) def get_secret_value(self) -> bytes: return self._secret_value # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PAYMENT CARD TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SecretBytes
python
getsentry__sentry
src/sentry/testutils/cases.py
{ "start": 108901, "end": 110801 }
class ____(ActivityTestCase): def setUp(self): with assume_test_silo_mode(SiloMode.CONTROL): base_params = { "user_id": self.user.id, "scope_identifier": self.user.id, "scope_type": "user", "value": "always", } for type in ["workflow", "deploy", "alerts"]: NotificationSettingOption.objects.create( type=type, **base_params, ) # need to enable the provider options since msteams is disabled by default NotificationSettingProvider.objects.create( provider="msteams", type=type, **base_params, ) UserOption.objects.create(user=self.user, key="self_notifications", value="1") self.tenant_id = "50cccd00-7c9c-4b32-8cda-58a084f9334a" self.integration = self.create_integration( self.organization, self.tenant_id, metadata={ "access_token": "xoxb-xxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxx", "service_url": "https://testserviceurl.com/testendpoint/", "installation_type": "tenant", "expires_at": 1234567890, "tenant_id": self.tenant_id, }, name="Personal Installation", provider="msteams", ) self.idp = self.create_identity_provider(integration=self.integration) self.user_id_1 = "29:1XJKJMvc5GBtc2JwZq0oj8tHZmzrQgFmB39ATiQWA85gQtHieVkKilBZ9XHoq9j7Zaqt7CZ-NJWi7me2kHTL3Bw" self.user_1 = self.user self.identity_1 = self.create_identity( user=self.user_1, identity_provider=self.idp, external_id=self.user_id_1 ) @pytest.mark.usefixtures("reset_snuba")
MSTeamsActivityNotificationTest
python
PyCQA__pylint
doc/data/messages/t/too-many-ancestors/good.py
{ "start": 294, "end": 404 }
class ____(Vertebrate): has_beak = False has_fur = True lays_egg = False venomous = False
Mammal
python
django__django
tests/view_tests/tests/test_debug.py
{ "start": 50578, "end": 55539 }
class ____(SimpleTestCase): rf = RequestFactory() def test_request_and_exception(self): "A simple exception report can be generated" try: request = self.rf.get("/test_view/") request.user = User() raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) text = reporter.get_traceback_text() self.assertIn("ValueError at /test_view/", text) self.assertIn("Can't find my keys", text) self.assertIn("Request Method:", text) self.assertIn("Request URL:", text) self.assertIn("USER: jacob", text) self.assertIn("Exception Type:", text) self.assertIn("Exception Value:", text) self.assertIn("Traceback (most recent call last):", text) self.assertIn("Request information:", text) self.assertNotIn("Request data not supplied", text) def test_no_request(self): "An exception report can be generated without request" try: raise ValueError("Can't find my keys") except ValueError: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(None, exc_type, exc_value, tb) text = reporter.get_traceback_text() self.assertIn("ValueError", text) self.assertIn("Can't find my keys", text) self.assertNotIn("Request Method:", text) self.assertNotIn("Request URL:", text) self.assertNotIn("USER:", text) self.assertIn("Exception Type:", text) self.assertIn("Exception Value:", text) self.assertIn("Traceback (most recent call last):", text) self.assertIn("Request data not supplied", text) def test_no_exception(self): "An exception report can be generated for just a request" request = self.rf.get("/test_view/") reporter = ExceptionReporter(request, None, None, None) reporter.get_traceback_text() def test_request_and_message(self): "A message can be provided in addition to a request" request = self.rf.get("/test_view/") reporter = ExceptionReporter(request, None, "I'm a little teapot", None) reporter.get_traceback_text() @override_settings(DEBUG=True) def test_template_exception(self): request = self.rf.get("/test_view/") try: render(request, "debug/template_error.html") except Exception: exc_type, exc_value, tb = sys.exc_info() reporter = ExceptionReporter(request, exc_type, exc_value, tb) text = reporter.get_traceback_text() templ_path = Path( Path(__file__).parents[1], "templates", "debug", "template_error.html" ) self.assertIn( "Template error:\n" "In template %(path)s, error at line 2\n" " 'cycle' tag requires at least two arguments\n" " 1 : Template with error:\n" " 2 : {%% cycle %%} \n" " 3 : " % {"path": templ_path}, text, ) def test_request_with_items_key(self): """ An exception report can be generated for requests with 'items' in request GET, POST, FILES, or COOKIES QueryDicts. """ # GET request = self.rf.get("/test_view/?items=Oops") reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) # POST request = self.rf.post("/test_view/", data={"items": "Oops"}) reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) # FILES fp = StringIO("filecontent") request = self.rf.post("/test_view/", data={"name": "filename", "items": fp}) reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = <InMemoryUploadedFile:", text) # COOKIES rf = RequestFactory() rf.cookies["items"] = "Oops" request = rf.get("/test_view/") reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("items = 'Oops'", text) def test_message_only(self): reporter = ExceptionReporter(None, None, "I'm a little teapot", None) reporter.get_traceback_text() @override_settings(ALLOWED_HOSTS="example.com") def test_disallowed_host(self): "An exception report can be generated even for a disallowed host." request = self.rf.get("/", headers={"host": "evil.com"}) reporter = ExceptionReporter(request, None, None, None) text = reporter.get_traceback_text() self.assertIn("http://evil.com/", text)
PlainTextReportTests
python
pytorch__pytorch
torch/serialization.py
{ "start": 25625, "end": 26161 }
class ____(_opener[IO[bytes]]): def __exit__(self, *args): self.file_like.flush() def _open_file_like(name_or_buffer: FileLike, mode: str) -> _opener[IO[bytes]]: if _is_path(name_or_buffer): return _open_file(name_or_buffer, mode) else: if "w" in mode: return _open_buffer_writer(name_or_buffer) elif "r" in mode: return _open_buffer_reader(name_or_buffer) else: raise RuntimeError(f"Expected 'r' or 'w' in mode but got {mode}")
_open_buffer_writer
python
ethereum__web3.py
web3/exceptions.py
{ "start": 2080, "end": 2224 }
class ____(Web3Exception): """ Raised by a provider to signal that too many requests have been made consecutively. """
TooManyRequests
python
pypa__pip
src/pip/_vendor/msgpack/exceptions.py
{ "start": 341, "end": 424 }
class ____(ValueError, UnpackException): """Invalid msgpack format"""
FormatError
python
getsentry__sentry
src/sentry/relocation/models/relocation.py
{ "start": 8188, "end": 11130 }
class ____(DefaultFieldsModelExisting): """ A `RelocationFile` is an association between a `Relocation` and a `File`. This model should be created in an atomic transaction with the `Relocation` and `File` it points to. """ __relocation_scope__ = RelocationScope.Excluded # Several different kinds of encrypted JSON files can be created during the `Relocation` # process. This enum allows us to identify which file we're currently handling. class Kind(Enum): UNKNOWN = 0 # The raw (hopefully encrypted!) export tarball that the user has provided us. RAW_USER_DATA = 1 # A normalized version of the user data. # # TODO(getsentry/team-ospo#216): Add a normalization step to the relocation flow NORMALIZED_USER_DATA = 2 # The global configuration we're going to validate against - pulled from the live Sentry # instance, not supplied by the user. # # Note: These files are only ever stored in the relocation-specific GCP bucket, never in the # main filestore, so in practice no DB entry should have this value set. BASELINE_CONFIG_VALIDATION_DATA = 3 # (Deprecated) The colliding users we're going to validate against - pulled from the live # Sentry instance, not supplied by the user. However, to determine what is a "colliding # user", we must inspect the user-provided data. # # Note: These files are only ever stored in the relocation-specific GCP bucket, never in the # main filestore, so in practice no DB entry should have this value set. COLLIDING_USERS_VALIDATION_DATA = 4 # TODO(getsentry/team-ospo#190): Could we dedup this with a mixin in the future? @classmethod def get_choices(cls) -> list[tuple[int, str]]: return [(key.value, key.name) for key in cls] def __str__(self) -> str: if self.name == "RAW_USER_DATA": return "raw-relocation-data" elif self.name == "NORMALIZED_USER_DATA": return "normalized-relocation-data" elif self.name == "BASELINE_CONFIG_VALIDATION_DATA": return "baseline-config" elif self.name == "COLLIDING_USERS_VALIDATION_DATA": return "colliding-users" else: raise ValueError("Cannot extract a filename from `RelocationFile.Kind.UNKNOWN`.") def to_filename(self, ext: str): return str(self) + "." + ext relocation = FlexibleForeignKey("sentry.Relocation") file = FlexibleForeignKey("sentry.File") kind = models.SmallIntegerField(choices=Kind.get_choices()) __repr__ = sane_repr("relocation", "file") class Meta: unique_together = (("relocation", "file"), ("relocation", "kind")) app_label = "sentry" db_table = "sentry_relocationfile" @unique
RelocationFile
python
pyca__cryptography
tests/hazmat/primitives/test_hkdf_vectors.py
{ "start": 797, "end": 986 }
class ____: test_hkdfsha256 = generate_hkdf_test( load_nist_vectors, os.path.join("KDF"), ["rfc-5869-HKDF-SHA256.txt"], hashes.SHA256(), )
TestHKDFSHA256
python
pytorch__pytorch
torch/distributed/argparse_util.py
{ "start": 297, "end": 2221 }
class ____(Action): """ Get argument values from ``PET_{dest}`` before defaulting to the given ``default`` value. For flags (e.g. ``--standalone``) use ``check_env`` instead. .. note:: when multiple option strings are specified, ``dest`` is the longest option string (e.g. for ``"-f", "--foo"`` the env var to set is ``PET_FOO`` not ``PET_F``) Example: :: parser.add_argument("-f", "--foo", action=env, default="bar") ./program -> args.foo="bar" ./program -f baz -> args.foo="baz" ./program --foo baz -> args.foo="baz" PET_FOO="env_bar" ./program -f baz -> args.foo="baz" PET_FOO="env_bar" ./program --foo baz -> args.foo="baz" PET_FOO="env_bar" ./program -> args.foo="env_bar" parser.add_argument("-f", "--foo", action=env, required=True) ./program -> fails ./program -f baz -> args.foo="baz" PET_FOO="env_bar" ./program -> args.foo="env_bar" PET_FOO="env_bar" ./program -f baz -> args.foo="baz" """ def __init__(self, dest, default=None, required=False, **kwargs) -> None: env_name = f"PET_{dest.upper()}" default = os.environ.get(env_name, default) # ``required`` means that it NEEDS to be present in the command-line args # rather than "this option requires a value (either set explicitly or default" # so if we found default then we don't "require" it to be in the command-line # so set it to False if default: required = False super().__init__(dest=dest, default=default, required=required, **kwargs) def __call__(self, parser, namespace, values, option_string=None): setattr(namespace, self.dest, values)
env
python
wandb__wandb
wandb/vendor/pygments/lexers/prolog.py
{ "start": 458, "end": 3126 }
class ____(RegexLexer): """ Lexer for Prolog files. """ name = 'Prolog' aliases = ['prolog'] filenames = ['*.ecl', '*.prolog', '*.pro', '*.pl'] mimetypes = ['text/x-prolog'] flags = re.UNICODE | re.MULTILINE tokens = { 'root': [ (r'^#.*', Comment.Single), (r'/\*', Comment.Multiline, 'nested-comment'), (r'%.*', Comment.Single), # character literal (r'0\'.', String.Char), (r'0b[01]+', Number.Bin), (r'0o[0-7]+', Number.Oct), (r'0x[0-9a-fA-F]+', Number.Hex), # literal with prepended base (r'\d\d?\'[a-zA-Z0-9]+', Number.Integer), (r'(\d+\.\d*|\d*\.\d+)([eE][+-]?[0-9]+)?', Number.Float), (r'\d+', Number.Integer), (r'[\[\](){}|.,;!]', Punctuation), (r':-|-->', Punctuation), (r'"(?:\\x[0-9a-fA-F]+\\|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|' r'\\[0-7]+\\|\\["\nabcefnrstv]|[^\\"])*"', String.Double), (r"'(?:''|[^'])*'", String.Atom), # quoted atom # Needs to not be followed by an atom. # (r'=(?=\s|[a-zA-Z\[])', Operator), (r'is\b', Operator), (r'(<|>|=<|>=|==|=:=|=|/|//|\*|\+|-)(?=\s|[a-zA-Z0-9\[])', Operator), (r'(mod|div|not)\b', Operator), (r'_', Keyword), # The don't-care variable (r'([a-z]+)(:)', bygroups(Name.Namespace, Punctuation)), (u'([a-z\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]' u'[\w$\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]*)' u'(\\s*)(:-|-->)', bygroups(Name.Function, Text, Operator)), # function defn (u'([a-z\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]' u'[\w$\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]*)' u'(\\s*)(\\()', bygroups(Name.Function, Text, Punctuation)), (u'[a-z\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]' u'[\w$\u00c0-\u1fff\u3040-\ud7ff\ue000-\uffef]*', String.Atom), # atom, characters # This one includes ! (u'[#&*+\\-./:<=>?@\\\\^~\u00a1-\u00bf\u2010-\u303f]+', String.Atom), # atom, graphics (r'[A-Z_]\w*', Name.Variable), (u'\\s+|[\u2000-\u200f\ufff0-\ufffe\uffef]', Text), ], 'nested-comment': [ (r'\*/', Comment.Multiline, '#pop'), (r'/\*', Comment.Multiline, '#push'), (r'[^*/]+', Comment.Multiline), (r'[*/]', Comment.Multiline), ], } def analyse_text(text): return ':-' in text
PrologLexer
python
numpy__numpy
numpy/_core/tests/test_multiarray.py
{ "start": 212378, "end": 216003 }
class ____: def _check_range(self, x, cmin, cmax): assert_(np.all(x >= cmin)) assert_(np.all(x <= cmax)) def _clip_type(self, type_group, array_max, clip_min, clip_max, inplace=False, expected_min=None, expected_max=None): if expected_min is None: expected_min = clip_min if expected_max is None: expected_max = clip_max for T in np._core.sctypes[type_group]: if sys.byteorder == 'little': byte_orders = ['=', '>'] else: byte_orders = ['<', '='] for byteorder in byte_orders: dtype = np.dtype(T).newbyteorder(byteorder) x = (np.random.random(1000) * array_max).astype(dtype) if inplace: # The tests that call us pass clip_min and clip_max that # might not fit in the destination dtype. They were written # assuming the previous unsafe casting, which now must be # passed explicitly to avoid a warning. x.clip(clip_min, clip_max, x, casting='unsafe') else: x = x.clip(clip_min, clip_max) byteorder = '=' if x.dtype.byteorder == '|': byteorder = '|' assert_equal(x.dtype.byteorder, byteorder) self._check_range(x, expected_min, expected_max) return x def test_basic(self): for inplace in [False, True]: self._clip_type( 'float', 1024, -12.8, 100.2, inplace=inplace) self._clip_type( 'float', 1024, 0, 0, inplace=inplace) self._clip_type( 'int', 1024, -120, 100, inplace=inplace) self._clip_type( 'int', 1024, 0, 0, inplace=inplace) self._clip_type( 'uint', 1024, 0, 0, inplace=inplace) self._clip_type( 'uint', 1024, 10, 100, inplace=inplace) @pytest.mark.parametrize("inplace", [False, True]) def test_int_out_of_range(self, inplace): # Simple check for out-of-bound integers, also testing the in-place # path. x = (np.random.random(1000) * 255).astype("uint8") out = np.empty_like(x) res = x.clip(-1, 300, out=out if inplace else None) assert res is out or not inplace assert (res == x).all() res = x.clip(-1, 50, out=out if inplace else None) assert res is out or not inplace assert (res <= 50).all() assert (res[x <= 50] == x[x <= 50]).all() res = x.clip(100, 1000, out=out if inplace else None) assert res is out or not inplace assert (res >= 100).all() assert (res[x >= 100] == x[x >= 100]).all() def test_record_array(self): rec = np.array([(-5, 2.0, 3.0), (5.0, 4.0, 3.0)], dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8')]) y = rec['x'].clip(-0.3, 0.5) self._check_range(y, -0.3, 0.5) def test_max_or_min(self): val = np.array([0, 1, 2, 3, 4, 5, 6, 7]) x = val.clip(3) assert_(np.all(x >= 3)) x = val.clip(min=3) assert_(np.all(x >= 3)) x = val.clip(max=4) assert_(np.all(x <= 4)) def test_nan(self): input_arr = np.array([-2., np.nan, 0.5, 3., 0.25, np.nan]) result = input_arr.clip(-1, 1) expected = np.array([-1., np.nan, 0.5, 1., 0.25, np.nan]) assert_array_equal(result, expected)
TestClip
python
getsentry__sentry
tools/mypy_helpers/plugin.py
{ "start": 6404, "end": 8595 }
class ____(Plugin): def get_function_signature_hook( self, fullname: str ) -> Callable[[FunctionSigContext], FunctionLike] | None: return _FUNCTION_SIGNATURE_HOOKS.get(fullname) def get_method_signature_hook( self, fullname: str ) -> Callable[[MethodSigContext], FunctionLike] | None: if fullname.startswith("django.core.cache.backends.base.BaseCache."): return _modify_base_cache_version_type else: return None def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None: if fullname in ( "django.core.cache.backends.base.BaseCache.adecr_version", "django.core.cache.backends.base.BaseCache.aincr_version", "django.core.cache.backends.base.BaseCache.decr_version", "django.core.cache.backends.base.BaseCache.incr_version", ): return _remove_base_cache_decr_incr else: return None def get_customize_class_mro_hook( self, fullname: str ) -> Callable[[ClassDefContext], None] | None: if fullname == "django.http.request.HttpRequest": return _adjust_http_request_members elif fullname == "rest_framework.request.Request": return _adjust_request_members elif fullname == "django.http.response.HttpResponseBase": return _adjust_http_response_members else: return None def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None: if fullname.startswith("sentry.utils.lazy_service_wrapper.LazyServiceWrapper."): _, attr = fullname.rsplit(".", 1) return functools.partial(_lazy_service_wrapper_attribute, attr=attr) else: return None def get_additional_deps(self, file: MypyFile) -> list[tuple[int, str, int]]: if file.fullname in {"django.http", "django.http.request", "rest_framework.request"}: return [(PRI_MYPY, "sentry.auth.services.auth.model", -1)] else: return [] def plugin(version: str) -> type[SentryMypyPlugin]: return SentryMypyPlugin
SentryMypyPlugin
python
crytic__slither
slither/core/declarations/custom_error_contract.py
{ "start": 237, "end": 625 }
class ____(CustomError, ContractLevel): def is_declared_by(self, contract: "Contract") -> bool: """ Check if the element is declared by the contract :param contract: :return: """ return self.contract == contract @property def canonical_name(self) -> str: return self.contract.name + "." + self.full_name
CustomErrorContract
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingCallable1.py
{ "start": 730, "end": 1674 }
class ____: def bar(self) -> None: pass def test2(o: ClassA) -> None: if callable(o): reveal_type(o, expected_text="<callable subtype of ClassA>") # This should generate an error o.foo() o.bar() r1 = o(1, 2, 3) reveal_type(r1, expected_text="Unknown") else: o.bar() # This should generate an error o(1, 2, 3) _T2 = TypeVar("_T2", int, str, Callable[[], int], Callable[[], str]) def test3(v: _T2) -> Union[_T2, int, str]: if callable(v): reveal_type(v, expected_text="(() -> int) | (() -> str)") reveal_type(v(), expected_text="int* | str*") return v() else: reveal_type(v, expected_text="int* | str*") return v def test4(v: type[int] | object): if callable(v): reveal_type(v, expected_text="type[int] | ((...) -> object)") else: reveal_type(v, expected_text="object")
ClassA
python
tensorflow__tensorflow
tensorflow/python/ops/parallel_for/control_flow_ops_test.py
{ "start": 51435, "end": 54325 }
class ____(PForTestCase): def test_loop_variant_scatter_update_no_shape(self): if test_util.is_gpu_available(): self.skipTest( "Flaky in some GPU configurations due to TensorScatterNdUpdate " "nondeterminism.") @def_function.function(input_signature=[ tensor_spec.TensorSpec(shape=None, dtype=dtypes.int32), tensor_spec.TensorSpec(shape=None, dtype=dtypes.int32), tensor_spec.TensorSpec(shape=None, dtype=dtypes.int32) ]) def shapeless_func(tensor, indices, updates): return array_ops.tensor_scatter_nd_update(tensor, indices, updates) def loop_fn(i): tensor = [0, 0, 0, 0, 0, 0, 0, 0] indices = [[i], [i + 1], [i + 3], [i + 2]] updates = [i, i - 10, i + 11, 12] return shapeless_func(tensor, indices, updates) self._test_loop_fn(loop_fn, 5) def test_loop_variant_scatter_update_singles(self): if test_util.is_gpu_available(): self.skipTest( "Flaky in some GPU configurations due to TensorScatterNdUpdate " "nondeterminism.") def loop_fn(i): tensor = [0, 0, 0, 0, 0, 0, 0, 0] indices = [[i], [i+1], [i+3], [i+2]] updates = [i, i-10, i+11, 12] return array_ops.tensor_scatter_nd_update(tensor, indices, updates) self._test_loop_fn(loop_fn, 5) def test_loop_variant_scatter_update_slices(self): if test_util.is_gpu_available(): self.skipTest( "Flaky in some GPU configurations due to TensorScatterNdUpdate " "nondeterminism.") def loop_fn(i): tensor = array_ops.zeros([10, 3], dtype=dtypes.int32) indices = [[i+2], [4]] updates = [[1, i*2, 3], [i+4, i-5, 6]] return array_ops.tensor_scatter_nd_update(tensor, indices, updates) self._test_loop_fn(loop_fn, 5) def test_loop_variant_scatter_update_multi_dim_index(self): if test_util.is_gpu_available(): self.skipTest( "Flaky in some GPU configurations due to TensorScatterNdUpdate " "nondeterminism.") def loop_fn(i): tensor = array_ops.zeros([10, 3], dtype=dtypes.int32) indices = [[i+2, 1], [4, 2]] updates = [i, 5] return array_ops.tensor_scatter_nd_update(tensor, indices, updates) self._test_loop_fn(loop_fn, 5) def test_loop_variant_scatter_update_folded_indices(self): if test_util.is_gpu_available(): self.skipTest( "Flaky in some GPU configurations due to TensorScatterNdUpdate " "nondeterminism.") def loop_fn(i): tensor = array_ops.zeros([5, 5]) indices = [ [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]], [[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]], ] updates = [ [1, i, 1, 1, 1], [1, 1, i+2, 1, i-5], ] return array_ops.tensor_scatter_nd_update(tensor, indices, updates) self._test_loop_fn(loop_fn, 5)
TensorTest
python
apache__airflow
dev/breeze/src/airflow_breeze/prepare_providers/provider_distributions.py
{ "start": 1324, "end": 1428 }
class ____(Exception): """Tag already exist for the package."""
PrepareReleasePackageTagExistException
python
scipy__scipy
benchmarks/benchmarks/spatial.py
{ "start": 10038, "end": 10497 }
class ____(Benchmark): params = [10, 100, 1000, 5000, 10000] param_names = ['num_points'] def setup(self, num_points): self.points = generate_spherical_points(num_points) def time_spherical_voronoi_calculation(self, num_points): """Perform spherical Voronoi calculation, but not the sorting of vertices in the Voronoi polygons. """ SphericalVoronoi(self.points, radius=1, center=np.zeros(3))
SphericalVor
python
pyinstaller__pyinstaller
bootloader/waflib/Tools/javaw.py
{ "start": 7518, "end": 8881 }
class ____(JTask): color = 'BLUE' run_str = '${JAVAC} -classpath ${CLASSPATH} -d ${OUTDIR} ${JAVACFLAGS} ${SRC}' vars = ['CLASSPATH', 'JAVACFLAGS', 'JAVAC', 'OUTDIR'] def uid(self): lst = [self.__class__.__name__, self.generator.outdir.abspath()] for x in self.srcdir: lst.append(x.abspath()) return Utils.h_list(lst) def runnable_status(self): for t in self.run_after: if not t.hasrun: return Task.ASK_LATER if not self.inputs: self.inputs = [] for x in self.srcdir: if x.exists(): self.inputs.extend(x.ant_glob(SOURCE_RE, remove=False, quiet=True)) return super(javac, self).runnable_status() def post_run(self): for node in self.generator.outdir.ant_glob('**/*.class', quiet=True): self.generator.bld.node_sigs[node] = self.uid() self.generator.bld.task_sigs[self.uid()] = self.cache_sig @feature('javadoc') @after_method('process_rule') def create_javadoc(self): tsk = self.create_task('javadoc') tsk.classpath = getattr(self, 'classpath', []) self.javadoc_package = Utils.to_list(self.javadoc_package) if not isinstance(self.javadoc_output, Node.Node): self.javadoc_output = self.bld.path.find_or_declare(self.javadoc_output)
javac
python
pyca__cryptography
src/cryptography/x509/extensions.py
{ "start": 58875, "end": 59589 }
class ____(ExtensionType): oid = OCSPExtensionOID.NONCE def __init__(self, nonce: bytes) -> None: if not isinstance(nonce, bytes): raise TypeError("nonce must be bytes") self._nonce = nonce def __eq__(self, other: object) -> bool: if not isinstance(other, OCSPNonce): return NotImplemented return self.nonce == other.nonce def __hash__(self) -> int: return hash(self.nonce) def __repr__(self) -> str: return f"<OCSPNonce(nonce={self.nonce!r})>" @property def nonce(self) -> bytes: return self._nonce def public_bytes(self) -> bytes: return rust_x509.encode_extension_value(self)
OCSPNonce
python
PrefectHQ__prefect
src/prefect/client/schemas/filters.py
{ "start": 4305, "end": 4749 }
class ____(PrefectBaseModel, OperatorMixin): """Filter by `FlowRun.work_queue_name`.""" any_: Optional[List[str]] = Field( default=None, description="A list of work queue names to include", examples=[["work_queue_1", "work_queue_2"]], ) is_null_: Optional[bool] = Field( default=None, description="If true, only include flow runs without work queue names", )
FlowRunFilterWorkQueueName
python
django__django
tests/forms_tests/tests/test_formsets.py
{ "start": 1750, "end": 69584 }
class ____(SimpleTestCase): def make_choiceformset( self, formset_data=None, formset_class=ChoiceFormSet, total_forms=None, initial_forms=0, max_num_forms=0, min_num_forms=0, **kwargs, ): """ Make a ChoiceFormset from the given formset_data. The data should be given as a list of (choice, votes) tuples. """ kwargs.setdefault("prefix", "choices") kwargs.setdefault("auto_id", False) if formset_data is None: return formset_class(**kwargs) if total_forms is None: total_forms = len(formset_data) def prefixed(*args): args = (kwargs["prefix"],) + args return "-".join(args) data = { prefixed("TOTAL_FORMS"): str(total_forms), prefixed("INITIAL_FORMS"): str(initial_forms), prefixed("MAX_NUM_FORMS"): str(max_num_forms), prefixed("MIN_NUM_FORMS"): str(min_num_forms), } for i, (choice, votes) in enumerate(formset_data): data[prefixed(str(i), "choice")] = choice data[prefixed(str(i), "votes")] = votes return formset_class(data, **kwargs) def test_basic_formset(self): """ A FormSet constructor takes the same arguments as Form. Create a FormSet for adding data. By default, it displays 1 blank form. """ formset = self.make_choiceformset() self.assertHTMLEqual( str(formset), """<input type="hidden" name="choices-TOTAL_FORMS" value="1"> <input type="hidden" name="choices-INITIAL_FORMS" value="0"> <input type="hidden" name="choices-MIN_NUM_FORMS" value="0"> <input type="hidden" name="choices-MAX_NUM_FORMS" value="1000"> <div>Choice:<input type="text" name="choices-0-choice"></div> <div>Votes:<input type="number" name="choices-0-votes"></div>""", ) # FormSet are treated similarly to Forms. FormSet has an is_valid() # method, and a cleaned_data or errors attribute depending on whether # all the forms passed validation. However, unlike a Form, cleaned_data # and errors will be a list of dicts rather than a single dict. formset = self.make_choiceformset([("Calexico", "100")]) self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.forms], [{"votes": 100, "choice": "Calexico"}], ) # If a FormSet wasn't passed any data, is_valid() and has_changed() # return False. formset = self.make_choiceformset() self.assertFalse(formset.is_valid()) self.assertFalse(formset.has_changed()) def test_formset_name(self): ArticleFormSet = formset_factory(ArticleForm) ChoiceFormSet = formset_factory(Choice) self.assertEqual(ArticleFormSet.__name__, "ArticleFormSet") self.assertEqual(ChoiceFormSet.__name__, "ChoiceFormSet") def test_form_kwargs_formset(self): """ Custom kwargs set on the formset instance are passed to the underlying forms. """ FormSet = formset_factory(CustomKwargForm, extra=2) formset = FormSet(form_kwargs={"custom_kwarg": 1}) for form in formset: self.assertTrue(hasattr(form, "custom_kwarg")) self.assertEqual(form.custom_kwarg, 1) def test_form_kwargs_formset_dynamic(self): """Form kwargs can be passed dynamically in a formset.""" class DynamicBaseFormSet(BaseFormSet): def get_form_kwargs(self, index): return {"custom_kwarg": index} DynamicFormSet = formset_factory( CustomKwargForm, formset=DynamicBaseFormSet, extra=2 ) formset = DynamicFormSet(form_kwargs={"custom_kwarg": "ignored"}) for i, form in enumerate(formset): self.assertTrue(hasattr(form, "custom_kwarg")) self.assertEqual(form.custom_kwarg, i) def test_form_kwargs_empty_form(self): FormSet = formset_factory(CustomKwargForm) formset = FormSet(form_kwargs={"custom_kwarg": 1}) self.assertTrue(hasattr(formset.empty_form, "custom_kwarg")) self.assertEqual(formset.empty_form.custom_kwarg, 1) def test_empty_permitted_ignored_empty_form(self): formset = ArticleFormSet(form_kwargs={"empty_permitted": False}) self.assertIs(formset.empty_form.empty_permitted, True) def test_formset_validation(self): # FormSet instances can also have an error attribute if validation # failed for any of the forms. formset = self.make_choiceformset([("Calexico", "")]) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{"votes": ["This field is required."]}]) def test_formset_validation_count(self): """ A formset's ManagementForm is validated once per FormSet.is_valid() call and each form of the formset is cleaned once. """ def make_method_counter(func): """Add a counter to func for the number of times it's called.""" counter = Counter() counter.call_count = 0 def mocked_func(*args, **kwargs): counter.call_count += 1 return func(*args, **kwargs) return mocked_func, counter mocked_is_valid, is_valid_counter = make_method_counter( formsets.ManagementForm.is_valid ) mocked_full_clean, full_clean_counter = make_method_counter(BaseForm.full_clean) formset = self.make_choiceformset( [("Calexico", "100"), ("Any1", "42"), ("Any2", "101")] ) with ( mock.patch( "django.forms.formsets.ManagementForm.is_valid", mocked_is_valid ), mock.patch("django.forms.forms.BaseForm.full_clean", mocked_full_clean), ): self.assertTrue(formset.is_valid()) self.assertEqual(is_valid_counter.call_count, 1) self.assertEqual(full_clean_counter.call_count, 4) def test_formset_has_changed(self): """ FormSet.has_changed() is True if any data is passed to its forms, even if the formset didn't validate. """ blank_formset = self.make_choiceformset([("", "")]) self.assertFalse(blank_formset.has_changed()) # invalid formset invalid_formset = self.make_choiceformset([("Calexico", "")]) self.assertFalse(invalid_formset.is_valid()) self.assertTrue(invalid_formset.has_changed()) # valid formset valid_formset = self.make_choiceformset([("Calexico", "100")]) self.assertTrue(valid_formset.is_valid()) self.assertTrue(valid_formset.has_changed()) def test_formset_initial_data(self): """ A FormSet can be prefilled with existing data by providing a list of dicts to the `initial` argument. By default, an extra blank form is included. """ formset = self.make_choiceformset( initial=[{"choice": "Calexico", "votes": 100}] ) self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), '<li>Choice: <input type="text" name="choices-0-choice" value="Calexico">' "</li>" '<li>Votes: <input type="number" name="choices-0-votes" value="100"></li>' '<li>Choice: <input type="text" name="choices-1-choice"></li>' '<li>Votes: <input type="number" name="choices-1-votes"></li>', ) def test_blank_form_unfilled(self): """A form that's displayed as blank may be submitted as blank.""" formset = self.make_choiceformset( [("Calexico", "100"), ("", "")], initial_forms=1 ) self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.forms], [{"votes": 100, "choice": "Calexico"}, {}], ) def test_second_form_partially_filled(self): """ If at least one field is filled out on a blank form, it will be validated. """ formset = self.make_choiceformset( [("Calexico", "100"), ("The Decemberists", "")], initial_forms=1 ) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{}, {"votes": ["This field is required."]}]) def test_delete_prefilled_data(self): """ Deleting prefilled data is an error. Removing data from form fields isn't the proper way to delete it. """ formset = self.make_choiceformset([("", ""), ("", "")], initial_forms=1) self.assertFalse(formset.is_valid()) self.assertEqual( formset.errors, [ { "votes": ["This field is required."], "choice": ["This field is required."], }, {}, ], ) def test_displaying_more_than_one_blank_form(self): """ More than 1 empty form can be displayed using formset_factory's `extra` argument. """ ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(auto_id=False, prefix="choices") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice"></li> <li>Votes: <input type="number" name="choices-0-votes"></li> <li>Choice: <input type="text" name="choices-1-choice"></li> <li>Votes: <input type="number" name="choices-1-votes"></li> <li>Choice: <input type="text" name="choices-2-choice"></li> <li>Votes: <input type="number" name="choices-2-votes"></li>""", ) # Since every form was displayed as blank, they are also accepted as # blank. This may seem a little strange, but min_num is used to require # a minimum number of forms to be completed. data = { "choices-TOTAL_FORMS": "3", # the number of forms rendered "choices-INITIAL_FORMS": "0", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "", "choices-0-votes": "", "choices-1-choice": "", "choices-1-votes": "", "choices-2-choice": "", "choices-2-votes": "", } formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertEqual([form.cleaned_data for form in formset.forms], [{}, {}, {}]) def test_min_num_displaying_more_than_one_blank_form(self): """ More than 1 empty form can also be displayed using formset_factory's min_num argument. It will (essentially) increment the extra argument. """ ChoiceFormSet = formset_factory(Choice, extra=1, min_num=1) formset = ChoiceFormSet(auto_id=False, prefix="choices") # Min_num forms are required; extra forms can be empty. self.assertFalse(formset.forms[0].empty_permitted) self.assertTrue(formset.forms[1].empty_permitted) self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice"></li> <li>Votes: <input type="number" name="choices-0-votes"></li> <li>Choice: <input type="text" name="choices-1-choice"></li> <li>Votes: <input type="number" name="choices-1-votes"></li>""", ) def test_min_num_displaying_more_than_one_blank_form_with_zero_extra(self): """More than 1 empty form can be displayed using min_num.""" ChoiceFormSet = formset_factory(Choice, extra=0, min_num=3) formset = ChoiceFormSet(auto_id=False, prefix="choices") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice"></li> <li>Votes: <input type="number" name="choices-0-votes"></li> <li>Choice: <input type="text" name="choices-1-choice"></li> <li>Votes: <input type="number" name="choices-1-votes"></li> <li>Choice: <input type="text" name="choices-2-choice"></li> <li>Votes: <input type="number" name="choices-2-votes"></li>""", ) def test_single_form_completed(self): """Just one form may be completed.""" data = { "choices-TOTAL_FORMS": "3", # the number of forms rendered "choices-INITIAL_FORMS": "0", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "Calexico", "choices-0-votes": "100", "choices-1-choice": "", "choices-1-votes": "", "choices-2-choice": "", "choices-2-votes": "", } ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.forms], [{"votes": 100, "choice": "Calexico"}, {}, {}], ) def test_formset_validate_max_flag(self): """ If validate_max is set and max_num is less than TOTAL_FORMS in the data, a ValidationError is raised. MAX_NUM_FORMS in the data is irrelevant here (it's output as a hint for the client but its value in the returned data is not checked). """ data = { "choices-TOTAL_FORMS": "2", # the number of forms rendered "choices-INITIAL_FORMS": "0", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "2", # max number of forms - should be ignored "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", } ChoiceFormSet = formset_factory(Choice, extra=1, max_num=1, validate_max=True) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertFalse(formset.is_valid()) self.assertEqual(formset.non_form_errors(), ["Please submit at most 1 form."]) self.assertEqual( str(formset.non_form_errors()), '<ul class="errorlist nonform"><li>Please submit at most 1 form.</li></ul>', ) def test_formset_validate_max_flag_custom_error(self): data = { "choices-TOTAL_FORMS": "2", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", "choices-MAX_NUM_FORMS": "2", "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", } ChoiceFormSet = formset_factory(Choice, extra=1, max_num=1, validate_max=True) formset = ChoiceFormSet( data, auto_id=False, prefix="choices", error_messages={ "too_many_forms": "Number of submitted forms should be at most %(num)d." }, ) self.assertFalse(formset.is_valid()) self.assertEqual( formset.non_form_errors(), ["Number of submitted forms should be at most 1."], ) self.assertEqual( str(formset.non_form_errors()), '<ul class="errorlist nonform">' "<li>Number of submitted forms should be at most 1.</li></ul>", ) def test_formset_validate_min_flag(self): """ If validate_min is set and min_num is more than TOTAL_FORMS in the data, a ValidationError is raised. MIN_NUM_FORMS in the data is irrelevant here (it's output as a hint for the client but its value in the returned data is not checked). """ data = { "choices-TOTAL_FORMS": "2", # the number of forms rendered "choices-INITIAL_FORMS": "0", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms - should be ignored "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", } ChoiceFormSet = formset_factory(Choice, extra=1, min_num=3, validate_min=True) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertFalse(formset.is_valid()) self.assertEqual(formset.non_form_errors(), ["Please submit at least 3 forms."]) self.assertEqual( str(formset.non_form_errors()), '<ul class="errorlist nonform"><li>' "Please submit at least 3 forms.</li></ul>", ) def test_formset_validate_min_flag_custom_formatted_error(self): data = { "choices-TOTAL_FORMS": "2", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", "choices-MAX_NUM_FORMS": "0", "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", } ChoiceFormSet = formset_factory(Choice, extra=1, min_num=3, validate_min=True) formset = ChoiceFormSet( data, auto_id=False, prefix="choices", error_messages={ "too_few_forms": "Number of submitted forms should be at least %(num)d." }, ) self.assertFalse(formset.is_valid()) self.assertEqual( formset.non_form_errors(), ["Number of submitted forms should be at least 3."], ) self.assertEqual( str(formset.non_form_errors()), '<ul class="errorlist nonform">' "<li>Number of submitted forms should be at least 3.</li></ul>", ) def test_formset_validate_min_unchanged_forms(self): """ min_num validation doesn't consider unchanged forms with initial data as "empty". """ initial = [ {"choice": "Zero", "votes": 0}, {"choice": "One", "votes": 0}, ] data = { "choices-TOTAL_FORMS": "2", "choices-INITIAL_FORMS": "2", "choices-MIN_NUM_FORMS": "0", "choices-MAX_NUM_FORMS": "2", "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", # changed from initial } ChoiceFormSet = formset_factory(Choice, min_num=2, validate_min=True) formset = ChoiceFormSet(data, auto_id=False, prefix="choices", initial=initial) self.assertFalse(formset.forms[0].has_changed()) self.assertTrue(formset.forms[1].has_changed()) self.assertTrue(formset.is_valid()) def test_formset_validate_min_excludes_empty_forms(self): data = { "choices-TOTAL_FORMS": "2", "choices-INITIAL_FORMS": "0", } ChoiceFormSet = formset_factory( Choice, extra=2, min_num=1, validate_min=True, can_delete=True ) formset = ChoiceFormSet(data, prefix="choices") self.assertFalse(formset.has_changed()) self.assertFalse(formset.is_valid()) self.assertEqual(formset.non_form_errors(), ["Please submit at least 1 form."]) def test_second_form_partially_filled_2(self): """A partially completed form is invalid.""" data = { "choices-TOTAL_FORMS": "3", # the number of forms rendered "choices-INITIAL_FORMS": "0", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "Calexico", "choices-0-votes": "100", "choices-1-choice": "The Decemberists", "choices-1-votes": "", # missing value "choices-2-choice": "", "choices-2-votes": "", } ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertFalse(formset.is_valid()) self.assertEqual( formset.errors, [{}, {"votes": ["This field is required."]}, {}] ) def test_more_initial_data(self): """ The extra argument works when the formset is pre-filled with initial data. """ initial = [{"choice": "Calexico", "votes": 100}] ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(initial=initial, auto_id=False, prefix="choices") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), '<li>Choice: <input type="text" name="choices-0-choice" value="Calexico">' "</li>" '<li>Votes: <input type="number" name="choices-0-votes" value="100"></li>' '<li>Choice: <input type="text" name="choices-1-choice"></li>' '<li>Votes: <input type="number" name="choices-1-votes"></li>' '<li>Choice: <input type="text" name="choices-2-choice"></li>' '<li>Votes: <input type="number" name="choices-2-votes"></li>' '<li>Choice: <input type="text" name="choices-3-choice"></li>' '<li>Votes: <input type="number" name="choices-3-votes"></li>', ) # Retrieving an empty form works. Tt shows up in the form list. self.assertTrue(formset.empty_form.empty_permitted) self.assertHTMLEqual( formset.empty_form.as_ul(), """<li>Choice: <input type="text" name="choices-__prefix__-choice"></li> <li>Votes: <input type="number" name="choices-__prefix__-votes"></li>""", ) def test_formset_with_deletion(self): """ formset_factory's can_delete argument adds a boolean "delete" field to each form. When that boolean field is True, the form will be in formset.deleted_forms. """ ChoiceFormSet = formset_factory(Choice, can_delete=True) initial = [ {"choice": "Calexico", "votes": 100}, {"choice": "Fergie", "votes": 900}, ] formset = ChoiceFormSet(initial=initial, auto_id=False, prefix="choices") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), '<li>Choice: <input type="text" name="choices-0-choice" value="Calexico">' "</li>" '<li>Votes: <input type="number" name="choices-0-votes" value="100"></li>' '<li>Delete: <input type="checkbox" name="choices-0-DELETE"></li>' '<li>Choice: <input type="text" name="choices-1-choice" value="Fergie">' "</li>" '<li>Votes: <input type="number" name="choices-1-votes" value="900"></li>' '<li>Delete: <input type="checkbox" name="choices-1-DELETE"></li>' '<li>Choice: <input type="text" name="choices-2-choice"></li>' '<li>Votes: <input type="number" name="choices-2-votes"></li>' '<li>Delete: <input type="checkbox" name="choices-2-DELETE"></li>', ) # To delete something, set that form's special delete field to 'on'. # Let's go ahead and delete Fergie. data = { "choices-TOTAL_FORMS": "3", # the number of forms rendered "choices-INITIAL_FORMS": "2", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "Calexico", "choices-0-votes": "100", "choices-0-DELETE": "", "choices-1-choice": "Fergie", "choices-1-votes": "900", "choices-1-DELETE": "on", "choices-2-choice": "", "choices-2-votes": "", "choices-2-DELETE": "", } formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.forms], [ {"votes": 100, "DELETE": False, "choice": "Calexico"}, {"votes": 900, "DELETE": True, "choice": "Fergie"}, {}, ], ) self.assertEqual( [form.cleaned_data for form in formset.deleted_forms], [{"votes": 900, "DELETE": True, "choice": "Fergie"}], ) def test_formset_with_deletion_remove_deletion_flag(self): """ If a form is filled with something and can_delete is also checked, that form's errors shouldn't make the entire formset invalid since it's going to be deleted. """ class CheckForm(Form): field = IntegerField(min_value=100) data = { "check-TOTAL_FORMS": "3", # the number of forms rendered "check-INITIAL_FORMS": "2", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "check-MAX_NUM_FORMS": "0", # max number of forms "check-0-field": "200", "check-0-DELETE": "", "check-1-field": "50", "check-1-DELETE": "on", "check-2-field": "", "check-2-DELETE": "", } CheckFormSet = formset_factory(CheckForm, can_delete=True) formset = CheckFormSet(data, prefix="check") self.assertTrue(formset.is_valid()) # If the deletion flag is removed, validation is enabled. data["check-1-DELETE"] = "" formset = CheckFormSet(data, prefix="check") self.assertFalse(formset.is_valid()) def test_formset_with_deletion_invalid_deleted_form(self): """ deleted_forms works on a valid formset even if a deleted form would have been invalid. """ FavoriteDrinkFormset = formset_factory(form=FavoriteDrinkForm, can_delete=True) formset = FavoriteDrinkFormset( { "form-0-name": "", "form-0-DELETE": "on", # no name! "form-TOTAL_FORMS": 1, "form-INITIAL_FORMS": 1, "form-MIN_NUM_FORMS": 0, "form-MAX_NUM_FORMS": 1, } ) self.assertTrue(formset.is_valid()) self.assertEqual(formset._errors, []) self.assertEqual(len(formset.deleted_forms), 1) def test_formset_with_deletion_custom_widget(self): class DeletionAttributeFormSet(BaseFormSet): deletion_widget = HiddenInput class DeletionMethodFormSet(BaseFormSet): def get_deletion_widget(self): return HiddenInput(attrs={"class": "deletion"}) tests = [ (DeletionAttributeFormSet, '<input type="hidden" name="form-0-DELETE">'), ( DeletionMethodFormSet, '<input class="deletion" type="hidden" name="form-0-DELETE">', ), ] for formset_class, delete_html in tests: with self.subTest(formset_class=formset_class.__name__): ArticleFormSet = formset_factory( ArticleForm, formset=formset_class, can_delete=True, ) formset = ArticleFormSet(auto_id=False) self.assertHTMLEqual( "\n".join([form.as_ul() for form in formset.forms]), ( f'<li>Title: <input type="text" name="form-0-title"></li>' f'<li>Pub date: <input type="text" name="form-0-pub_date">' f"{delete_html}</li>" ), ) def test_formsets_with_ordering(self): """ formset_factory's can_order argument adds an integer field to each form. When form validation succeeds, [form.cleaned_data for form in formset.forms] will have the data in the correct order specified by the ordering fields. If a number is duplicated in the set of ordering fields, for instance form 0 and form 3 are both marked as 1, then the form index used as a secondary ordering criteria. In order to put something at the front of the list, you'd need to set its order to 0. """ ChoiceFormSet = formset_factory(Choice, can_order=True) initial = [ {"choice": "Calexico", "votes": 100}, {"choice": "Fergie", "votes": 900}, ] formset = ChoiceFormSet(initial=initial, auto_id=False, prefix="choices") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), '<li>Choice: <input type="text" name="choices-0-choice" value="Calexico">' "</li>" '<li>Votes: <input type="number" name="choices-0-votes" value="100"></li>' '<li>Order: <input type="number" name="choices-0-ORDER" value="1"></li>' '<li>Choice: <input type="text" name="choices-1-choice" value="Fergie">' "</li>" '<li>Votes: <input type="number" name="choices-1-votes" value="900"></li>' '<li>Order: <input type="number" name="choices-1-ORDER" value="2"></li>' '<li>Choice: <input type="text" name="choices-2-choice"></li>' '<li>Votes: <input type="number" name="choices-2-votes"></li>' '<li>Order: <input type="number" name="choices-2-ORDER"></li>', ) data = { "choices-TOTAL_FORMS": "3", # the number of forms rendered "choices-INITIAL_FORMS": "2", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "Calexico", "choices-0-votes": "100", "choices-0-ORDER": "1", "choices-1-choice": "Fergie", "choices-1-votes": "900", "choices-1-ORDER": "2", "choices-2-choice": "The Decemberists", "choices-2-votes": "500", "choices-2-ORDER": "0", } formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.ordered_forms], [ {"votes": 500, "ORDER": 0, "choice": "The Decemberists"}, {"votes": 100, "ORDER": 1, "choice": "Calexico"}, {"votes": 900, "ORDER": 2, "choice": "Fergie"}, ], ) def test_formsets_with_ordering_custom_widget(self): class OrderingAttributeFormSet(BaseFormSet): ordering_widget = HiddenInput class OrderingMethodFormSet(BaseFormSet): def get_ordering_widget(self): return HiddenInput(attrs={"class": "ordering"}) tests = ( (OrderingAttributeFormSet, '<input type="hidden" name="form-0-ORDER">'), ( OrderingMethodFormSet, '<input class="ordering" type="hidden" name="form-0-ORDER">', ), ) for formset_class, order_html in tests: with self.subTest(formset_class=formset_class.__name__): ArticleFormSet = formset_factory( ArticleForm, formset=formset_class, can_order=True ) formset = ArticleFormSet(auto_id=False) self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), ( '<li>Title: <input type="text" name="form-0-title"></li>' '<li>Pub date: <input type="text" name="form-0-pub_date">' "%s</li>" % order_html ), ) def test_empty_ordered_fields(self): """ Ordering fields are allowed to be left blank. If they are left blank, they'll be sorted below everything else. """ data = { "choices-TOTAL_FORMS": "4", # the number of forms rendered "choices-INITIAL_FORMS": "3", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "Calexico", "choices-0-votes": "100", "choices-0-ORDER": "1", "choices-1-choice": "Fergie", "choices-1-votes": "900", "choices-1-ORDER": "2", "choices-2-choice": "The Decemberists", "choices-2-votes": "500", "choices-2-ORDER": "", "choices-3-choice": "Basia Bulat", "choices-3-votes": "50", "choices-3-ORDER": "", } ChoiceFormSet = formset_factory(Choice, can_order=True) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.ordered_forms], [ {"votes": 100, "ORDER": 1, "choice": "Calexico"}, {"votes": 900, "ORDER": 2, "choice": "Fergie"}, {"votes": 500, "ORDER": None, "choice": "The Decemberists"}, {"votes": 50, "ORDER": None, "choice": "Basia Bulat"}, ], ) def test_ordering_blank_fieldsets(self): """Ordering works with blank fieldsets.""" data = { "choices-TOTAL_FORMS": "3", # the number of forms rendered "choices-INITIAL_FORMS": "0", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms } ChoiceFormSet = formset_factory(Choice, can_order=True) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertEqual(formset.ordered_forms, []) def test_formset_with_ordering_and_deletion(self): """FormSets with ordering + deletion.""" ChoiceFormSet = formset_factory(Choice, can_order=True, can_delete=True) initial = [ {"choice": "Calexico", "votes": 100}, {"choice": "Fergie", "votes": 900}, {"choice": "The Decemberists", "votes": 500}, ] formset = ChoiceFormSet(initial=initial, auto_id=False, prefix="choices") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), '<li>Choice: <input type="text" name="choices-0-choice" value="Calexico">' "</li>" '<li>Votes: <input type="number" name="choices-0-votes" value="100"></li>' '<li>Order: <input type="number" name="choices-0-ORDER" value="1"></li>' '<li>Delete: <input type="checkbox" name="choices-0-DELETE"></li>' '<li>Choice: <input type="text" name="choices-1-choice" value="Fergie">' "</li>" '<li>Votes: <input type="number" name="choices-1-votes" value="900"></li>' '<li>Order: <input type="number" name="choices-1-ORDER" value="2"></li>' '<li>Delete: <input type="checkbox" name="choices-1-DELETE"></li>' '<li>Choice: <input type="text" name="choices-2-choice" ' 'value="The Decemberists"></li>' '<li>Votes: <input type="number" name="choices-2-votes" value="500"></li>' '<li>Order: <input type="number" name="choices-2-ORDER" value="3"></li>' '<li>Delete: <input type="checkbox" name="choices-2-DELETE"></li>' '<li>Choice: <input type="text" name="choices-3-choice"></li>' '<li>Votes: <input type="number" name="choices-3-votes"></li>' '<li>Order: <input type="number" name="choices-3-ORDER"></li>' '<li>Delete: <input type="checkbox" name="choices-3-DELETE"></li>', ) # Let's delete Fergie, and put The Decemberists ahead of Calexico. data = { "choices-TOTAL_FORMS": "4", # the number of forms rendered "choices-INITIAL_FORMS": "3", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "Calexico", "choices-0-votes": "100", "choices-0-ORDER": "1", "choices-0-DELETE": "", "choices-1-choice": "Fergie", "choices-1-votes": "900", "choices-1-ORDER": "2", "choices-1-DELETE": "on", "choices-2-choice": "The Decemberists", "choices-2-votes": "500", "choices-2-ORDER": "0", "choices-2-DELETE": "", "choices-3-choice": "", "choices-3-votes": "", "choices-3-ORDER": "", "choices-3-DELETE": "", } formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.ordered_forms], [ { "votes": 500, "DELETE": False, "ORDER": 0, "choice": "The Decemberists", }, {"votes": 100, "DELETE": False, "ORDER": 1, "choice": "Calexico"}, ], ) self.assertEqual( [form.cleaned_data for form in formset.deleted_forms], [{"votes": 900, "DELETE": True, "ORDER": 2, "choice": "Fergie"}], ) def test_invalid_deleted_form_with_ordering(self): """ Can get ordered_forms from a valid formset even if a deleted form would have been invalid. """ FavoriteDrinkFormset = formset_factory( form=FavoriteDrinkForm, can_delete=True, can_order=True ) formset = FavoriteDrinkFormset( { "form-0-name": "", "form-0-DELETE": "on", # no name! "form-TOTAL_FORMS": 1, "form-INITIAL_FORMS": 1, "form-MIN_NUM_FORMS": 0, "form-MAX_NUM_FORMS": 1, } ) self.assertTrue(formset.is_valid()) self.assertEqual(formset.ordered_forms, []) def test_clean_hook(self): """ FormSets have a clean() hook for doing extra validation that isn't tied to any form. It follows the same pattern as the clean() hook on Forms. """ # Start out with a some duplicate data. data = { "drinks-TOTAL_FORMS": "2", # the number of forms rendered "drinks-INITIAL_FORMS": "0", # the number of forms with initial data "drinks-MIN_NUM_FORMS": "0", # min number of forms "drinks-MAX_NUM_FORMS": "0", # max number of forms "drinks-0-name": "Gin and Tonic", "drinks-1-name": "Gin and Tonic", } formset = FavoriteDrinksFormSet(data, prefix="drinks") self.assertFalse(formset.is_valid()) # Any errors raised by formset.clean() are available via the # formset.non_form_errors() method. for error in formset.non_form_errors(): self.assertEqual(str(error), "You may only specify a drink once.") # The valid case still works. data["drinks-1-name"] = "Bloody Mary" formset = FavoriteDrinksFormSet(data, prefix="drinks") self.assertTrue(formset.is_valid()) self.assertEqual(formset.non_form_errors(), []) def test_limiting_max_forms(self): """Limiting the maximum number of forms with max_num.""" # When not passed, max_num will take a high default value, leaving the # number of forms only controlled by the value of the extra parameter. LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3) formset = LimitedFavoriteDrinkFormSet() self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), """<div><label for="id_form-0-name">Name:</label> <input type="text" name="form-0-name" id="id_form-0-name"></div> <div><label for="id_form-1-name">Name:</label> <input type="text" name="form-1-name" id="id_form-1-name"></div> <div><label for="id_form-2-name">Name:</label> <input type="text" name="form-2-name" id="id_form-2-name"></div>""", ) # If max_num is 0 then no form is rendered at all. LimitedFavoriteDrinkFormSet = formset_factory( FavoriteDrinkForm, extra=3, max_num=0 ) formset = LimitedFavoriteDrinkFormSet() self.assertEqual(formset.forms, []) def test_limited_max_forms_two(self): LimitedFavoriteDrinkFormSet = formset_factory( FavoriteDrinkForm, extra=5, max_num=2 ) formset = LimitedFavoriteDrinkFormSet() self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), """<div><label for="id_form-0-name">Name:</label> <input type="text" name="form-0-name" id="id_form-0-name"></div> <div><label for="id_form-1-name">Name:</label> <input type="text" name="form-1-name" id="id_form-1-name"></div>""", ) def test_limiting_extra_lest_than_max_num(self): """max_num has no effect when extra is less than max_num.""" LimitedFavoriteDrinkFormSet = formset_factory( FavoriteDrinkForm, extra=1, max_num=2 ) formset = LimitedFavoriteDrinkFormSet() self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), """<div><label for="id_form-0-name">Name:</label> <input type="text" name="form-0-name" id="id_form-0-name"></div>""", ) def test_max_num_with_initial_data(self): # When not passed, max_num will take a high default value, leaving the # number of forms only controlled by the value of the initial and extra # parameters. LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1) formset = LimitedFavoriteDrinkFormSet(initial=[{"name": "Fernet and Coke"}]) self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), """ <div><label for="id_form-0-name">Name:</label> <input type="text" name="form-0-name" value="Fernet and Coke" id="id_form-0-name"></div> <div><label for="id_form-1-name">Name:</label> <input type="text" name="form-1-name" id="id_form-1-name"></div> """, ) def test_max_num_zero(self): """ If max_num is 0 then no form is rendered at all, regardless of extra, unless initial data is present. """ LimitedFavoriteDrinkFormSet = formset_factory( FavoriteDrinkForm, extra=1, max_num=0 ) formset = LimitedFavoriteDrinkFormSet() self.assertEqual(formset.forms, []) def test_max_num_zero_with_initial(self): # initial trumps max_num initial = [ {"name": "Fernet and Coke"}, {"name": "Bloody Mary"}, ] LimitedFavoriteDrinkFormSet = formset_factory( FavoriteDrinkForm, extra=1, max_num=0 ) formset = LimitedFavoriteDrinkFormSet(initial=initial) self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), """ <div><label for="id_form-0-name">Name:</label> <input id="id_form-0-name" name="form-0-name" type="text" value="Fernet and Coke"></div> <div><label for="id_form-1-name">Name:</label> <input id="id_form-1-name" name="form-1-name" type="text" value="Bloody Mary"></div> """, ) def test_more_initial_than_max_num(self): """ More initial forms than max_num results in all initial forms being displayed (but no extra forms). """ initial = [ {"name": "Gin Tonic"}, {"name": "Bloody Mary"}, {"name": "Jack and Coke"}, ] LimitedFavoriteDrinkFormSet = formset_factory( FavoriteDrinkForm, extra=1, max_num=2 ) formset = LimitedFavoriteDrinkFormSet(initial=initial) self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), """ <div><label for="id_form-0-name">Name:</label> <input id="id_form-0-name" name="form-0-name" type="text" value="Gin Tonic"> </div> <div><label for="id_form-1-name">Name:</label> <input id="id_form-1-name" name="form-1-name" type="text" value="Bloody Mary"></div> <div><label for="id_form-2-name">Name:</label> <input id="id_form-2-name" name="form-2-name" type="text" value="Jack and Coke"></div> """, ) def test_default_absolute_max(self): # absolute_max defaults to 2 * DEFAULT_MAX_NUM if max_num is None. data = { "form-TOTAL_FORMS": 2001, "form-INITIAL_FORMS": "0", "form-MAX_NUM_FORMS": "0", } formset = FavoriteDrinksFormSet(data=data) self.assertIs(formset.is_valid(), False) self.assertEqual( formset.non_form_errors(), ["Please submit at most 1000 forms."], ) self.assertEqual(formset.absolute_max, 2000) def test_absolute_max(self): data = { "form-TOTAL_FORMS": "2001", "form-INITIAL_FORMS": "0", "form-MAX_NUM_FORMS": "0", } AbsoluteMaxFavoriteDrinksFormSet = formset_factory( FavoriteDrinkForm, absolute_max=3000, ) formset = AbsoluteMaxFavoriteDrinksFormSet(data=data) self.assertIs(formset.is_valid(), True) self.assertEqual(len(formset.forms), 2001) # absolute_max provides a hard limit. data["form-TOTAL_FORMS"] = "3001" formset = AbsoluteMaxFavoriteDrinksFormSet(data=data) self.assertIs(formset.is_valid(), False) self.assertEqual(len(formset.forms), 3000) self.assertEqual( formset.non_form_errors(), ["Please submit at most 1000 forms."], ) def test_absolute_max_with_max_num(self): data = { "form-TOTAL_FORMS": "1001", "form-INITIAL_FORMS": "0", "form-MAX_NUM_FORMS": "0", } LimitedFavoriteDrinksFormSet = formset_factory( FavoriteDrinkForm, max_num=30, absolute_max=1000, ) formset = LimitedFavoriteDrinksFormSet(data=data) self.assertIs(formset.is_valid(), False) self.assertEqual(len(formset.forms), 1000) self.assertEqual( formset.non_form_errors(), ["Please submit at most 30 forms."], ) def test_absolute_max_invalid(self): msg = "'absolute_max' must be greater or equal to 'max_num'." for max_num in [None, 31]: with self.subTest(max_num=max_num): with self.assertRaisesMessage(ValueError, msg): formset_factory(FavoriteDrinkForm, max_num=max_num, absolute_max=30) def test_more_initial_form_result_in_one(self): """ One form from initial and extra=3 with max_num=2 results in the one initial form and one extra. """ LimitedFavoriteDrinkFormSet = formset_factory( FavoriteDrinkForm, extra=3, max_num=2 ) formset = LimitedFavoriteDrinkFormSet(initial=[{"name": "Gin Tonic"}]) self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), """ <div><label for="id_form-0-name">Name:</label> <input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name"> </div> <div><label for="id_form-1-name">Name:</label> <input type="text" name="form-1-name" id="id_form-1-name"></div>""", ) def test_management_form_field_names(self): """The management form class has field names matching the constants.""" self.assertCountEqual( ManagementForm.base_fields, [ TOTAL_FORM_COUNT, INITIAL_FORM_COUNT, MIN_NUM_FORM_COUNT, MAX_NUM_FORM_COUNT, ], ) def test_management_form_prefix(self): """The management form has the correct prefix.""" formset = FavoriteDrinksFormSet() self.assertEqual(formset.management_form.prefix, "form") data = { "form-TOTAL_FORMS": "2", "form-INITIAL_FORMS": "0", "form-MIN_NUM_FORMS": "0", "form-MAX_NUM_FORMS": "0", } formset = FavoriteDrinksFormSet(data=data) self.assertEqual(formset.management_form.prefix, "form") formset = FavoriteDrinksFormSet(initial={}) self.assertEqual(formset.management_form.prefix, "form") def test_non_form_errors(self): data = { "drinks-TOTAL_FORMS": "2", # the number of forms rendered "drinks-INITIAL_FORMS": "0", # the number of forms with initial data "drinks-MIN_NUM_FORMS": "0", # min number of forms "drinks-MAX_NUM_FORMS": "0", # max number of forms "drinks-0-name": "Gin and Tonic", "drinks-1-name": "Gin and Tonic", } formset = FavoriteDrinksFormSet(data, prefix="drinks") self.assertFalse(formset.is_valid()) self.assertEqual( formset.non_form_errors(), ["You may only specify a drink once."] ) self.assertEqual( str(formset.non_form_errors()), '<ul class="errorlist nonform"><li>' "You may only specify a drink once.</li></ul>", ) def test_formset_iteration(self): """Formset instances are iterable.""" ChoiceFormset = formset_factory(Choice, extra=3) formset = ChoiceFormset() # An iterated formset yields formset.forms. forms = list(formset) self.assertEqual(forms, formset.forms) self.assertEqual(len(formset), len(forms)) # A formset may be indexed to retrieve its forms. self.assertEqual(formset[0], forms[0]) with self.assertRaises(IndexError): formset[3] # Formsets can override the default iteration order class BaseReverseFormSet(BaseFormSet): def __iter__(self): return reversed(self.forms) def __getitem__(self, idx): return super().__getitem__(len(self) - idx - 1) ReverseChoiceFormset = formset_factory(Choice, BaseReverseFormSet, extra=3) reverse_formset = ReverseChoiceFormset() # __iter__() modifies the rendering order. # Compare forms from "reverse" formset with forms from original formset self.assertEqual(str(reverse_formset[0]), str(forms[-1])) self.assertEqual(str(reverse_formset[1]), str(forms[-2])) self.assertEqual(len(reverse_formset), len(forms)) def test_formset_nonzero(self): """A formsets without any forms evaluates as True.""" ChoiceFormset = formset_factory(Choice, extra=0) formset = ChoiceFormset() self.assertEqual(len(formset.forms), 0) self.assertTrue(formset) def test_formset_splitdatetimefield(self): """ Formset works with SplitDateTimeField(initial=datetime.datetime.now). """ class SplitDateTimeForm(Form): when = SplitDateTimeField(initial=datetime.datetime.now) SplitDateTimeFormSet = formset_factory(SplitDateTimeForm) data = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "0", "form-0-when_0": "1904-06-16", "form-0-when_1": "15:51:33", } formset = SplitDateTimeFormSet(data) self.assertTrue(formset.is_valid()) def test_formset_error_class(self): """Formset's forms use the formset's error_class.""" class CustomErrorList(ErrorList): pass formset = FavoriteDrinksFormSet(error_class=CustomErrorList) self.assertEqual(formset.forms[0].error_class, CustomErrorList) def test_formset_calls_forms_is_valid(self): """Formsets call is_valid() on each form.""" class AnotherChoice(Choice): def is_valid(self): self.is_valid_called = True return super().is_valid() AnotherChoiceFormSet = formset_factory(AnotherChoice) data = { "choices-TOTAL_FORMS": "1", # number of forms rendered "choices-INITIAL_FORMS": "0", # number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "Calexico", "choices-0-votes": "100", } formset = AnotherChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertTrue(all(form.is_valid_called for form in formset.forms)) def test_hard_limit_on_instantiated_forms(self): """A formset has a hard limit on the number of forms instantiated.""" # reduce the default limit of 1000 temporarily for testing _old_DEFAULT_MAX_NUM = formsets.DEFAULT_MAX_NUM try: formsets.DEFAULT_MAX_NUM = 2 ChoiceFormSet = formset_factory(Choice, max_num=1) # someone fiddles with the mgmt form data... formset = ChoiceFormSet( { "choices-TOTAL_FORMS": "4", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "4", "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", "choices-2-choice": "Two", "choices-2-votes": "2", "choices-3-choice": "Three", "choices-3-votes": "3", }, prefix="choices", ) # But we still only instantiate 3 forms self.assertEqual(len(formset.forms), 3) # and the formset isn't valid self.assertFalse(formset.is_valid()) finally: formsets.DEFAULT_MAX_NUM = _old_DEFAULT_MAX_NUM def test_increase_hard_limit(self): """Can increase the built-in forms limit via a higher max_num.""" # reduce the default limit of 1000 temporarily for testing _old_DEFAULT_MAX_NUM = formsets.DEFAULT_MAX_NUM try: formsets.DEFAULT_MAX_NUM = 3 # for this form, we want a limit of 4 ChoiceFormSet = formset_factory(Choice, max_num=4) formset = ChoiceFormSet( { "choices-TOTAL_FORMS": "4", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "4", "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", "choices-2-choice": "Two", "choices-2-votes": "2", "choices-3-choice": "Three", "choices-3-votes": "3", }, prefix="choices", ) # Four forms are instantiated and no exception is raised self.assertEqual(len(formset.forms), 4) finally: formsets.DEFAULT_MAX_NUM = _old_DEFAULT_MAX_NUM def test_non_form_errors_run_full_clean(self): """ If non_form_errors() is called without calling is_valid() first, it should ensure that full_clean() is called. """ class BaseCustomFormSet(BaseFormSet): def clean(self): raise ValidationError("This is a non-form error") ChoiceFormSet = formset_factory(Choice, formset=BaseCustomFormSet) data = { "choices-TOTAL_FORMS": "1", "choices-INITIAL_FORMS": "0", } formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertIsInstance(formset.non_form_errors(), ErrorList) self.assertEqual(list(formset.non_form_errors()), ["This is a non-form error"]) def test_validate_max_ignores_forms_marked_for_deletion(self): class CheckForm(Form): field = IntegerField() data = { "check-TOTAL_FORMS": "2", "check-INITIAL_FORMS": "0", "check-MAX_NUM_FORMS": "1", "check-0-field": "200", "check-0-DELETE": "", "check-1-field": "50", "check-1-DELETE": "on", } CheckFormSet = formset_factory( CheckForm, max_num=1, validate_max=True, can_delete=True ) formset = CheckFormSet(data, prefix="check") self.assertTrue(formset.is_valid()) def test_formset_total_error_count(self): """A valid formset should have 0 total errors.""" data = [ # formset_data, expected error count ([("Calexico", "100")], 0), ([("Calexico", "")], 1), ([("", "invalid")], 2), ([("Calexico", "100"), ("Calexico", "")], 1), ([("Calexico", ""), ("Calexico", "")], 2), ] for formset_data, expected_error_count in data: formset = self.make_choiceformset(formset_data) self.assertEqual(formset.total_error_count(), expected_error_count) def test_formset_total_error_count_with_non_form_errors(self): data = { "choices-TOTAL_FORMS": "2", # the number of forms rendered "choices-INITIAL_FORMS": "0", # the number of forms with initial data "choices-MAX_NUM_FORMS": "2", # max number of forms - should be ignored "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", } ChoiceFormSet = formset_factory(Choice, extra=1, max_num=1, validate_max=True) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertEqual(formset.total_error_count(), 1) data["choices-1-votes"] = "" formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertEqual(formset.total_error_count(), 2) def test_html_safe(self): formset = self.make_choiceformset() self.assertTrue(hasattr(formset, "__html__")) self.assertEqual(str(formset), formset.__html__()) def test_can_delete_extra_formset_forms(self): ChoiceFormFormset = formset_factory(form=Choice, can_delete=True, extra=2) formset = ChoiceFormFormset() self.assertEqual(len(formset), 2) self.assertIn("DELETE", formset.forms[0].fields) self.assertIn("DELETE", formset.forms[1].fields) def test_disable_delete_extra_formset_forms(self): ChoiceFormFormset = formset_factory( form=Choice, can_delete=True, can_delete_extra=False, extra=2, ) formset = ChoiceFormFormset() self.assertEqual(len(formset), 2) self.assertNotIn("DELETE", formset.forms[0].fields) self.assertNotIn("DELETE", formset.forms[1].fields) formset = ChoiceFormFormset(initial=[{"choice": "Zero", "votes": "1"}]) self.assertEqual(len(formset), 3) self.assertIn("DELETE", formset.forms[0].fields) self.assertNotIn("DELETE", formset.forms[1].fields) self.assertNotIn("DELETE", formset.forms[2].fields) self.assertNotIn("DELETE", formset.empty_form.fields) formset = ChoiceFormFormset( data={ "form-0-choice": "Zero", "form-0-votes": "0", "form-0-DELETE": "on", "form-1-choice": "One", "form-1-votes": "1", "form-2-choice": "", "form-2-votes": "", "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "1", }, initial=[{"choice": "Zero", "votes": "1"}], ) self.assertEqual( formset.cleaned_data, [ {"choice": "Zero", "votes": 0, "DELETE": True}, {"choice": "One", "votes": 1}, {}, ], ) self.assertIs(formset._should_delete_form(formset.forms[0]), True) self.assertIs(formset._should_delete_form(formset.forms[1]), False) self.assertIs(formset._should_delete_form(formset.forms[2]), False) def test_template_name_uses_renderer_value(self): class CustomRenderer(TemplatesSetting): formset_template_name = "a/custom/formset/template.html" ChoiceFormSet = formset_factory(Choice, renderer=CustomRenderer) self.assertEqual( ChoiceFormSet().template_name, "a/custom/formset/template.html" ) def test_template_name_can_be_overridden(self): class CustomFormSet(BaseFormSet): template_name = "a/custom/formset/template.html" ChoiceFormSet = formset_factory(Choice, formset=CustomFormSet) self.assertEqual( ChoiceFormSet().template_name, "a/custom/formset/template.html" ) def test_custom_renderer(self): """ A custom renderer passed to a formset_factory() is passed to all forms and ErrorList. """ from django.forms.renderers import Jinja2 renderer = Jinja2() data = { "choices-TOTAL_FORMS": "2", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", "choices-0-choice": "Zero", "choices-0-votes": "", "choices-1-choice": "One", "choices-1-votes": "", } ChoiceFormSet = formset_factory(Choice, renderer=renderer) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertEqual(formset.renderer, renderer) self.assertEqual(formset.forms[0].renderer, renderer) self.assertEqual(formset.management_form.renderer, renderer) self.assertEqual(formset.non_form_errors().renderer, renderer) self.assertEqual(formset.empty_form.renderer, renderer) def test_form_default_renderer(self): """ In the absence of a renderer passed to the formset_factory(), Form.default_renderer is respected. """ class CustomRenderer(DjangoTemplates): pass class ChoiceWithDefaultRenderer(Choice): default_renderer = CustomRenderer() data = { "choices-TOTAL_FORMS": "1", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", } ChoiceFormSet = formset_factory(ChoiceWithDefaultRenderer) formset = ChoiceFormSet(data, prefix="choices") self.assertEqual( formset.forms[0].renderer, ChoiceWithDefaultRenderer.default_renderer ) self.assertEqual( formset.empty_form.renderer, ChoiceWithDefaultRenderer.default_renderer ) default_renderer = get_default_renderer() self.assertIsInstance(formset.renderer, type(default_renderer)) def test_form_default_renderer_class(self): """ In the absence of a renderer passed to the formset_factory(), Form.default_renderer is respected. """ class CustomRenderer(DjangoTemplates): pass class ChoiceWithDefaultRenderer(Choice): default_renderer = CustomRenderer data = { "choices-TOTAL_FORMS": "1", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", } ChoiceFormSet = formset_factory(ChoiceWithDefaultRenderer) formset = ChoiceFormSet(data, prefix="choices") self.assertIsInstance(formset.forms[0].renderer, CustomRenderer) self.assertIsInstance(formset.empty_form.renderer, CustomRenderer) default_renderer = get_default_renderer() self.assertIsInstance(formset.renderer, type(default_renderer)) def test_repr(self): valid_formset = self.make_choiceformset([("test", 1)]) valid_formset.full_clean() invalid_formset = self.make_choiceformset([("test", "")]) invalid_formset.full_clean() partially_invalid_formset = self.make_choiceformset( [("test", "1"), ("test", "")], ) partially_invalid_formset.full_clean() invalid_formset_non_form_errors_only = self.make_choiceformset( [("test", "")], formset_class=ChoiceFormsetWithNonFormError, ) invalid_formset_non_form_errors_only.full_clean() cases = [ ( self.make_choiceformset(), "<ChoiceFormSet: bound=False valid=Unknown total_forms=1>", ), ( self.make_choiceformset( formset_class=formset_factory(Choice, extra=10), ), "<ChoiceFormSet: bound=False valid=Unknown total_forms=10>", ), ( self.make_choiceformset([]), "<ChoiceFormSet: bound=True valid=Unknown total_forms=0>", ), ( self.make_choiceformset([("test", 1)]), "<ChoiceFormSet: bound=True valid=Unknown total_forms=1>", ), (valid_formset, "<ChoiceFormSet: bound=True valid=True total_forms=1>"), (invalid_formset, "<ChoiceFormSet: bound=True valid=False total_forms=1>"), ( partially_invalid_formset, "<ChoiceFormSet: bound=True valid=False total_forms=2>", ), ( invalid_formset_non_form_errors_only, "<ChoiceFormsetWithNonFormError: bound=True valid=False total_forms=1>", ), ] for formset, expected_repr in cases: with self.subTest(expected_repr=expected_repr): self.assertEqual(repr(formset), expected_repr) def test_repr_do_not_trigger_validation(self): formset = self.make_choiceformset([("test", 1)]) with mock.patch.object(formset, "full_clean") as mocked_full_clean: repr(formset) mocked_full_clean.assert_not_called() formset.is_valid() mocked_full_clean.assert_called() @jinja2_tests
FormsFormsetTestCase
python
pypa__pip
src/pip/_vendor/msgpack/exceptions.py
{ "start": 424, "end": 564 }
class ____(ValueError, UnpackException): """Too nested""" # Deprecated. Use ValueError instead UnpackValueError = ValueError
StackError
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_isan.py
{ "start": 1842, "end": 4624 }
class ____(ColumnMapExpectation): """Expect column values to be valid ISAN (International Standard Audiovisual Number).""" # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "all_valid": [ "000000018947000000000000", "0000-0000-D07A-0090-Q-0000-0000-X", "0000-0001-8CFA-0000-I-0000-0000-K", "00000000D07A009000000000", "0000-0000-D07A-0090-Q-0000-0000-X", ], "some_other": [ "000000018947000000000000", "0000-0000-D07A-0090-Q-0000-0000-X", "0000-0001-8CFA-0000-I-0000-0000-K", "00000000D07A009000000000", "abcd", ], }, "tests": [ { "title": "basic_positive_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "all_valid"}, "out": { "success": True, }, }, { "title": "basic_negative_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "some_other", "mostly": 1}, "out": { "success": False, }, }, ], } ] # This is the id string of the Metric used by this Expectation. # For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above. map_metric = "column_values.to_be_valid_isan" # This is a list of parameter names that can affect whether the Expectation evaluates to True or False success_keys = ("mostly",) # This dictionary contains default values for any parameters that should have default values default_kwarg_values = {} # This object contains metadata for display in the public Gallery library_metadata = { "maturity": "experimental", "tags": [ "hackathon-22", "experimental", "typed-entities", ], # Tags for this Expectation in the Gallery "contributors": [ # Github handles for all contributors to this Expectation. "@szecsip", # Don't forget to add your github handle here! ], "requirements": ["python-stdnum"], } if __name__ == "__main__": ExpectColumnValuesToBeValidIsan().print_diagnostic_checklist()
ExpectColumnValuesToBeValidIsan
python
eth-brownie__brownie
brownie/_gui/root.py
{ "start": 3312, "end": 4799 }
class ____(ttk.Frame): def __init__(self, root, project): super().__init__(root) self.root = root # geometry self.columnconfigure([0, 1], minsize=80) self.columnconfigure(7, weight=1) self.columnconfigure([8, 9], minsize=200) self.columnconfigure(10, minsize=304) # toggle buttons self.console = ConsoleButton(self) self.console.grid(row=0, column=0, sticky="nsew") ToolTip(self.console, "Toggle expanded console") self.scope = ScopingButton(self) self.scope.grid(row=0, column=1, sticky="nsew") ToolTip(self.scope, "Filter opcodes to only show those\nrelated to the highlighted source") # report selection self.highlight_select = HighlightSelect(self) self.highlight_select.grid(row=0, column=8, sticky="nsew", padx=10) self.highlight_select.hide() ToolTip(self.highlight_select, "Select which report highlights to display") self.report = ReportSelect(self) self.report.grid(row=0, column=9, sticky="nsew", padx=10) self.report.hide() ToolTip(self.report, "Select a report to overlay onto the source code") # contract selection self.combo = ContractSelect( self, [k for k, v in project._build.items() if v.get("bytecode")] ) self.combo.grid(row=0, column=10, sticky="nsew") ToolTip(self.combo, "Select the contract source to view")
ToolbarFrame
python
ray-project__ray
doc/source/ray-core/doc_code/direct_transport_gloo.py
{ "start": 1928, "end": 2773 }
class ____: @ray.method(tensor_transport="gloo") def random_tensor_dict(self): return {"tensor1": torch.randn(1000, 1000), "tensor2": torch.randn(1000, 1000)} def sum(self, tensor_dict: dict): return torch.sum(tensor_dict["tensor1"]) + torch.sum(tensor_dict["tensor2"]) sender, receiver = MyActor.remote(), MyActor.remote() group = create_collective_group([sender, receiver], backend="torch_gloo") # Both tensor values in the dictionary will be stored by the `sender` actor # instead of in Ray's object store. tensor_dict = sender.random_tensor_dict.remote() result = receiver.sum.remote(tensor_dict) print(ray.get(result)) # __gloo_multiple_tensors_example_end__ # __gloo_intra_actor_start__ import torch import ray import pytest from ray.experimental.collective import create_collective_group @ray.remote
MyActor
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 314784, "end": 315291 }
class ____(sgqlc.types.Input): """Autogenerated input type of UnfollowOrganization""" __schema__ = github_schema __field_names__ = ("organization_id", "client_mutation_id") organization_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="organizationId") """ID of the organization to unfollow.""" client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation."""
UnfollowOrganizationInput
python
tensorflow__tensorflow
tensorflow/python/ops/while_v2.py
{ "start": 38423, "end": 61813 }
class ____(util.WhileBodyFuncGraph): """FuncGraph for the gradient function of the body of a While op. Contains the logic for capturing the tensors from the body of the forward While op which is as follows: 1. If the tensor is of resource type (these are not accumulated): a. Ensure that the tensor is a loop invariant, i.e., it exists in both loop inputs and outputs at the same index. b. Lookup the corresponding resource tensor in the forward outer graph and try to capture that. 2. If the tensor is not of resource type: a. Create an accumulator for that tensor and output it from the forward pass. Note this also requires adding it as an input to the forward pass. b. Capture the accumulator from the forward pass in this FuncGraph. This will later be resolved to the correct output of the forward While op. c. Pop a value from the captured placeholder and use it as the captured value for the forward pass tensor. This only allows capturing tensors in the forward graph. A ValueError is raised if an attempt is made to capture a tensor not in the forward graph. To manually capture a tensor that is not in the forward graph, call `capture` with `allowlisted=True`. Note: The `captures` dict does not contain the forward tensor since it is not directly captured. It contains the accumulator corresponding to this forward tensor. Attributes: while_op_needs_rewrite: True if any non-resource intermediates were captured, meaning the forward While op needs to be rewritten to output the corresponding accumulators. extra_inputs: list of EmptyTensorList tensors to be used as initial input to the new accumulators in the forward graph. It may also contain external captures of the custom gradient function. internal_capture_to_output: dict from a tensor_id(captured placeholder) to the corresponding tensor that needs to be added to the list of outputs. For instance, when capturing an accumulator TensorList this contains the TensorList obtained after popping a tensor from the list. Other entries in this dict are expected, though not enforced, to be identities. This dict is needed because these output tensors need to be added to FuncGraph.outputs "after" the tensors returned from the gradient function. """ def __init__(self, name, forward_cond_graph, forward_body_graph, maximum_iterations, forward_while_op, body_graph_inputs, body_graph_outputs): super(_WhileBodyGradFuncGraph, self).__init__(name) self.extra_inputs = [] self.internal_capture_to_output = {} # FuncGraph for the body of the forward While op. self._forward_graph = forward_body_graph # FuncGraph for the cond of the forward While op. self._forward_cond_graph = forward_cond_graph self._maximum_iterations = maximum_iterations self._forward_while_op = forward_while_op # Dict from forward intermediate tensor to its indirectly captured tensor # in this graph. Indirect capturing happens in two ways: # 1. For non-resource tensors we capture their accumulators from the forward # outer graph and pop values from that accumulator inside this graph # using TensorListPopBack. # 2. For resource tensors we directly capture their corresponding tensor # in the forward outer graph. self._indirect_captures = {} @property def while_op_needs_rewrite(self): return self.extra_inputs def _create_op_internal( self, op_type, inputs, dtypes=None, # pylint: disable=redefined-outer-name input_types=None, name=None, attrs=None, op_def=None, compute_device=True): # For a reduction op, if op is in the gradient body graph and its input is # from the forward graph, moving op to the forward graph means we would # store the tensor after the reduction as opposed to the tensor before # reduction, and therefore could significantly reduce memory consumption. # For now, we do this only for a few ops. # # We don't do this if any input tensor has already been accumulated. This # can happen if we output all intermediates in the forward pass. # # If in XLA context, do not move constant ops to forward pass as pushing to # and popping from a TensorList removes the constant property of an op and # breaks XLA compilation, which requires certain inputs to be compile-time # constant for certain ops. # # This optimization is currently also disabled when under a persistent tape, # since it leads to an unbounded number of side outputs. With caching it may # be possible to re-enable it. optimized_reduction_ops = { "Shape", "Size", "Rank", "TensorListElementShape", "TensorListLength" } if (op_type in optimized_reduction_ops and not util.output_all_intermediates() and all(input.graph is self._forward_graph for input in inputs) and all(_get_accumulator(input) is None for input in inputs) and not util_v1.GraphOrParentsInXlaContext(self._forward_graph) and not util.graph_wrapped_for_higher_order_tape_gradients( self._forward_graph)): return self._move_op_to_forward_graph( op_type, inputs, dtypes=dtypes, input_types=input_types, name=name, attrs=attrs, op_def=op_def, compute_device=compute_device) return super(_WhileBodyGradFuncGraph, self)._create_op_internal( op_type, inputs, dtypes=dtypes, input_types=input_types, name=name, attrs=attrs, op_def=op_def, compute_device=compute_device) def _move_op_to_forward_graph( self, op_type, inputs, dtypes=None, # pylint: disable=redefined-outer-name input_types=None, name=None, attrs=None, op_def=None, compute_device=True): # We have a cache of reduction ops that have already been moved to the # forward graph, and we will check it first to avoid moving an op twice. if not hasattr(self._forward_graph, "_optimized_reduction_ops_cache"): self._forward_graph._optimized_reduction_ops_cache = {} cache_key = self._get_optimized_reduction_ops_cache_key( op_type, inputs, dtypes, input_types, name, attrs, op_def, compute_device) cached_op = self._forward_graph._optimized_reduction_ops_cache.get( cache_key) if cached_op is not None: # This op has already been moved to the forward graph and we have it in # the cache. return cached_op with self._forward_graph.as_default(): # `name` was built using name_scope stack of gradient graph and may not # be unique in the forward graph. `Graph.create_op` does not uniquify # names which are name scopes i.e. end in `/`. To ensure that the op # created gets a unique name in the forward graph we get rid of the # trailing slash. name = ops.name_from_scope_name(name) result = self._forward_graph._create_op_internal( op_type, inputs, dtypes=dtypes, input_types=input_types, name=name, attrs=attrs, op_def=op_def, compute_device=compute_device) # Store the op we just moved to the forward graph so that it does # not need to be added there again. self._forward_graph._optimized_reduction_ops_cache[cache_key] = result return result def _get_optimized_reduction_ops_cache_key( self, op_type, inputs, dtypes=None, # pylint: disable=redefined-outer-name input_types=None, name=None, attrs=None, op_def=None, compute_device=True): # We need all elements of CacheKey to be hashable. inputs = tuple(map(lambda t: t.ref(), inputs)) if dtypes is not None: dtypes = tuple(dtypes) if input_types is not None: input_types = tuple(input_types) if attrs is not None: hashable_attrs = [] for attr_name, attr_value in sorted(attrs.items()): hashable_attrs.append((attr_name, attr_value.SerializeToString())) attrs = tuple(hashable_attrs) if op_def is not None: op_def = op_def.SerializeToString() return OptimizedReductionOpsCacheKey(op_type, inputs, dtypes, input_types, name, attrs, op_def, compute_device) def _capture_helper(self, tensor, name): """Implements the capturing described in the class docstring.""" captured_tensor = self._indirect_captures.get(ops.tensor_id(tensor)) if captured_tensor is not None: return captured_tensor if tensor.graph is not self._forward_graph: already_captured = id(tensor) in self.function_captures.by_val_internal captured_tensor = super(_WhileBodyGradFuncGraph, self)._capture_helper( tensor, name) if not already_captured: # Adds the captured tensor to the list of outputs so that the input # and output signatures match. self.internal_capture_to_output[ops.tensor_id( captured_tensor)] = captured_tensor self._indirect_captures[ops.tensor_id(tensor)] = captured_tensor return captured_tensor while tensor.op.type == "Identity": # We do not accumulate the output of identity nodes so we try to capture # the input of the Identity node instead. tensor = tensor.op.inputs[0] captured_tensor = self._indirect_captures.get(ops.tensor_id(tensor)) if captured_tensor is not None: return captured_tensor # No need to accumulate loop invariants. Capture them directly. # The captured tensor gets resolved to the corresponding while output in # `_resolve_grad_captures`. if _is_loop_invariant(tensor, self._forward_graph.inputs, self._forward_graph.outputs): captured_tensor = super(_WhileBodyGradFuncGraph, self)._capture_helper(tensor, name) # Add to `internal_capture_to_output` so that this gets added to the list # of outputs. self.internal_capture_to_output[ops.tensor_id( captured_tensor)] = captured_tensor self._indirect_captures[ops.tensor_id(tensor)] = captured_tensor return captured_tensor # Do not accumulate Const nodes. Instead copy them directly in the backward # graph. # TODO(srbs): This just checks for `Const` nodes. Consider checking for # graph compile time consts in general. # TODO(srbs): Consider making this a loop input. if constant_op.is_constant(tensor): real_value = constant_op.constant( tensor_util.constant_value(tensor), dtype=tensor.dtype) self._indirect_captures[ops.tensor_id(tensor)] = real_value return real_value # Resource tensors are not accumulated and handled specially. if tensor.dtype == dtypes.resource: return self._resource_capture_helper(tensor) # Create or find an existing accumulator output for `tensor` in the forward # graph, and fetch from this accumulator in the gradient graph to get the # raw intermediate value. accumulator = _get_accumulator(tensor) if accumulator is None: # Create the initial empty tensor list. # # Note: We clear the control dependencies to avoid a cycle in case a # control tensor has an input path to an output of the forward While. # # E.g.: # x = tf.while_loop(...) # y = f(x) # with tf.control_dependencies([y]): # tf.gradients(y, x) # # Since the EmptyTensorList is fed back into the forward While, not # removing the control edge would cause a cycle. with self._forward_graph.outer_graph.as_default(): with util.clear_control_inputs(): tensor_list = list_ops.empty_tensor_list( element_dtype=tensor.dtype, element_shape=tensor.shape, max_num_elements=self._maximum_iterations, name=_build_accumulator_name(tensor)) self.extra_inputs.append(tensor_list) # Push the intermediate tensor to the tensor list. This captures # `tensor_list`. with self._forward_graph.as_default(): accumulator = list_ops.tensor_list_push_back(tensor_list, tensor) # Add the modified tensor list to the list of outputs. This output will be # all the accumulated values. self._forward_graph.outputs.append(accumulator) # Capture in the cond graph as well so the forward cond and body inputs # match. with self._forward_cond_graph.as_default(): self._forward_cond_graph.capture(tensor_list) # Capture the accumulator tensor list in the gradient graph directly from # the forward graph -- we'll later modify this to capture the final list # output by the forward While op instead. captured_accumulator = super(_WhileBodyGradFuncGraph, self)._capture_helper( accumulator, name) # Pop the intermediate value from the tensor list in the gradient graph. new_tensor_list, captured_tensor = list_ops.tensor_list_pop_back( captured_accumulator, element_dtype=tensor.dtype) self._indirect_captures[ops.tensor_id(tensor)] = captured_tensor self.internal_capture_to_output[ops.tensor_id( captured_accumulator)] = new_tensor_list return captured_tensor def _resource_capture_helper(self, tensor): """Returns the captured resource tensor. Resource-type tensors are not accumulated. If a resource tensor exists in the loop body it must either be a loop input or an output of a nested While op inside the loop body which had captured the external resource. Args: tensor: the external resource Tensor to be captured. Returns: Tensor in this graph. """ assert tensor.dtype == dtypes.resource forward_graph_input_names = [t.name for t in self._forward_graph.inputs] forward_graph_name_to_opdef = { op.name: op.node_def for op in self._forward_graph.get_operations()} index = util.resource_input_index( tensor.name, forward_graph_input_names, forward_graph_name_to_opdef, self._forward_graph._functions) input_placeholder = self._forward_graph.inputs[index] tensor_in_outer_graph = self._forward_graph._while.inputs[index] assert input_placeholder.dtype == dtypes.resource assert tensor_in_outer_graph.dtype == dtypes.resource # This must be a loop invariant. However, infrastructure # (e.g. tf.vectorized_map) may insert identity nodes, function calls, conds, # etc. which take and return the resource tensor unmodified; this means that # the Python objects may differ. if index != util.resource_input_index( self._forward_graph.outputs[index].name, forward_graph_input_names, forward_graph_name_to_opdef, self._forward_graph._functions): raise AssertionError( f"Resource tensors must be loop invariants {tensor_in_outer_graph}") self._indirect_captures[ops.tensor_id(tensor)] = self.capture( tensor_in_outer_graph) return self._indirect_captures[ops.tensor_id(tensor)] def _check_shapes_compat(flat_output_tensors, flat_shape_invariants, flat_input_tensors): for (t, shape, input_t) in zip(flat_output_tensors, flat_shape_invariants, flat_input_tensors): if not control_flow_ops._ShapeLessThanOrEqual(t.shape, shape): raise ValueError( f"Input tensor `{input_t.name}` enters the loop with shape {shape}, " f"but has shape {t.shape} after one iteration. To allow the shape to " "vary across iterations, use the `shape_invariants` argument of " "tf.while_loop to specify a less-specific shape.") def _check_num_inputs_outputs(cond_graph, body_graph, num_flattened_loop_vars): """Checks the number of inputs/outputs of `cond_graph` and `body_graph`.""" assert len(cond_graph.inputs) == num_flattened_loop_vars, ( "cond_graph takes %d inputs; Expected: %d" % (len(cond_graph.inputs), num_flattened_loop_vars)) assert len(cond_graph.outputs) == 1, ( "cond_graph has %d outputs; Expected: 1" % len(cond_graph.outputs)) assert len(body_graph.inputs) == num_flattened_loop_vars, ( "body_graph takes %d inputs; Expected: %d" % (len(body_graph.inputs), num_flattened_loop_vars)) assert len(body_graph.outputs) == num_flattened_loop_vars, ( "body_graph has %d outputs; Expected: %d" % (len(body_graph.outputs), num_flattened_loop_vars)) def _check_inputs_outputs_types_match(body_graph, flattened_loop_vars): for inp, out, loop_var in zip(body_graph.inputs, body_graph.outputs, flattened_loop_vars): if inp.dtype != out.dtype: raise TypeError( f"Loop var {loop_var.name} enters the loop with type {inp.dtype} " f"but has type {out.dtype} after 1 iteration. {loop_var.name} type " "should remain constant.") def _build_cond_placeholders_name_prefix(cond_graph): return cond_graph.unique_name(cond_graph.name + "___redundant_placeholder") def _duplicate_body_captures_in_cond(cond_graph, body_graph_captures): """Creates placeholders for body captures in cond_graph. This is needed to match signatures of cond and body graphs. Args: cond_graph: cond branch graph body_graph_captures: Tensors which were captured when building the `body_graph`. """ types = [t.dtype.as_datatype_enum for t in body_graph_captures] # TODO(srbs): Providing a unique prefix does not ensure that there is no # conflict between the placeholder names and existing nodes in the graph. # However passing a list of strings may not be performant. # Ideally we should move `Graph.unique_name` to C++ or make # `Graph._names_in_use` a trie so that we can find a unique prefix. # TODO(b/143286622): This should not be required once captures are separated # from regular loop vars. with cond_graph._c_graph.get() as c_graph: placeholders = c_api.TF_CreatePlaceholders( c_graph, types, compat.as_str(_build_cond_placeholders_name_prefix(cond_graph))) placeholder_ops = [ ops.Operation._from_c_op(ph.oper, cond_graph) for ph in placeholders ] tensors = [] for op in placeholder_ops: tensors.append(op.outputs[0]) # Update `cond_graph._captures` and `cond_graph.inputs` to contain the # newly created placeholders. tuples = zip(body_graph_captures, tensors) keys = [id(t) for t in body_graph_captures] for k, v in zip(keys, tuples): cond_graph._function_captures.add_or_replace( key=k, external=v[0], internal=v[1], is_by_ref=False) cond_graph.inputs.extend(tensors) def _copy_handle_data(src_tensors, tgt_tensors): for src_t, tgt_t in zip(src_tensors, tgt_tensors): handle_data_util.copy_handle_data(src_t, tgt_t) def _pack_sequence_as(loop_vars_signature, flat_orig_loop_vars, loop_vars): """Like `nest.pack_sequence_as` but also replaces flows with TensorArrays.""" def flow_to_tensor_array(flow, ta): # pylint: disable=missing-docstring return (tensor_array_ops.build_ta_with_new_flow(ta, flow) if isinstance( # pylint: disable=g-long-ternary ta, tensor_array_ops.TensorArray) else flow) flattened_loop_vars = [ flow_to_tensor_array(*z) for z in zip(nest.flatten(loop_vars, expand_composites=True), flat_orig_loop_vars) ] return nest.pack_sequence_as(loop_vars_signature, flattened_loop_vars, expand_composites=True) def _tensor_array_to_flow(loop_vars): def f(maybe_ta): if isinstance(maybe_ta, tensor_array_ops.TensorArray): return maybe_ta.flow return maybe_ta return nest.map_structure(f, loop_vars, expand_composites=True) def _build_maximum_iterations_loop_var(maximum_iterations): if maximum_iterations is None: # Default value for max_num_elements to EmptyTensorList meaning that the # list size is unbounded. maximum_iterations = -1 # EmptyTensorList expects `max_num_elements` to be of type int32. return ops.convert_to_tensor( maximum_iterations, dtype=dtypes.int32, name="maximum_iterations") def _build_accumulator_name(tensor): # Tensor name may be of the form "pow/y:0". Name scope does not allow ":". return "{}/accumulator".format(tensor.name).replace(":", "_") def _is_loop_invariant(tensor, inputs, outputs): return (any(tensor is t for t in inputs) and any(tensor is t for t in outputs)) def _set_read_only_resource_inputs_attr(op: ops.Operation, branch_graphs): """Sets the list of resource inputs which are read-only. This is used by AutomaticControlDependencies. Args: op: While Operation. branch_graphs: List of branch FuncGraphs. """ read_only_indices = set(range(len(op.inputs))) for branch_graph in branch_graphs: if not read_only_indices: break branch_read_only_indices = acd.get_read_only_resource_input_indices_graph( branch_graph) read_only_indices = read_only_indices.intersection(branch_read_only_indices) ops.set_int_list_attr(op, acd.READ_ONLY_RESOURCE_INPUTS_ATTR, sorted(read_only_indices)) def async_noop(name=None): """Returns a no-op that is implemented as an async kernel. This operation may be useful to implement "aggressive inter-op parallelism" because it will cause any immediate downstream operations to be scheduled on different threads. Args: name: The name of the operation. """ with ops.name_scope(name, "async_noop") as name: cond_init_value = constant_op.constant(False, name="cond_init_value") func_graph_signature = [tensor_spec.TensorSpec(shape=(), dtype=dtypes.bool)] cond_graph = func_graph_module.func_graph_from_py_func( "cond_graph", lambda x: x, [cond_init_value], {}, signature=func_graph_signature, func_graph=util.WhileCondFuncGraph( "cond_graph", collections=ops.get_default_graph()._collections ), # pylint: disable=protected-access add_control_dependencies=False, ) body_graph = func_graph_module.func_graph_from_py_func( "body_graph", lambda x: x, [cond_init_value], {}, signature=func_graph_signature, func_graph=util.WhileBodyFuncGraph( "body_graph", collections=ops.get_default_graph()._collections ), # pylint: disable=protected-access add_control_dependencies=False, ) while_op, _ = util.get_op_and_outputs( gen_functional_ops._while( [cond_init_value], util.create_new_tf_function(cond_graph), util.create_new_tf_function(body_graph), output_shapes=[[]], name=name, ) ) # Disable lowering using switch merge. util.maybe_set_lowering_attr(while_op, lower_using_switch_merge=False) return while_op # pylint: enable=protected-access
_WhileBodyGradFuncGraph
python
getsentry__sentry
tests/sentry/backup/test_exports.py
{ "start": 3750, "end": 5390 }
class ____(BackupTransactionTestCase): @staticmethod def count(data: Any, model: type[models.base.BaseModel]) -> int: return len(list(filter(lambda d: d["model"] == str(get_model_name(model)), data))) @staticmethod def exists( data: Any, model: type[models.base.BaseModel], key: str, value: Any | None = None ) -> bool: for d in data: if d["model"] == str(get_model_name(model)): field = d["fields"].get(key) if field is None: continue if value is None: return True if field == value: return True return False def export( self, tmp_dir: str, *, scope: ExportScope, filter_by: set[str] | None = None, checkpointer: ExportCheckpointer | None = None, ) -> Any: tmp_path = Path(tmp_dir).joinpath(f"{self._testMethodName}.json") return export_to_file(tmp_path, scope=scope, filter_by=filter_by, checkpointer=checkpointer) def export_and_encrypt( self, tmp_dir: str, *, scope: ExportScope, rsa_key_pair: tuple[bytes, bytes], filter_by: set[str] | None = None, checkpointer: ExportCheckpointer | None = None, ) -> Any: tmp_path = Path(tmp_dir).joinpath(f"{self._testMethodName}.enc.tar") return export_to_encrypted_tarball( tmp_path, scope=scope, filter_by=filter_by, checkpointer=checkpointer, rsa_key_pair=rsa_key_pair, )
ExportTestCase
python
keras-team__keras
keras/src/optimizers/ftrl_test.py
{ "start": 168, "end": 4402 }
class ____(testing.TestCase): def test_config(self): optimizer = Ftrl( learning_rate=0.05, learning_rate_power=-0.2, initial_accumulator_value=0.4, l1_regularization_strength=0.05, l2_regularization_strength=0.15, l2_shrinkage_regularization_strength=0.01, beta=0.3, ) self.run_class_serialization_test(optimizer) def test_single_step(self): optimizer = Ftrl(learning_rate=0.5) grads = np.array([1.0, 6.0, 7.0, 2.0]) vars = backend.Variable([1.0, 2.0, 3.0, 4.0]) optimizer.apply_gradients(zip([grads], [vars])) self.assertAllClose( vars, [0.2218, 1.3954, 2.3651, 2.8814], rtol=1e-4, atol=1e-4 ) def test_correctness_with_golden(self): optimizer = Ftrl( learning_rate=0.05, learning_rate_power=-0.2, initial_accumulator_value=0.4, l1_regularization_strength=0.05, l2_regularization_strength=0.15, l2_shrinkage_regularization_strength=0.01, beta=0.3, ) x = backend.Variable(np.ones([10])) grads = np.arange(0.1, 1.1, 0.1) first_grads = np.full((10,), 0.01) # fmt: off golden = np.array( [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [-0.0034, -0.0077, -0.0118, -0.0157, -0.0194, -0.023, -0.0263, -0.0294, -0.0325, -0.0354], [-0.0078, -0.0162, -0.0242, -0.0317, -0.0387, -0.0454, -0.0516, -0.0575, -0.0631, -0.0685], [-0.0121, -0.0246, -0.0363, -0.0472, -0.0573, -0.0668, -0.0757, -0.0842, -0.0922, -0.0999], [-0.0164, -0.0328, -0.0481, -0.0623, -0.0753, -0.0875, -0.099, -0.1098, -0.1201, -0.1299]] ) # fmt: on optimizer.apply_gradients(zip([first_grads], [x])) for i in range(5): self.assertAllClose(x, golden[i], rtol=5e-4, atol=5e-4) optimizer.apply_gradients(zip([grads], [x])) def test_clip_norm(self): optimizer = Ftrl(clipnorm=1) grad = [np.array([100.0, 100.0])] clipped_grad = optimizer._clip_gradients(grad) self.assertAllClose(clipped_grad[0], [2**0.5 / 2, 2**0.5 / 2]) def test_clip_value(self): optimizer = Ftrl(clipvalue=1) grad = [np.array([100.0, 100.0])] clipped_grad = optimizer._clip_gradients(grad) self.assertAllClose(clipped_grad[0], [1.0, 1.0]) def test_invalid_initial_accumulator_value(self): invalid_value = -0.1 with self.assertRaisesRegex( ValueError, f"^`initial_accumulator_value` needs to be positive or zero. Received: initial_accumulator_value={invalid_value}.$", ): Ftrl(initial_accumulator_value=invalid_value) def test_invalid_learning_rate_power(self): invalid_value = 0.1 with self.assertRaisesRegex( ValueError, f"^`learning_rate_power` needs to be negative or zero. Received: learning_rate_power={invalid_value}.$", ): Ftrl(learning_rate_power=invalid_value) def test_invalid_l1_regularization_strength(self): invalid_value = -0.1 with self.assertRaisesRegex( ValueError, f"^`l1_regularization_strength` needs to be positive or zero. Received: l1_regularization_strength={invalid_value}.$", ): Ftrl(l1_regularization_strength=invalid_value) def test_invalid_l2_regularization_strength(self): invalid_value = -0.1 with self.assertRaisesRegex( ValueError, f"^`l2_regularization_strength` needs to be positive or zero. Received: l2_regularization_strength={invalid_value}.$", ): Ftrl(l2_regularization_strength=invalid_value) def test_invalid_l2_shrinkage_regularization_strength(self): invalid_value = -0.1 with self.assertRaisesRegex( ValueError, f"^`l2_shrinkage_regularization_strength` needs to be positive or zero. Received: l2_shrinkage_regularization_strength={invalid_value}.$", ): Ftrl(l2_shrinkage_regularization_strength=invalid_value)
FtrlTest
python
huggingface__transformers
src/transformers/models/t5/modeling_t5.py
{ "start": 23421, "end": 28478 }
class ____(PreTrainedModel): config: T5Config base_model_prefix = "transformer" supports_gradient_checkpointing = True _can_compile_fullgraph = True _no_split_modules = ["T5Block"] _keep_in_fp32_modules = ["wo"] @property def dummy_inputs(self): input_ids = torch.tensor(DUMMY_INPUTS) input_mask = torch.tensor(DUMMY_MASK) dummy_inputs = { "decoder_input_ids": input_ids, "input_ids": input_ids, "decoder_attention_mask": input_mask, } return dummy_inputs @torch.no_grad() def _init_weights(self, module): """Initialize the weights""" factor = self.config.initializer_factor # Used for testing weights initialization if isinstance(module, T5LayerNorm): init.constant_(module.weight, factor * 1.0) elif isinstance( module, (T5Model, T5ForConditionalGeneration, T5EncoderModel, T5ForQuestionAnswering), ): init.normal_(module.shared.weight, mean=0.0, std=factor * 1.0) if hasattr(module, "lm_head") and not self.config.tie_word_embeddings: init.normal_(module.lm_head.weight, mean=0.0, std=factor * 1.0) if hasattr(module, "qa_outputs"): init.normal_(module.qa_outputs.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5)) init.zeros_(module.qa_outputs.bias) elif isinstance(module, T5ForTokenClassification): if hasattr(module, "classifier"): init.normal_(module.classifier.weight, mean=0.0, std=factor * 1.0) init.zeros_(module.classifier.bias) elif isinstance(module, T5ClassificationHead): init.normal_(module.dense.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5)) if hasattr(module.dense, "bias") and module.dense.bias is not None: init.zeros_(module.dense.bias) init.normal_(module.out_proj.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5)) if hasattr(module.out_proj, "bias") and module.out_proj.bias is not None: init.zeros_(module.out_proj.bias) elif isinstance(module, T5DenseActDense): init.normal_(module.wi.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5)) if hasattr(module.wi, "bias") and module.wi.bias is not None: init.zeros_(module.wi.bias) init.normal_(module.wo.weight, mean=0.0, std=factor * ((self.config.d_ff) ** -0.5)) if hasattr(module.wo, "bias") and module.wo.bias is not None: init.zeros_(module.wo.bias) elif isinstance(module, T5DenseGatedActDense): init.normal_(module.wi_0.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5)) if hasattr(module.wi_0, "bias") and module.wi_0.bias is not None: init.zeros_(module.wi_0.bias) init.normal_(module.wi_1.weight, mean=0.0, std=factor * ((self.config.d_model) ** -0.5)) if hasattr(module.wi_1, "bias") and module.wi_1.bias is not None: init.zeros_(module.wi_1.bias) init.normal_(module.wo.weight, mean=0.0, std=factor * ((self.config.d_ff) ** -0.5)) if hasattr(module.wo, "bias") and module.wo.bias is not None: init.zeros_(module.wo.bias) elif isinstance(module, T5Attention): d_model = self.config.d_model key_value_proj_dim = self.config.d_kv n_heads = self.config.num_heads init.normal_(module.q.weight, mean=0.0, std=factor * ((d_model * key_value_proj_dim) ** -0.5)) init.normal_(module.k.weight, mean=0.0, std=factor * (d_model**-0.5)) init.normal_(module.v.weight, mean=0.0, std=factor * (d_model**-0.5)) init.normal_(module.o.weight, mean=0.0, std=factor * ((n_heads * key_value_proj_dim) ** -0.5)) if module.has_relative_attention_bias: init.normal_(module.relative_attention_bias.weight, mean=0.0, std=factor * ((d_model) ** -0.5)) def _shift_right(self, input_ids): decoder_start_token_id = self.config.decoder_start_token_id pad_token_id = self.config.pad_token_id if decoder_start_token_id is None: raise ValueError( "self.model.config.decoder_start_token_id has to be defined. In T5 it is usually set to the pad_token_id. " "See T5 docs for more information." ) shifted_input_ids = input_ids.new_zeros(input_ids.shape) shifted_input_ids[..., 1:] = input_ids[..., :-1].clone() shifted_input_ids[..., 0] = decoder_start_token_id if pad_token_id is None: raise ValueError("self.model.config.pad_token_id has to be defined.") # replace possible -100 values in labels by `pad_token_id` shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id) return shifted_input_ids
T5PreTrainedModel
python
takluyver__flit
flit/install.py
{ "start": 2796, "end": 2933 }
class ____(Exception): def __str__(self): return 'To install dependencies for extras, you cannot set deps=none.'
DependencyError
python
wandb__wandb
wandb/vendor/pygments/lexers/r.py
{ "start": 2331, "end": 22534 }
class ____(RegexLexer): """ For S, S-plus, and R source code. .. versionadded:: 0.10 """ name = 'S' aliases = ['splus', 's', 'r'] filenames = ['*.S', '*.R', '.Rhistory', '.Rprofile', '.Renviron'] mimetypes = ['text/S-plus', 'text/S', 'text/x-r-source', 'text/x-r', 'text/x-R', 'text/x-r-history', 'text/x-r-profile'] builtins_base = ( 'Arg', 'Conj', 'Cstack_info', 'Encoding', 'FALSE', 'Filter', 'Find', 'I', 'ISOdate', 'ISOdatetime', 'Im', 'Inf', 'La.svd', 'Map', 'Math.Date', 'Math.POSIXt', 'Math.data.frame', 'Math.difftime', 'Math.factor', 'Mod', 'NA_character_', 'NA_complex_', 'NA_real_', 'NCOL', 'NROW', 'NULLNA_integer_', 'NaN', 'Negate', 'NextMethod', 'Ops.Date', 'Ops.POSIXt', 'Ops.data.frame', 'Ops.difftime', 'Ops.factor', 'Ops.numeric_version', 'Ops.ordered', 'Position', 'R.Version', 'R.home', 'R.version', 'R.version.string', 'RNGkind', 'RNGversion', 'R_system_version', 'Re', 'Recall', 'Reduce', 'Summary.Date', 'Summary.POSIXct', 'Summary.POSIXlt', 'Summary.data.frame', 'Summary.difftime', 'Summary.factor', 'Summary.numeric_version', 'Summary.ordered', 'Sys.Date', 'Sys.chmod', 'Sys.getenv', 'Sys.getlocale', 'Sys.getpid', 'Sys.glob', 'Sys.info', 'Sys.localeconv', 'Sys.readlink', 'Sys.setFileTime', 'Sys.setenv', 'Sys.setlocale', 'Sys.sleep', 'Sys.time', 'Sys.timezone', 'Sys.umask', 'Sys.unsetenv', 'Sys.which', 'TRUE', 'UseMethod', 'Vectorize', 'abbreviate', 'abs', 'acos', 'acosh', 'addNA', 'addTaskCallback', 'agrep', 'alist', 'all', 'all.equal', 'all.equal.POSIXct', 'all.equal.character', 'all.equal.default', 'all.equal.factor', 'all.equal.formula', 'all.equal.language', 'all.equal.list', 'all.equal.numeric', 'all.equal.raw', 'all.names', 'all.vars', 'any', 'anyDuplicated', 'anyDuplicated.array', 'anyDuplicated.data.frame', 'anyDuplicated.default', 'anyDuplicated.matrix', 'aperm', 'aperm.default', 'aperm.table', 'append', 'apply', 'args', 'arrayInd', 'as.Date', 'as.Date.POSIXct', 'as.Date.POSIXlt', 'as.Date.character', 'as.Date.date', 'as.Date.dates', 'as.Date.default', 'as.Date.factor', 'as.Date.numeric', 'as.POSIXct', 'as.POSIXct.Date', 'as.POSIXct.POSIXlt', 'as.POSIXct.date', 'as.POSIXct.dates', 'as.POSIXct.default', 'as.POSIXct.numeric', 'as.POSIXlt', 'as.POSIXlt.Date', 'as.POSIXlt.POSIXct', 'as.POSIXlt.character', 'as.POSIXlt.date', 'as.POSIXlt.dates', 'as.POSIXlt.default', 'as.POSIXlt.factor', 'as.POSIXlt.numeric', 'as.array', 'as.array.default', 'as.call', 'as.character', 'as.character.Date', 'as.character.POSIXt', 'as.character.condition', 'as.character.default', 'as.character.error', 'as.character.factor', 'as.character.hexmode', 'as.character.numeric_version', 'as.character.octmode', 'as.character.srcref', 'as.complex', 'as.data.frame', 'as.data.frame.AsIs', 'as.data.frame.Date', 'as.data.frame.POSIXct', 'as.data.frame.POSIXlt', 'as.data.frame.array', 'as.data.frame.character', 'as.data.frame.complex', 'as.data.frame.data.frame', 'as.data.frame.default', 'as.data.frame.difftime', 'as.data.frame.factor', 'as.data.frame.integer', 'as.data.frame.list', 'as.data.frame.logical', 'as.data.frame.matrix', 'as.data.frame.model.matrix', 'as.data.frame.numeric', 'as.data.frame.numeric_version', 'as.data.frame.ordered', 'as.data.frame.raw', 'as.data.frame.table', 'as.data.frame.ts', 'as.data.frame.vector', 'as.difftime', 'as.double', 'as.double.POSIXlt', 'as.double.difftime', 'as.environment', 'as.expression', 'as.expression.default', 'as.factor', 'as.function', 'as.function.default', 'as.hexmode', 'as.integer', 'as.list', 'as.list.Date', 'as.list.POSIXct', 'as.list.data.frame', 'as.list.default', 'as.list.environment', 'as.list.factor', 'as.list.function', 'as.list.numeric_version', 'as.logical', 'as.logical.factor', 'as.matrix', 'as.matrix.POSIXlt', 'as.matrix.data.frame', 'as.matrix.default', 'as.matrix.noquote', 'as.name', 'as.null', 'as.null.default', 'as.numeric', 'as.numeric_version', 'as.octmode', 'as.ordered', 'as.package_version', 'as.pairlist', 'as.qr', 'as.raw', 'as.single', 'as.single.default', 'as.symbol', 'as.table', 'as.table.default', 'as.vector', 'as.vector.factor', 'asNamespace', 'asS3', 'asS4', 'asin', 'asinh', 'assign', 'atan', 'atan2', 'atanh', 'attachNamespace', 'attr', 'attr.all.equal', 'attributes', 'autoload', 'autoloader', 'backsolve', 'baseenv', 'basename', 'besselI', 'besselJ', 'besselK', 'besselY', 'beta', 'bindingIsActive', 'bindingIsLocked', 'bindtextdomain', 'bitwAnd', 'bitwNot', 'bitwOr', 'bitwShiftL', 'bitwShiftR', 'bitwXor', 'body', 'bquote', 'browser', 'browserCondition', 'browserSetDebug', 'browserText', 'builtins', 'by', 'by.data.frame', 'by.default', 'bzfile', 'c.Date', 'c.POSIXct', 'c.POSIXlt', 'c.noquote', 'c.numeric_version', 'call', 'callCC', 'capabilities', 'casefold', 'cat', 'category', 'cbind', 'cbind.data.frame', 'ceiling', 'char.expand', 'charToRaw', 'charmatch', 'chartr', 'check_tzones', 'chol', 'chol.default', 'chol2inv', 'choose', 'class', 'clearPushBack', 'close', 'close.connection', 'close.srcfile', 'close.srcfilealias', 'closeAllConnections', 'col', 'colMeans', 'colSums', 'colnames', 'commandArgs', 'comment', 'computeRestarts', 'conditionCall', 'conditionCall.condition', 'conditionMessage', 'conditionMessage.condition', 'conflicts', 'contributors', 'cos', 'cosh', 'crossprod', 'cummax', 'cummin', 'cumprod', 'cumsum', 'cut', 'cut.Date', 'cut.POSIXt', 'cut.default', 'dQuote', 'data.class', 'data.matrix', 'date', 'debug', 'debugonce', 'default.stringsAsFactors', 'delayedAssign', 'deparse', 'det', 'determinant', 'determinant.matrix', 'dget', 'diag', 'diff', 'diff.Date', 'diff.POSIXt', 'diff.default', 'difftime', 'digamma', 'dim', 'dim.data.frame', 'dimnames', 'dimnames.data.frame', 'dir', 'dir.create', 'dirname', 'do.call', 'dput', 'drop', 'droplevels', 'droplevels.data.frame', 'droplevels.factor', 'dump', 'duplicated', 'duplicated.POSIXlt', 'duplicated.array', 'duplicated.data.frame', 'duplicated.default', 'duplicated.matrix', 'duplicated.numeric_version', 'dyn.load', 'dyn.unload', 'eapply', 'eigen', 'else', 'emptyenv', 'enc2native', 'enc2utf8', 'encodeString', 'enquote', 'env.profile', 'environment', 'environmentIsLocked', 'environmentName', 'eval', 'eval.parent', 'evalq', 'exists', 'exp', 'expand.grid', 'expm1', 'expression', 'factor', 'factorial', 'fifo', 'file', 'file.access', 'file.append', 'file.choose', 'file.copy', 'file.create', 'file.exists', 'file.info', 'file.link', 'file.path', 'file.remove', 'file.rename', 'file.show', 'file.symlink', 'find.package', 'findInterval', 'findPackageEnv', 'findRestart', 'floor', 'flush', 'flush.connection', 'force', 'formals', 'format', 'format.AsIs', 'format.Date', 'format.POSIXct', 'format.POSIXlt', 'format.data.frame', 'format.default', 'format.difftime', 'format.factor', 'format.hexmode', 'format.info', 'format.libraryIQR', 'format.numeric_version', 'format.octmode', 'format.packageInfo', 'format.pval', 'format.summaryDefault', 'formatC', 'formatDL', 'forwardsolve', 'gamma', 'gc', 'gc.time', 'gcinfo', 'gctorture', 'gctorture2', 'get', 'getAllConnections', 'getCallingDLL', 'getCallingDLLe', 'getConnection', 'getDLLRegisteredRoutines', 'getDLLRegisteredRoutines.DLLInfo', 'getDLLRegisteredRoutines.character', 'getElement', 'getExportedValue', 'getHook', 'getLoadedDLLs', 'getNamespace', 'getNamespaceExports', 'getNamespaceImports', 'getNamespaceInfo', 'getNamespaceName', 'getNamespaceUsers', 'getNamespaceVersion', 'getNativeSymbolInfo', 'getOption', 'getRversion', 'getSrcLines', 'getTaskCallbackNames', 'geterrmessage', 'gettext', 'gettextf', 'getwd', 'gl', 'globalenv', 'gregexpr', 'grep', 'grepRaw', 'grepl', 'gsub', 'gzcon', 'gzfile', 'head', 'iconv', 'iconvlist', 'icuSetCollate', 'identical', 'identity', 'ifelse', 'importIntoEnv', 'in', 'inherits', 'intToBits', 'intToUtf8', 'interaction', 'interactive', 'intersect', 'inverse.rle', 'invisible', 'invokeRestart', 'invokeRestartInteractively', 'is.R', 'is.array', 'is.atomic', 'is.call', 'is.character', 'is.complex', 'is.data.frame', 'is.double', 'is.element', 'is.environment', 'is.expression', 'is.factor', 'is.finite', 'is.function', 'is.infinite', 'is.integer', 'is.language', 'is.list', 'is.loaded', 'is.logical', 'is.matrix', 'is.na', 'is.na.POSIXlt', 'is.na.data.frame', 'is.na.numeric_version', 'is.name', 'is.nan', 'is.null', 'is.numeric', 'is.numeric.Date', 'is.numeric.POSIXt', 'is.numeric.difftime', 'is.numeric_version', 'is.object', 'is.ordered', 'is.package_version', 'is.pairlist', 'is.primitive', 'is.qr', 'is.raw', 'is.recursive', 'is.single', 'is.symbol', 'is.table', 'is.unsorted', 'is.vector', 'isBaseNamespace', 'isIncomplete', 'isNamespace', 'isOpen', 'isRestart', 'isS4', 'isSeekable', 'isSymmetric', 'isSymmetric.matrix', 'isTRUE', 'isatty', 'isdebugged', 'jitter', 'julian', 'julian.Date', 'julian.POSIXt', 'kappa', 'kappa.default', 'kappa.lm', 'kappa.qr', 'kronecker', 'l10n_info', 'labels', 'labels.default', 'lapply', 'lazyLoad', 'lazyLoadDBexec', 'lazyLoadDBfetch', 'lbeta', 'lchoose', 'length', 'length.POSIXlt', 'letters', 'levels', 'levels.default', 'lfactorial', 'lgamma', 'library.dynam', 'library.dynam.unload', 'licence', 'license', 'list.dirs', 'list.files', 'list2env', 'load', 'loadNamespace', 'loadedNamespaces', 'loadingNamespaceInfo', 'local', 'lockBinding', 'lockEnvironment', 'log', 'log10', 'log1p', 'log2', 'logb', 'lower.tri', 'ls', 'make.names', 'make.unique', 'makeActiveBinding', 'mapply', 'margin.table', 'mat.or.vec', 'match', 'match.arg', 'match.call', 'match.fun', 'max', 'max.col', 'mean', 'mean.Date', 'mean.POSIXct', 'mean.POSIXlt', 'mean.default', 'mean.difftime', 'mem.limits', 'memCompress', 'memDecompress', 'memory.profile', 'merge', 'merge.data.frame', 'merge.default', 'message', 'mget', 'min', 'missing', 'mode', 'month.abb', 'month.name', 'months', 'months.Date', 'months.POSIXt', 'months.abb', 'months.nameletters', 'names', 'names.POSIXlt', 'namespaceExport', 'namespaceImport', 'namespaceImportClasses', 'namespaceImportFrom', 'namespaceImportMethods', 'nargs', 'nchar', 'ncol', 'new.env', 'ngettext', 'nlevels', 'noquote', 'norm', 'normalizePath', 'nrow', 'numeric_version', 'nzchar', 'objects', 'oldClass', 'on.exit', 'open', 'open.connection', 'open.srcfile', 'open.srcfilealias', 'open.srcfilecopy', 'options', 'order', 'ordered', 'outer', 'packBits', 'packageEvent', 'packageHasNamespace', 'packageStartupMessage', 'package_version', 'pairlist', 'parent.env', 'parent.frame', 'parse', 'parseNamespaceFile', 'paste', 'paste0', 'path.expand', 'path.package', 'pipe', 'pmatch', 'pmax', 'pmax.int', 'pmin', 'pmin.int', 'polyroot', 'pos.to.env', 'pretty', 'pretty.default', 'prettyNum', 'print', 'print.AsIs', 'print.DLLInfo', 'print.DLLInfoList', 'print.DLLRegisteredRoutines', 'print.Date', 'print.NativeRoutineList', 'print.POSIXct', 'print.POSIXlt', 'print.by', 'print.condition', 'print.connection', 'print.data.frame', 'print.default', 'print.difftime', 'print.factor', 'print.function', 'print.hexmode', 'print.libraryIQR', 'print.listof', 'print.noquote', 'print.numeric_version', 'print.octmode', 'print.packageInfo', 'print.proc_time', 'print.restart', 'print.rle', 'print.simple.list', 'print.srcfile', 'print.srcref', 'print.summary.table', 'print.summaryDefault', 'print.table', 'print.warnings', 'prmatrix', 'proc.time', 'prod', 'prop.table', 'provideDimnames', 'psigamma', 'pushBack', 'pushBackLength', 'q', 'qr', 'qr.Q', 'qr.R', 'qr.X', 'qr.coef', 'qr.default', 'qr.fitted', 'qr.qty', 'qr.qy', 'qr.resid', 'qr.solve', 'quarters', 'quarters.Date', 'quarters.POSIXt', 'quit', 'quote', 'range', 'range.default', 'rank', 'rapply', 'raw', 'rawConnection', 'rawConnectionValue', 'rawShift', 'rawToBits', 'rawToChar', 'rbind', 'rbind.data.frame', 'rcond', 'read.dcf', 'readBin', 'readChar', 'readLines', 'readRDS', 'readRenviron', 'readline', 'reg.finalizer', 'regexec', 'regexpr', 'registerS3method', 'registerS3methods', 'regmatches', 'remove', 'removeTaskCallback', 'rep', 'rep.Date', 'rep.POSIXct', 'rep.POSIXlt', 'rep.factor', 'rep.int', 'rep.numeric_version', 'rep_len', 'replace', 'replicate', 'requireNamespace', 'restartDescription', 'restartFormals', 'retracemem', 'rev', 'rev.default', 'rle', 'rm', 'round', 'round.Date', 'round.POSIXt', 'row', 'row.names', 'row.names.data.frame', 'row.names.default', 'rowMeans', 'rowSums', 'rownames', 'rowsum', 'rowsum.data.frame', 'rowsum.default', 'sQuote', 'sample', 'sample.int', 'sapply', 'save', 'save.image', 'saveRDS', 'scale', 'scale.default', 'scan', 'search', 'searchpaths', 'seek', 'seek.connection', 'seq', 'seq.Date', 'seq.POSIXt', 'seq.default', 'seq.int', 'seq_along', 'seq_len', 'sequence', 'serialize', 'set.seed', 'setHook', 'setNamespaceInfo', 'setSessionTimeLimit', 'setTimeLimit', 'setdiff', 'setequal', 'setwd', 'shQuote', 'showConnections', 'sign', 'signalCondition', 'signif', 'simpleCondition', 'simpleError', 'simpleMessage', 'simpleWarning', 'simplify2array', 'sin', 'single', 'sinh', 'sink', 'sink.number', 'slice.index', 'socketConnection', 'socketSelect', 'solve', 'solve.default', 'solve.qr', 'sort', 'sort.POSIXlt', 'sort.default', 'sort.int', 'sort.list', 'split', 'split.Date', 'split.POSIXct', 'split.data.frame', 'split.default', 'sprintf', 'sqrt', 'srcfile', 'srcfilealias', 'srcfilecopy', 'srcref', 'standardGeneric', 'stderr', 'stdin', 'stdout', 'stop', 'stopifnot', 'storage.mode', 'strftime', 'strptime', 'strsplit', 'strtoi', 'strtrim', 'structure', 'strwrap', 'sub', 'subset', 'subset.data.frame', 'subset.default', 'subset.matrix', 'substitute', 'substr', 'substring', 'sum', 'summary', 'summary.Date', 'summary.POSIXct', 'summary.POSIXlt', 'summary.connection', 'summary.data.frame', 'summary.default', 'summary.factor', 'summary.matrix', 'summary.proc_time', 'summary.srcfile', 'summary.srcref', 'summary.table', 'suppressMessages', 'suppressPackageStartupMessages', 'suppressWarnings', 'svd', 'sweep', 'sys.call', 'sys.calls', 'sys.frame', 'sys.frames', 'sys.function', 'sys.load.image', 'sys.nframe', 'sys.on.exit', 'sys.parent', 'sys.parents', 'sys.save.image', 'sys.source', 'sys.status', 'system', 'system.file', 'system.time', 'system2', 't', 't.data.frame', 't.default', 'table', 'tabulate', 'tail', 'tan', 'tanh', 'tapply', 'taskCallbackManager', 'tcrossprod', 'tempdir', 'tempfile', 'testPlatformEquivalence', 'textConnection', 'textConnectionValue', 'toString', 'toString.default', 'tolower', 'topenv', 'toupper', 'trace', 'traceback', 'tracemem', 'tracingState', 'transform', 'transform.data.frame', 'transform.default', 'trigamma', 'trunc', 'trunc.Date', 'trunc.POSIXt', 'truncate', 'truncate.connection', 'try', 'tryCatch', 'typeof', 'unclass', 'undebug', 'union', 'unique', 'unique.POSIXlt', 'unique.array', 'unique.data.frame', 'unique.default', 'unique.matrix', 'unique.numeric_version', 'units', 'units.difftime', 'unix.time', 'unlink', 'unlist', 'unloadNamespace', 'unlockBinding', 'unname', 'unserialize', 'unsplit', 'untrace', 'untracemem', 'unz', 'upper.tri', 'url', 'utf8ToInt', 'vapply', 'version', 'warning', 'warnings', 'weekdays', 'weekdays.Date', 'weekdays.POSIXt', 'which', 'which.max', 'which.min', 'with', 'with.default', 'withCallingHandlers', 'withRestarts', 'withVisible', 'within', 'within.data.frame', 'within.list', 'write', 'write.dcf', 'writeBin', 'writeChar', 'writeLines', 'xor', 'xor.hexmode', 'xor.octmode', 'xpdrows.data.frame', 'xtfrm', 'xtfrm.AsIs', 'xtfrm.Date', 'xtfrm.POSIXct', 'xtfrm.POSIXlt', 'xtfrm.Surv', 'xtfrm.default', 'xtfrm.difftime', 'xtfrm.factor', 'xtfrm.numeric_version', 'xzfile', 'zapsmall' ) tokens = { 'comments': [ (r'#.*$', Comment.Single), ], 'valid_name': [ (r'[a-zA-Z][\w.]*', Text), # can begin with ., but not if that is followed by a digit (r'\.[a-zA-Z_][\w.]*', Text), ], 'punctuation': [ (r'\[{1,2}|\]{1,2}|\(|\)|;|,', Punctuation), ], 'keywords': [ (words(builtins_base, suffix=r'(?![\w. =])'), Keyword.Pseudo), (r'(if|else|for|while|repeat|in|next|break|return|switch|function)' r'(?![\w.])', Keyword.Reserved), (r'(array|category|character|complex|double|function|integer|list|' r'logical|matrix|numeric|vector|data.frame|c)' r'(?![\w.])', Keyword.Type), (r'(library|require|attach|detach|source)' r'(?![\w.])', Keyword.Namespace) ], 'operators': [ (r'<<?-|->>?|-|==|<=|>=|<|>|&&?|!=|\|\|?|\?', Operator), (r'\*|\+|\^|/|!|%[^%]*%|=|~|\$|@|:{1,3}', Operator) ], 'builtin_symbols': [ (r'(NULL|NA(_(integer|real|complex|character)_)?|' r'letters|LETTERS|Inf|TRUE|FALSE|NaN|pi|\.\.(\.|[0-9]+))' r'(?![\w.])', Keyword.Constant), (r'(T|F)\b', Name.Builtin.Pseudo), ], 'numbers': [ # hex number (r'0[xX][a-fA-F0-9]+([pP][0-9]+)?[Li]?', Number.Hex), # decimal number (r'[+-]?([0-9]+(\.[0-9]+)?|\.[0-9]+|\.)([eE][+-]?[0-9]+)?[Li]?', Number), ], 'statements': [ include('comments'), # whitespaces (r'\s+', Text), (r'`.*?`', String.Backtick), (r'\'', String, 'string_squote'), (r'\"', String, 'string_dquote'), include('builtin_symbols'), include('numbers'), include('keywords'), include('punctuation'), include('operators'), include('valid_name'), ], 'root': [ include('statements'), # blocks: (r'\{|\}', Punctuation), # (r'\{', Punctuation, 'block'), (r'.', Text), ], # 'block': [ # include('statements'), # ('\{', Punctuation, '#push'), # ('\}', Punctuation, '#pop') # ], 'string_squote': [ (r'([^\'\\]|\\.)*\'', String, '#pop'), ], 'string_dquote': [ (r'([^"\\]|\\.)*"', String, '#pop'), ], } def analyse_text(text): if re.search(r'[a-z0-9_\])\s]<-(?!-)', text): return 0.11
SLexer
python
tensorflow__tensorflow
tensorflow/python/debug/wrappers/grpc_wrapper.py
{ "start": 5569, "end": 8102 }
class ____(GrpcDebugWrapperSession): """A tfdbg Session wrapper that can be used with TensorBoard Debugger Plugin. This wrapper is the same as `GrpcDebugWrapperSession`, except that it uses a predefined `watch_fn` that 1) uses `DebugIdentity` debug ops with the `gated_grpc` attribute set to `True` to allow the interactive enabling and disabling of tensor breakpoints. 2) watches all tensors in the graph. This saves the need for the user to define a `watch_fn`. """ def __init__(self, sess, grpc_debug_server_addresses, thread_name_filter=None, send_traceback_and_source_code=True): """Constructor of TensorBoardDebugWrapperSession. Args: sess: The `tf.compat.v1.Session` instance to be wrapped. grpc_debug_server_addresses: gRPC address(es) of debug server(s), as a `str` or a `list` of `str`s. E.g., "localhost:2333", "grpc://localhost:2333", ["192.168.0.7:2333", "192.168.0.8:2333"]. thread_name_filter: Optional filter for thread names. send_traceback_and_source_code: Whether traceback of graph elements and the source code are to be sent to the debug server(s). """ def _gated_grpc_watch_fn(fetches, feeds): del fetches, feeds # Unused. return framework.WatchOptions( debug_ops=["DebugIdentity(gated_grpc=true)"]) super().__init__( sess, grpc_debug_server_addresses, watch_fn=_gated_grpc_watch_fn, thread_name_filter=thread_name_filter) self._send_traceback_and_source_code = send_traceback_and_source_code # Keeps track of the latest version of Python graph object that has been # sent to the debug servers. self._sent_graph_version = -1 register_signal_handler() def run(self, fetches, feed_dict=None, options=None, run_metadata=None, callable_runner=None, callable_runner_args=None, callable_options=None): if self._send_traceback_and_source_code: self._sent_graph_version = publish_traceback( self._grpc_debug_server_urls, self.graph, feed_dict, fetches, self._sent_graph_version) return super().run( fetches, feed_dict=feed_dict, options=options, run_metadata=run_metadata, callable_runner=callable_runner, callable_runner_args=callable_runner_args, callable_options=callable_options)
TensorBoardDebugWrapperSession
python
matplotlib__matplotlib
galleries/examples/widgets/menu.py
{ "start": 258, "end": 400 }
class ____: fontsize: float = 14 labelcolor: ColorType = 'black' bgcolor: ColorType = 'yellow' alpha: float = 1.0
ItemProperties
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 2497, "end": 13684 }
class ____: _obj = None def __new__(cls): if NotConstant._obj is None: NotConstant._obj = super().__new__(cls) return NotConstant._obj def __repr__(self): return "<NOT CONSTANT>" not_a_constant = NotConstant() constant_value_not_set = object() def _type_to_itself(tp): return tp, tp # error messages when coercing from key[0] to key[1] coercion_error_dict = { # string related errors (unicode_type, bytes_type): "Cannot convert Unicode string to 'bytes' implicitly, encoding required.", (unicode_type, PyrexTypes.c_char_ptr_type): "Unicode objects only support coercion to Py_UNICODE*.", (unicode_type, PyrexTypes.c_const_char_ptr_type): "Unicode objects only support coercion to Py_UNICODE*.", (unicode_type, PyrexTypes.c_uchar_ptr_type): "Unicode objects only support coercion to Py_UNICODE*.", (unicode_type, PyrexTypes.c_const_uchar_ptr_type): "Unicode objects only support coercion to Py_UNICODE*.", (bytes_type, unicode_type): "Cannot convert 'bytes' object to str implicitly, decoding required", (bytes_type, PyrexTypes.c_py_unicode_ptr_type): "Cannot convert 'bytes' object to Py_UNICODE*, use 'str'.", (bytes_type, PyrexTypes.c_const_py_unicode_ptr_type): ( "Cannot convert 'bytes' object to Py_UNICODE*, use 'str'."), (PyrexTypes.c_char_ptr_type, unicode_type): "Cannot convert 'char*' to unicode implicitly, decoding required", (PyrexTypes.c_const_char_ptr_type, unicode_type): ( "Cannot convert 'char*' to unicode implicitly, decoding required"), (PyrexTypes.c_uchar_ptr_type, unicode_type): "Cannot convert 'char*' to unicode implicitly, decoding required", (PyrexTypes.c_const_uchar_ptr_type, unicode_type): ( "Cannot convert 'char*' to unicode implicitly, decoding required"), _type_to_itself(PyrexTypes.get_cy_pymutex_type()): ( "cython.pymutex cannot be copied"), _type_to_itself(PyrexTypes.get_cy_pythread_type_lock_type()): ( "cython.pythread_type_lock cannot be copied"), } def find_coercion_error(type_tuple, default, env): err = coercion_error_dict.get(type_tuple) if err is None: return default elif (env.directives['c_string_encoding'] and any(t in type_tuple for t in (PyrexTypes.c_char_ptr_type, PyrexTypes.c_uchar_ptr_type, PyrexTypes.c_const_char_ptr_type, PyrexTypes.c_const_uchar_ptr_type))): if type_tuple[1].is_pyobject: return default elif env.directives['c_string_encoding'] in ('ascii', 'utf8'): return default else: return "'%s' objects do not support coercion to C types with non-ascii or non-utf8 c_string_encoding" % type_tuple[0].name else: return err def default_str_type(env): return { 'bytes': bytes_type, 'bytearray': bytearray_type, 'str': unicode_type, 'unicode': unicode_type }.get(env.directives['c_string_type']) def check_negative_indices(*nodes): """ Raise a warning on nodes that are known to have negative numeric values. Used to find (potential) bugs inside of "wraparound=False" sections. """ for node in nodes: if node is None or not isinstance(node.constant_result, (int, float)): continue if node.constant_result < 0: warning(node.pos, "the result of using negative indices inside of " "code sections marked as 'wraparound=False' is " "undefined", level=1) def infer_sequence_item_type(env, seq_node, index_node=None, seq_type=None): if not seq_node.is_sequence_constructor: if seq_type is None: seq_type = seq_node.infer_type(env) if seq_type is tuple_type: # tuples are immutable => we can safely follow assignments if seq_node.cf_state and len(seq_node.cf_state) == 1: try: seq_node = seq_node.cf_state[0].rhs except AttributeError: pass if seq_node.is_sequence_constructor: if index_node is not None and index_node.has_constant_result(): # With a constant index, look up the item and infer its type. try: item = seq_node.args[index_node.constant_result] except (ValueError, TypeError, IndexError): pass else: return item.infer_type(env) if seq_node.is_sequence_constructor or seq_node.is_set_literal: # If we're lucky, all items have the same type (possibly with None). args_without_none = [item for item in seq_node.args if not item.is_none] has_none = len(args_without_none) < len(seq_node.args) item_types = { infer_sequence_item_type(env, item) if item.is_starred else item.infer_type(env) for item in args_without_none } if None in item_types: # Could not infer all starred types. return None # Unpack the Python types. Also avoids a mix of inferred C and Python. item_types = { item_type.equivalent_type if item_type.is_pyobject and item_type.equivalent_type else item_type for item_type in item_types } if len(item_types) == 1: item_type = item_types.pop() if has_none and not item_type.is_pyobject: # Must be a Python type to cover 'None'. item_type = item_type.equivalent_type # 'equivalent_type' may be None => cannot infer type elif not has_none and item_type in (unicode_type, bytes_type): # Infer special case of single character sequences as single character type. if all(arg.is_string_literal and arg.can_coerce_to_char_literal() for arg in args_without_none): item_type = PyrexTypes.c_py_ucs4_type if item_type is unicode_type else PyrexTypes.c_uchar_type return item_type return None def make_dedup_key(outer_type, item_nodes): """ Recursively generate a deduplication key from a sequence of values. Includes Cython node types to work around the fact that (1, 2.0) == (1.0, 2), for example. @param outer_type: The type of the outer container. @param item_nodes: A sequence of constant nodes that will be traversed recursively. @return: A tuple that can be used as a dict key for deduplication. """ item_keys = [ (py_object_type, None, type(None)) if node is None # For sequences and their "mult_factor", see TupleNode. else make_dedup_key(node.type, [node.mult_factor if node.is_literal else None] + node.args) if node.is_sequence_constructor else make_dedup_key(node.type, (node.start, node.stop, node.step)) if node.is_slice # For constants, look at the Python value type if we don't know the concrete Cython type. else (node.type, node.constant_result, type(node.constant_result) if node.type is py_object_type else None) if node.has_constant_result() else None # something we cannot handle => short-circuit below for node in item_nodes ] if None in item_keys: return None return outer_type, tuple(item_keys) # Returns a block of code to translate the exception, # plus a boolean indicating whether to check for Python exceptions. def get_exception_handler(exception_value): if exception_value is None: return "__Pyx_CppExn2PyErr();", False elif (exception_value.type == PyrexTypes.c_char_type and exception_value.value == '*'): return "__Pyx_CppExn2PyErr();", True elif exception_value.type.is_pyobject: return ( 'try { throw; } catch(const std::exception& exn) {' 'PyErr_SetString((PyObject*)%s, exn.what());' '} catch(...) { PyErr_SetNone((PyObject*)%s); }' % ( exception_value.entry.cname, exception_value.entry.cname), False) else: return ( '%s(); if (!PyErr_Occurred())' 'PyErr_SetString(PyExc_RuntimeError, ' '"Error converting c++ exception.");' % ( exception_value.entry.cname), False) def maybe_check_py_error(code, check_py_exception, pos, nogil): if check_py_exception: if nogil: code.globalstate.use_utility_code( UtilityCode.load_cached("ErrOccurredWithGIL", "Exceptions.c")) code.putln(code.error_goto_if("__Pyx_ErrOccurredWithGIL()", pos)) else: code.putln(code.error_goto_if("PyErr_Occurred()", pos)) def translate_cpp_exception(code, pos, inside, py_result, exception_value, nogil): raise_py_exception, check_py_exception = get_exception_handler(exception_value) code.putln("try {") code.putln("%s" % inside) if py_result: code.putln(code.error_goto_if_null(py_result, pos)) maybe_check_py_error(code, check_py_exception, pos, nogil) code.putln("} catch(...) {") if nogil: code.put_ensure_gil(declare_gilstate=True) code.putln(raise_py_exception) if nogil: code.put_release_ensured_gil() code.putln(code.error_goto(pos)) code.putln("}") def needs_cpp_exception_conversion(node): assert node.exception_check == "+" if node.exception_value is None: return True # exception_value can be a NameNode # (in which case it's used as a handler function and no conversion is needed) if node.exception_value.is_name: return False # or a CharNode with a value of "*" if isinstance(node.exception_value, CharNode) and node.exception_value.value == "*": return True # Most other const-nodes are disallowed after "+" by the parser return False # Used to handle the case where an lvalue expression and an overloaded assignment # both have an exception declaration. def translate_double_cpp_exception(code, pos, lhs_type, lhs_code, rhs_code, lhs_exc_val, assign_exc_val, nogil): handle_lhs_exc, lhc_check_py_exc = get_exception_handler(lhs_exc_val) handle_assignment_exc, assignment_check_py_exc = get_exception_handler(assign_exc_val) code.putln("try {") code.putln(lhs_type.declaration_code("__pyx_local_lvalue = %s;" % lhs_code)) maybe_check_py_error(code, lhc_check_py_exc, pos, nogil) code.putln("try {") code.putln("__pyx_local_lvalue = %s;" % rhs_code) maybe_check_py_error(code, assignment_check_py_exc, pos, nogil) # Catch any exception from the overloaded assignment. code.putln("} catch(...) {") if nogil: code.put_ensure_gil(declare_gilstate=True) code.putln(handle_assignment_exc) if nogil: code.put_release_ensured_gil() code.putln(code.error_goto(pos)) code.putln("}") # Catch any exception from evaluating lhs. code.putln("} catch(...) {") if nogil: code.put_ensure_gil(declare_gilstate=True) code.putln(handle_lhs_exc) if nogil: code.put_release_ensured_gil() code.putln(code.error_goto(pos)) code.putln('}')
NotConstant
python
plotly__plotly.py
plotly/graph_objs/treemap/_pathbar.py
{ "start": 233, "end": 5690 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "treemap" _path_str = "treemap.pathbar" _valid_props = {"edgeshape", "side", "textfont", "thickness", "visible"} @property def edgeshape(self): """ Determines which shape is used for edges between `barpath` labels. The 'edgeshape' property is an enumeration that may be specified as: - One of the following enumeration values: ['>', '<', '|', '/', '\\'] Returns ------- Any """ return self["edgeshape"] @edgeshape.setter def edgeshape(self, val): self["edgeshape"] = val @property def side(self): """ Determines on which side of the the treemap the `pathbar` should be presented. The 'side' property is an enumeration that may be specified as: - One of the following enumeration values: ['top', 'bottom'] Returns ------- Any """ return self["side"] @side.setter def side(self, val): self["side"] = val @property def textfont(self): """ Sets the font used inside `pathbar`. The 'textfont' property is an instance of Textfont that may be specified as: - An instance of :class:`plotly.graph_objs.treemap.pathbar.Textfont` - A dict of string/value properties that will be passed to the Textfont constructor Returns ------- plotly.graph_objs.treemap.pathbar.Textfont """ return self["textfont"] @textfont.setter def textfont(self, val): self["textfont"] = val @property def thickness(self): """ Sets the thickness of `pathbar` (in px). If not specified the `pathbar.textfont.size` is used with 3 pixles extra padding on each side. The 'thickness' property is a number and may be specified as: - An int or float in the interval [12, inf] Returns ------- int|float """ return self["thickness"] @thickness.setter def thickness(self, val): self["thickness"] = val @property def visible(self): """ Determines if the path bar is drawn i.e. outside the trace `domain` and with one pixel gap. The 'visible' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["visible"] @visible.setter def visible(self, val): self["visible"] = val @property def _prop_descriptions(self): return """\ edgeshape Determines which shape is used for edges between `barpath` labels. side Determines on which side of the the treemap the `pathbar` should be presented. textfont Sets the font used inside `pathbar`. thickness Sets the thickness of `pathbar` (in px). If not specified the `pathbar.textfont.size` is used with 3 pixles extra padding on each side. visible Determines if the path bar is drawn i.e. outside the trace `domain` and with one pixel gap. """ def __init__( self, arg=None, edgeshape=None, side=None, textfont=None, thickness=None, visible=None, **kwargs, ): """ Construct a new Pathbar object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.treemap.Pathbar` edgeshape Determines which shape is used for edges between `barpath` labels. side Determines on which side of the the treemap the `pathbar` should be presented. textfont Sets the font used inside `pathbar`. thickness Sets the thickness of `pathbar` (in px). If not specified the `pathbar.textfont.size` is used with 3 pixles extra padding on each side. visible Determines if the path bar is drawn i.e. outside the trace `domain` and with one pixel gap. Returns ------- Pathbar """ super().__init__("pathbar") if "_parent" in kwargs: self._parent = kwargs["_parent"] return 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.Pathbar constructor must be a dict or an instance of :class:`plotly.graph_objs.treemap.Pathbar`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("edgeshape", arg, edgeshape) self._set_property("side", arg, side) self._set_property("textfont", arg, textfont) self._set_property("thickness", arg, thickness) self._set_property("visible", arg, visible) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Pathbar
python
coleifer__peewee
tests/shortcuts.py
{ "start": 1588, "end": 1691 }
class ____(TestModel): host = ForeignKeyField(Host, backref='services') name = TextField()
Service
python
google__jax
jax/_src/numpy/index_tricks.py
{ "start": 1744, "end": 3113 }
class ____: """Return dense multi-dimensional "meshgrid". LAX-backend implementation of :obj:`numpy.mgrid`. This is a convenience wrapper for functionality provided by :func:`jax.numpy.meshgrid` with ``sparse=False``. See Also: jnp.ogrid: open/sparse version of jnp.mgrid Examples: Pass ``[start:stop:step]`` to generate values similar to :func:`jax.numpy.arange`: >>> jnp.mgrid[0:4:1] Array([0, 1, 2, 3], dtype=int32) Passing an imaginary step generates values similar to :func:`jax.numpy.linspace`: >>> jnp.mgrid[0:1:4j] Array([0. , 0.33333334, 0.6666667 , 1. ], dtype=float32) Multiple slices can be used to create broadcasted grids of indices: >>> jnp.mgrid[:2, :3] Array([[[0, 0, 0], [1, 1, 1]], [[0, 1, 2], [0, 1, 2]]], dtype=int32) """ def __getitem__(self, key: slice | tuple[slice, ...]) -> Array: if isinstance(key, slice): return _make_1d_grid_from_slice(key, op_name="mgrid") output: Iterable[Array] = (_make_1d_grid_from_slice(k, op_name="mgrid") for k in key) with config.numpy_dtype_promotion('standard'): output = promote_dtypes(*output) output_arr = meshgrid(*output, indexing='ij', sparse=False) if len(output_arr) == 0: return arange(0) return stack(output_arr, 0) mgrid = export(_Mgrid())
_Mgrid
python
ray-project__ray
python/ray/llm/_internal/batch/processor/vllm_engine_proc.py
{ "start": 1424, "end": 1686 }
class ____(BaseModelExtended): model_config = ConfigDict(extra="allow") CPU: Optional[int] = Field(default=1, description="The number of CPUs per bundle.") GPU: Optional[int] = Field(default=1, description="The number of GPUs per bundle.")
BundleSchema
python
huggingface__transformers
src/transformers/models/mlcd/modular_mlcd.py
{ "start": 12510, "end": 14631 }
class ____(CLIPEncoder): """ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a [`MLCDEncoderLayer`]. Args: config: MLCDVisionConfig """ def __init__(self, config: MLCDVisionConfig): """Overwrite dummy `MLCDConfig` to `MLCDVisionConfig`.""" super().__init__(config) def forward( self, inputs_embeds: torch.FloatTensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: Optional[torch.Tensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple, BaseModelOutput]: r""" Args: inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. position_embeddings (`tuple[torch.Tensor, torch.Tensor]`): A tuple of two tensors, each of shape `(batch, seq_len, embed_dim)`. Represents absolute positional embeddings for the query and key in the attention mechanism. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) """ hidden_states = inputs_embeds for encoder_layer in self.layers: hidden_states = encoder_layer( hidden_states, position_embeddings, attention_mask, **kwargs, ) return BaseModelOutput( last_hidden_state=hidden_states, ) @auto_docstring
MLCDEncoder
python
huggingface__transformers
src/transformers/models/jetmoe/modular_jetmoe.py
{ "start": 7998, "end": 11543 }
class ____(nn.Module): """ A Sparsely gated mixture of attention layer with pairs of query- and output-projections as experts. Args: config: Configuration object with model hyperparameters. """ def __init__(self, config: JetMoeConfig): super().__init__() self.num_experts = config.num_local_experts self.input_size = config.hidden_size self.hidden_size = config.kv_channels * config.num_key_value_heads self.top_k = config.num_experts_per_tok self.bias = torch.nn.Parameter(torch.empty(self.input_size)) self.input_linear = JetMoeParallelExperts(self.num_experts, self.input_size, self.hidden_size) self.output_linear = JetMoeParallelExperts(self.num_experts, self.hidden_size, self.input_size) self.router = JetMoeTopKGating( input_size=self.input_size, num_experts=self.num_experts, top_k=self.top_k, ) def map(self, layer_input): """ Map inputs to attention experts according to routing decision and compute query projection inside each experts. """ # Compute gating topology bsz, length, emb_size = layer_input.size() layer_input = layer_input.reshape(-1, emb_size) # [bsz * length, emb_size] index_sorted_experts, batch_index, batch_gates, expert_size, router_logits = self.router(layer_input) topo_info = (index_sorted_experts, batch_index, batch_gates, expert_size) # Group inputs according to topology and compute query projection expert_inputs = layer_input[batch_index] # [bsz * length * top_k, emb_size] expert_outputs = self.input_linear(expert_inputs, expert_size) # [bsz * length * top_k, hidden_size] # Ungroup queries back to original order zeros = torch.zeros( (bsz * length * self.top_k, self.hidden_size), dtype=expert_outputs.dtype, device=expert_outputs.device ) layer_output = zeros.index_add(0, index_sorted_experts, expert_outputs) layer_output = layer_output.view(bsz, length, self.top_k, -1) # [bsz, length, top_k, hidden_size] return layer_output, router_logits, topo_info def reduce(self, layer_input, topo_info): """ Compute output projection inside each attention experts and merge the outputs of different experts. """ bsz, length, k, hidden_size = layer_input.size() layer_input = layer_input.reshape(-1, hidden_size) # [bsz * length * k, hidden_size] index_sorted_experts, batch_index, batch_gates, expert_size = topo_info # Group inputs according to topology and compute output projection expert_inputs = layer_input[index_sorted_experts] # [bsz * length * top_k, hidden_size] expert_outputs = self.output_linear(expert_inputs, expert_size) # [bsz * length * top_k, emb_size] # Apply gates to attention expert outputs expert_outputs = expert_outputs * batch_gates[:, None] # Ungroup and merge outputs to original order zeros = torch.zeros((bsz * length, self.input_size), dtype=expert_outputs.dtype, device=expert_outputs.device) layer_output = zeros.index_add(0, batch_index, expert_outputs) layer_output = layer_output.view(bsz, length, self.input_size) layer_output = layer_output + self.bias return layer_output def forward(self, layer_input): raise NotImplementedError("This module doesn't support call and forward.")
JetMoeMoA
python
pytorch__pytorch
torch/_numpy/_dtypes.py
{ "start": 1792, "end": 1892 }
class ____(unsignedinteger): name = "uint8" typecode = "B" torch_dtype = torch.uint8
uint8
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 387963, "end": 391371 }
class ____(sgqlc.types.Interface): """Represents a comment.""" __schema__ = github_schema __field_names__ = ( "author", "author_association", "body", "body_html", "body_text", "created_at", "created_via_email", "editor", "id", "includes_created_edit", "last_edited_at", "published_at", "updated_at", "user_content_edits", "viewer_did_author", ) author = sgqlc.types.Field(Actor, graphql_name="author") """The actor who authored the comment.""" author_association = sgqlc.types.Field(sgqlc.types.non_null(CommentAuthorAssociation), graphql_name="authorAssociation") """Author's association with the subject of the comment.""" body = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="body") """The body as Markdown.""" body_html = sgqlc.types.Field(sgqlc.types.non_null(HTML), graphql_name="bodyHTML") """The body rendered to HTML.""" body_text = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="bodyText") """The body rendered to text.""" created_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="createdAt") """Identifies the date and time when the object was created.""" created_via_email = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="createdViaEmail") """Check if this comment was created via an email reply.""" editor = sgqlc.types.Field(Actor, graphql_name="editor") """The actor who edited the comment.""" id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="id") includes_created_edit = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="includesCreatedEdit") """Check if this comment was edited and includes an edit with the creation data """ last_edited_at = sgqlc.types.Field(DateTime, graphql_name="lastEditedAt") """The moment the editor made the last edit""" published_at = sgqlc.types.Field(DateTime, graphql_name="publishedAt") """Identifies when the comment was published at.""" updated_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="updatedAt") """Identifies the date and time when the object was last updated.""" user_content_edits = sgqlc.types.Field( "UserContentEditConnection", graphql_name="userContentEdits", args=sgqlc.types.ArgDict( ( ("after", sgqlc.types.Arg(String, graphql_name="after", default=None)), ("before", sgqlc.types.Arg(String, graphql_name="before", default=None)), ("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)), ("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)), ) ), ) """A list of edits to this content. Arguments: * `after` (`String`): Returns the elements in the list that come after the specified cursor. * `before` (`String`): Returns the elements in the list that come before the specified cursor. * `first` (`Int`): Returns the first _n_ elements from the list. * `last` (`Int`): Returns the last _n_ elements from the list. """ viewer_did_author = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="viewerDidAuthor") """Did the viewer author this comment."""
Comment
python
django__django
tests/generic_views/views.py
{ "start": 5897, "end": 6049 }
class ____(generic.edit.ModelFormMixin): fields = "__all__" def get_queryset(self): return Author.objects.all()
AuthorGetQuerySetFormView
python
falconry__falcon
tests/asgi/test_hello_asgi.py
{ "start": 4758, "end": 12178 }
class ____: def test_env_headers_list_of_tuples(self): env = testing.create_environ(headers=[('User-Agent', 'Falcon-Test')]) assert env['HTTP_USER_AGENT'] == 'Falcon-Test' def test_root_route(self, client): doc = {'message': 'Hello world!'} resource = testing.SimpleTestResourceAsync(json=doc) client.app.add_route('/', resource) result = client.simulate_get() assert result.json == doc def test_no_route(self, client): result = client.simulate_get('/seenoevil') assert result.status_code == 404 @pytest.mark.parametrize( 'path,resource,get_body', [ ('/body', HelloResource('body'), lambda r: r.text.encode('utf-8')), ('/bytes', HelloResource('body, bytes'), lambda r: r.text), ('/data', HelloResource('data'), lambda r: r.data), ], ) def test_body(self, client, path, resource, get_body): client.app.add_route(path, resource) result = client.simulate_get(path) resp = resource.resp content_length = int(result.headers['content-length']) assert content_length == len(resource.sample_utf8) assert result.status == resource.sample_status assert resp.status == resource.sample_status assert get_body(resp) == resource.sample_utf8 assert result.content == resource.sample_utf8 def test_no_body_on_head(self, client): resource = HelloResource('body') client.app.add_route('/body', resource) result = client.simulate_head('/body') assert not result.content assert result.status_code == 200 assert resource.called assert result.headers['content-length'] == str(len(HelloResource.sample_utf8)) def test_stream_chunked(self, client): resource = HelloResource('stream') client.app.add_route('/chunked-stream', resource) result = client.simulate_get('/chunked-stream') assert result.content == resource.sample_utf8 assert 'content-length' not in result.headers def test_stream_known_len(self, client): resource = HelloResource('stream, stream_len') client.app.add_route('/stream', resource) result = client.simulate_get('/stream') assert resource.called expected_len = int(resource.resp.content_length) actual_len = int(result.headers['content-length']) assert actual_len == expected_len assert len(result.content) == expected_len assert result.content == resource.sample_utf8 def test_filelike(self, client): resource = HelloResource('stream, stream_len, filelike') client.app.add_route('/filelike', resource) result = client.simulate_get('/filelike') assert resource.called expected_len = int(resource.resp.content_length) actual_len = int(result.headers['content-length']) assert actual_len == expected_len assert len(result.content) == expected_len result = client.simulate_get('/filelike') assert resource.called expected_len = int(resource.resp.content_length) actual_len = int(result.headers['content-length']) assert actual_len == expected_len assert len(result.content) == expected_len def test_genfunc_error(self, client): resource = HelloResource('stream, stream_len, stream_genfunc') client.app.add_route('/filelike', resource) with pytest.raises(TypeError): client.simulate_get('/filelike') def test_nongenfunc_error(self, client): resource = HelloResource('stream, stream_len, stream_nongenfunc') client.app.add_route('/filelike', resource) with pytest.raises(TypeError): client.simulate_get('/filelike') @pytest.mark.parametrize( 'stream_factory,assert_closed', [ (DataReader, True), # Implements close() (DataReaderWithoutClose, False), ], ) def test_filelike_closing(self, client, stream_factory, assert_closed): resource = ClosingFilelikeHelloResource(stream_factory) client.app.add_route('/filelike-closing', resource) result = client.simulate_get('/filelike-closing') assert resource.called expected_len = int(resource.resp.content_length) actual_len = int(result.headers['content-length']) assert actual_len == expected_len assert len(result.content) == expected_len if assert_closed: assert resource.stream.close_called @pytest.mark.skipif(aiofiles is None, reason='aiofiles is required for this test') def test_filelike_closing_aiofiles(self, client): resource = AIOFilesHelloResource() try: client.app.add_route('/filelike-closing', resource) result = client.simulate_get('/filelike-closing') assert result.status_code == 200 assert 'content-length' not in result.headers assert result.content == resource.sample_utf8 assert resource.aiofiles_closed finally: resource.cleanup() def test_filelike_using_helper(self, client): resource = HelloResource('stream, stream_len, filelike, use_helper') client.app.add_route('/filelike-helper', resource) result = client.simulate_get('/filelike-helper') assert resource.called expected_len = int(resource.resp.content_length) actual_len = int(result.headers['content-length']) assert actual_len == expected_len assert len(result.content) == expected_len @pytest.mark.parametrize( 'value,divisor,text,error', [ (10, 3, '3\n3\n3\n1\n', None), (10, 7, '7\n3\n', None), (10, 17, '10\n', None), (20, 0, '', ZeroDivisionError), ], ) def test_closing_stream(self, client, value, divisor, text, error): resource = ClosingStreamResource() client.app.add_route('/stream', resource) if error: with pytest.raises(error): client.simulate_get( '/stream', params={'value': value, 'divisor': divisor} ) else: result = client.simulate_get( '/stream', params={'value': value, 'divisor': divisor} ) assert result.status_code == 200 assert result.text == text assert resource.stream.closed def test_status_not_set(self, client): client.app.add_route('/nostatus', NoStatusResource()) result = client.simulate_get('/nostatus') assert not result.content assert result.status_code == 200 def test_coroutine_required(self, client, util): with util.disable_asgi_non_coroutine_wrapping(): with pytest.raises(TypeError) as exinfo: client.app.add_route('/', PartialCoroutineResource()) assert 'responder must be a non-blocking async coroutine' in str( exinfo.value ) def test_noncoroutine_required(self): wsgi_app = falcon.App() with pytest.raises(TypeError) as exinfo: wsgi_app.add_route('/', PartialCoroutineResource()) assert 'responder must be a regular synchronous method' in str(exinfo.value)
TestHelloWorld
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_boolean_trap/FBT.py
{ "start": 3312, "end": 3435 }
class ____(BaseSettings): foo: bool = Field(True, exclude=True) # https://github.com/astral-sh/ruff/issues/14202
Settings
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeVarDefaultClass3.py
{ "start": 1481, "end": 1642 }
class ____[T1 = str]: # This should generate an error because T2 depends on T1, which # is defined in an outer scope. class ClassL[T2 = T1]: ...
ClassK
python
PrefectHQ__prefect
src/prefect/settings/models/runner.py
{ "start": 1146, "end": 1991 }
class ____(PrefectBaseSettings): """ Settings for controlling runner behavior """ model_config: ClassVar[SettingsConfigDict] = build_settings_config(("runner",)) process_limit: int = Field( default=5, description="Maximum number of processes a runner will execute in parallel.", ) poll_frequency: int = Field( default=10, description="Number of seconds a runner should wait between queries for scheduled work.", ) heartbeat_frequency: Optional[int] = Field( default=None, description="Number of seconds a runner should wait between heartbeats for flow runs.", ge=30, ) server: RunnerServerSettings = Field( default_factory=RunnerServerSettings, description="Settings for controlling runner server behavior", )
RunnerSettings
python
spack__spack
lib/spack/spack/vendor/jinja2/ext.py
{ "start": 21539, "end": 21881 }
class ____(Extension): def __init__(self, environment: Environment) -> None: super().__init__(environment) warnings.warn( "The 'with' extension is deprecated and will be removed in" " Jinja 3.1. This is built in now.", DeprecationWarning, stacklevel=3, )
WithExtension
python
doocs__leetcode
solution/1400-1499/1486.XOR Operation in an Array/Solution.py
{ "start": 0, "end": 135 }
class ____: def xorOperation(self, n: int, start: int) -> int: return reduce(xor, ((start + 2 * i) for i in range(n)))
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-outbrain-amplify/source_outbrain_amplify/source.py
{ "start": 46963, "end": 47302 }
class ____(OutbrainAmplifyStream, ABC): state_checkpoint_interval = None @property def cursor_field(self) -> str: return [] def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]) -> Mapping[str, Any]: return {} # Source
IncrementalOutbrainAmplifyStream
python
doocs__leetcode
solution/1700-1799/1769.Minimum Number of Operations to Move All Balls to Each Box/Solution2.py
{ "start": 0, "end": 444 }
class ____: def minOperations(self, boxes: str) -> List[int]: n = len(boxes) ans = [0] * n cnt = 0 for i in range(1, n): if boxes[i - 1] == '1': cnt += 1 ans[i] = ans[i - 1] + cnt cnt = s = 0 for i in range(n - 2, -1, -1): if boxes[i + 1] == '1': cnt += 1 s += cnt ans[i] += s return ans
Solution
python
django__django
tests/admin_widgets/test_autocomplete_widget.py
{ "start": 769, "end": 1020 }
class ____(forms.Form): band = ModelChoiceField( queryset=Album.objects.all(), widget=AutocompleteSelect( Album._meta.get_field("band").remote_field, admin.site ), required=False, )
NotRequiredBandForm
python
scipy__scipy
scipy/optimize/tests/test_least_squares.py
{ "start": 29812, "end": 30209 }
class ____(BaseMixin, BoundsMixin, SparseMixin, LossFunctionMixin): method = 'trf' def test_lsmr_regularization(self): p = BroydenTridiagonal() for regularize in [True, False]: res = least_squares(p.fun, p.x0, p.jac, method='trf', tr_options={'regularize': regularize}) assert_allclose(res.cost, 0, atol=1e-20)
TestTRF
python
encode__django-rest-framework
tests/test_model_serializer.py
{ "start": 13829, "end": 15375 }
class ____(TestCase): def test_duration_field(self): class DurationFieldModel(models.Model): """ A model that defines DurationField. """ duration_field = models.DurationField() class TestSerializer(serializers.ModelSerializer): class Meta: model = DurationFieldModel fields = '__all__' expected = dedent(""" TestSerializer(): id = IntegerField(label='ID', read_only=True) duration_field = DurationField() """) self.assertEqual(repr(TestSerializer()), expected) def test_duration_field_with_validators(self): class ValidatedDurationFieldModel(models.Model): """ A model that defines DurationField with validators. """ duration_field = models.DurationField( validators=[MinValueValidator(datetime.timedelta(days=1)), MaxValueValidator(datetime.timedelta(days=3))] ) class TestSerializer(serializers.ModelSerializer): class Meta: model = ValidatedDurationFieldModel fields = '__all__' expected = dedent(""" TestSerializer(): id = IntegerField(label='ID', read_only=True) duration_field = DurationField(max_value=datetime.timedelta(days=3), min_value=datetime.timedelta(days=1)) """) self.assertEqual(repr(TestSerializer()), expected)
TestDurationFieldMapping
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclassSlots1.py
{ "start": 461, "end": 651 }
class ____: x: int __slots__ = ("x",) def __init__(self): self.x = 3 # This should generate an error because "y" is not in slots. self.y = 3 @dataclass
C
python
google__pytype
pytype/typegraph/typegraph_serializer.py
{ "start": 1305, "end": 1410 }
class ____: where: CFGNodeId source_sets: list[list[BindingId]] @dataclasses.dataclass
SerializedOrigin
python
instagram__MonkeyType
tests/test_stubs.py
{ "start": 34097, "end": 34308 }
class ____: @staticmethod def has_annos(a: int, b) -> int: return 0 @classmethod def a_class_method(cls): pass def an_instance_method(self): pass
UpdateSignatureHelper
python
kamyu104__LeetCode-Solutions
Python/choose-edges-to-maximize-score-in-a-tree.py
{ "start": 54, "end": 1120 }
class ____(object): def maxScore(self, edges): """ :type edges: List[List[int]] :rtype: int """ def iter_dfs(): result = [(0, 0) for _ in xrange(len(adj))] stk = [(1, 0)] while stk: step, u = stk.pop() if step == 1: if not adj[u]: continue stk.append((2, u)) for v, _ in adj[u]: stk.append((1, v)) elif step == 2: without_u = sum(max(result[v]) for v, w in adj[u]) with_u = max(without_u-max(result[v])+(result[v][1]+w) for v, w in adj[u]) result[u] = (with_u, without_u) return max(result[0]) adj = [[] for _ in xrange(len(edges))] for i, (p, w) in enumerate(edges): if i == 0: continue adj[p].append((i, w)) return iter_dfs() # Time: O(n) # Space: O(n) # dfs, tree dp
Solution
python
pyqtgraph__pyqtgraph
pyqtgraph/graphicsItems/PColorMeshItem.py
{ "start": 1931, "end": 22464 }
class ____(GraphicsObject): """ **Bases:** :class:`GraphicsObject <pyqtgraph.GraphicsObject>` """ sigLevelsChanged = QtCore.Signal(object) # emits tuple with levels (low,high) when color levels are changed. def __init__(self, *args, **kwargs): """ Create a pseudocolor plot with convex polygons. Call signature: ``PColorMeshItem([x, y,] z, **kwargs)`` x and y can be used to specify the corners of the quadrilaterals. z must be used to specified to color of the quadrilaterals. Parameters ---------- x, y : np.ndarray, optional, default None 2D array containing the coordinates of the polygons z : np.ndarray 2D array containing the value which will be mapped into the polygons colors. If x and y is None, the polygons will be displaced on a grid otherwise x and y will be used as polygons vertices coordinates as:: (x[i+1, j], y[i+1, j]) (x[i+1, j+1], y[i+1, j+1]) +---------+ | z[i, j] | +---------+ (x[i, j], y[i, j]) (x[i, j+1], y[i, j+1]) "ASCII from: <https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.pcolormesh.html>". colorMap : pyqtgraph.ColorMap Colormap used to map the z value to colors. default ``pyqtgraph.colormap.get('viridis')`` levels: tuple, optional, default None Sets the minimum and maximum values to be represented by the colormap (min, max). Values outside this range will be clipped to the colors representing min or max. ``None`` disables the limits, meaning that the colormap will autoscale the next time ``setData()`` is called with new data. enableAutoLevels: bool, optional, default True Causes the colormap levels to autoscale whenever ``setData()`` is called. It is possible to override this value on a per-change-basis by using the ``autoLevels`` keyword argument when calling ``setData()``. If ``enableAutoLevels==False`` and ``levels==None``, autoscaling will be performed once when the first z data is supplied. edgecolors : dict, optional The color of the edges of the polygons. Default None means no edges. Only cosmetic pens are supported. The dict may contains any arguments accepted by :func:`mkColor() <pyqtgraph.mkColor>`. Example: ``mkPen(color='w', width=2)`` antialiasing : bool, default False Whether to draw edgelines with antialiasing. Note that if edgecolors is None, antialiasing is always False. """ GraphicsObject.__init__(self) self.qpicture = None ## rendered picture for display self.x = None self.y = None self.z = None self._dataBounds = None self.glstate = None self.edgecolors = kwargs.get('edgecolors', None) if self.edgecolors is not None: self.edgecolors = fn.mkPen(self.edgecolors) # force the pen to be cosmetic. see discussion in # https://github.com/pyqtgraph/pyqtgraph/pull/2586 self.edgecolors.setCosmetic(True) self.antialiasing = kwargs.get('antialiasing', False) self.levels = kwargs.get('levels', None) self._defaultAutoLevels = kwargs.get('enableAutoLevels', True) if 'colorMap' in kwargs: cmap = kwargs.get('colorMap') if not isinstance(cmap, colormap.ColorMap): raise ValueError('colorMap argument must be a ColorMap instance') self.cmap = cmap else: self.cmap = colormap.get('viridis') self.lut_qcolor = self.cmap.getLookupTable(nPts=256, mode=self.cmap.QCOLOR) self.quads = QuadInstances() # If some data have been sent we directly display it if len(args)>0: self.setData(*args) def _prepareData(self, args) -> DirtyFlag: """ Check the shape of the data. Return a set of 2d array x, y, z ready to be used to draw the picture. """ dirtyFlags = DirtyFlag.XY | DirtyFlag.Z | DirtyFlag.DIM # User didn't specified data if len(args)==0: self.x = None self.y = None self.z = None self._dataBounds = None # User only specified z elif len(args)==1: # If x and y is None, the polygons will be displaced on a grid x = np.arange(0, args[0].shape[0]+1, 1) y = np.arange(0, args[0].shape[1]+1, 1) self.x, self.y = np.meshgrid(x, y, indexing='ij') self.z = args[0] self._dataBounds = ((x[0], x[-1]), (y[0], y[-1])) # User specified x, y, z elif len(args)==3: # specifying None explicitly means to retain the existing value if (x := args[0]) is None: x = self.x if (y := args[1]) is None: y = self.y if (z := args[2]) is None: z = self.z if args[0] is None and args[1] is None: dirtyFlags &= ~DirtyFlag.XY if args[2] is None: dirtyFlags &= ~DirtyFlag.Z if self.z is not None and z.shape == self.z.shape: dirtyFlags &= ~DirtyFlag.DIM # Shape checking xy_shape = (z.shape[0]+1, z.shape[1]+1) if x.shape != xy_shape: raise ValueError('The dimension of x should be one greater than the one of z') if y.shape != xy_shape: raise ValueError('The dimension of y should be one greater than the one of z') self.x = x self.y = y self.z = z xmn, xmx = np.min(self.x), np.max(self.x) ymn, ymx = np.min(self.y), np.max(self.y) self._dataBounds = ((xmn, xmx), (ymn, ymx)) else: raise ValueError('Data must been sent as (z) or (x, y, z)') return dirtyFlags def setData(self, *args, **kwargs): """ Set the data to be drawn. Parameters ---------- x, y : np.ndarray, optional, default None 2D array containing the coordinates of the polygons z : np.ndarray 2D array containing the value which will be mapped into the polygons colors. If x and y is None, the polygons will be displaced on a grid otherwise x and y will be used as polygons vertices coordinates as:: (x[i+1, j], y[i+1, j]) (x[i+1, j+1], y[i+1, j+1]) +---------+ | z[i, j] | +---------+ (x[i, j], y[i, j]) (x[i, j+1], y[i, j+1]) "ASCII from: <https://matplotlib.org/3.2.1/api/_as_gen/ matplotlib.pyplot.pcolormesh.html>". autoLevels: bool, optional If set, overrides the value of ``enableAutoLevels`` """ old_bounds = self._dataBounds dirtyFlags = self._prepareData(args) boundsChanged = old_bounds != self._dataBounds self._rerender( autoLevels=kwargs.get('autoLevels', self._defaultAutoLevels) ) if boundsChanged: self.prepareGeometryChange() self.informViewBoundsChanged() if self.glstate is not None: self.glstate.dataChange(dirtyFlags) self.update() def _rerender(self, *, autoLevels): self.qpicture = None if self.z is not None and np.any(np.isfinite(self.z)): if (self.levels is None) or autoLevels: # Autoscale colormap z_min = np.nanmin(self.z) z_max = np.nanmax(self.z) self.setLevels( (z_min, z_max), update=False) def _drawPicture(self) -> QtGui.QPicture: # on entry, the following members are all valid: x, y, z, levels # this function does not alter any state (besides using self.quads) picture = QtGui.QPicture() painter = QtGui.QPainter(picture) # We set the pen of all polygons once if self.edgecolors is None: painter.setPen(QtCore.Qt.PenStyle.NoPen) else: painter.setPen(self.edgecolors) if self.antialiasing: painter.setRenderHint(QtGui.QPainter.RenderHint.Antialiasing) z_invalid = np.isnan(self.z) skip_nans = np.any(z_invalid) if skip_nans: # note: flattens array valid_z = self.z[~z_invalid] if len(valid_z) == 0: # nothing to draw => return painter.end() return picture else: valid_z = self.z ## Prepare colormap # First we get the LookupTable lut = self.lut_qcolor # Second we associate each z value, that we normalize, to the lut scale = len(lut) - 1 lo, hi = self.levels[0], self.levels[1] rng = hi - lo if rng == 0: rng = 1 norm = fn.rescaleData(valid_z, scale / rng, lo, dtype=int, clip=(0, len(lut)-1)) if Qt.QT_LIB.startswith('PyQt'): drawConvexPolygon = lambda x : painter.drawConvexPolygon(*x) else: drawConvexPolygon = painter.drawConvexPolygon self.quads.resize(self.z.shape[0], self.z.shape[1]) memory = self.quads.ndarray() memory[..., 0] = self.x.ravel() memory[..., 1] = self.y.ravel() polys = self.quads.instances() if skip_nans: polys = polys[(~z_invalid).flat] # group indices of same coloridx together color_indices, counts = np.unique(norm, return_counts=True) # note: returns flattened array sorted_indices = np.argsort(norm, axis=None) offset = 0 for coloridx, cnt in zip(color_indices, counts): indices = sorted_indices[offset:offset+cnt] offset += cnt painter.setBrush(lut[coloridx]) for idx in indices: drawConvexPolygon(polys[idx]) painter.end() return picture def setLevels(self, levels, update=True): """ Sets color-scaling levels for the mesh. Parameters ---------- levels: tuple ``(low, high)`` sets the range for which values can be represented in the colormap. update: bool, optional Controls if mesh immediately updates to reflect the new color levels. """ self.levels = levels self.sigLevelsChanged.emit(levels) if update: self._rerender(autoLevels=False) self.update() def getLevels(self): """ Returns a tuple containing the current level settings. See :func:`~setLevels`. The format is ``(low, high)``. """ return self.levels def setLookupTable(self, lut, update=True): self.cmap = None # invalidate since no longer consistent with lut self.lut_qcolor = lut[:] if self.glstate is not None: self.glstate.dataChange(DirtyFlag.LUT) if update: self._rerender(autoLevels=False) self.update() def getColorMap(self): return self.cmap def setColorMap(self, cmap): self.setLookupTable(cmap.getLookupTable(nPts=256, mode=cmap.QCOLOR), update=True) self.cmap = cmap def enableAutoLevels(self): self._defaultAutoLevels = True def disableAutoLevels(self): self._defaultAutoLevels = False def paint(self, painter, opt, widget): if self.z is None: return if ( isinstance(widget, OpenGLHelpers.GraphicsViewGLWidget) and self.cmap is not None # don't support setting colormap by setLookupTable ): if self.glstate is None: self.glstate = OpenGLState(widget) painter.beginNativePainting() try: self.paintGL(widget) finally: painter.endNativePainting() if ( self.edgecolors is not None and self.edgecolors.style() != QtCore.Qt.PenStyle.NoPen ): painter.setPen(self.edgecolors) if self.antialiasing: painter.setRenderHint(QtGui.QPainter.RenderHint.Antialiasing) for idx in range(self.x.shape[0]): painter.drawPolyline(fn.arrayToQPolygonF(self.x[idx, :], self.y[idx, :])) for idx in range(self.x.shape[1]): painter.drawPolyline(fn.arrayToQPolygonF(self.x[:, idx], self.y[:, idx])) return if self.qpicture is None: self.qpicture = self._drawPicture() painter.drawPicture(0, 0, self.qpicture) def width(self): if self._dataBounds is None: return 0 bounds = self._dataBounds[0] return bounds[1]-bounds[0] def height(self): if self._dataBounds is None: return 0 bounds = self._dataBounds[1] return bounds[1]-bounds[0] def dataBounds(self, ax, frac=1.0, orthoRange=None): if self._dataBounds is None: return (None, None) return self._dataBounds[ax] def pixelPadding(self): # pen is known to be cosmetic pen = self.edgecolors no_pen = (pen is None) or (pen.style() == QtCore.Qt.PenStyle.NoPen) return 0 if no_pen else (pen.widthF() or 1) * 0.5 def boundingRect(self): xmn, xmx = self.dataBounds(ax=0) if xmn is None or xmx is None: return QtCore.QRectF() ymn, ymx = self.dataBounds(ax=1) if ymn is None or ymx is None: return QtCore.QRectF() px = py = 0 pxPad = self.pixelPadding() if pxPad > 0: # determine length of pixel in local x, y directions px, py = self.pixelVectors() px = 0 if px is None else px.length() py = 0 if py is None else py.length() # return bounds expanded by pixel size px *= pxPad py *= pxPad return QtCore.QRectF(xmn-px, ymn-py, (2*px)+xmx-xmn, (2*py)+ymx-ymn) def paintGL(self, widget): if (view := self.getViewBox()) is None: return X, Y, Z = self.x, self.y, self.z glstate = self.glstate glstate.setup(widget.context()) glfn = widget.getFunctions() program = widget.retrieveProgram("PColorMeshItem") # OpenGL only sees the float32 version of our data, and this may cause # precision issues. To mitigate this, we shift the origin of our data # to the center of its bounds. # Note that xc, yc are double precision Python floats. Subtracting them # from the x, y ndarrays will automatically upcast the latter to double # precision. if glstate.render_cache is None: origin = None dirty_bits = DirtyFlag.XY | DirtyFlag.Z | DirtyFlag.LUT | DirtyFlag.DIM else: origin, dirty_bits = glstate.render_cache if origin is None or DirtyFlag.XY in dirty_bits: # the origin point is calculated once per data change. # once the data is uploaded, the origin point is fixed. center = self.boundingRect().center() origin = center.x(), center.y() proj = QtGui.QMatrix4x4() proj.ortho(widget.rect()) tr = self.sceneTransform() xc, yc = origin tr.translate(xc, yc) mvp = proj * QtGui.QMatrix4x4(tr) if glstate.flat_shading: vtx_array_shape = X.shape else: vtx_array_shape = Z.shape + (4,) num_vtx_mesh = np.prod(vtx_array_shape) num_ind_mesh = np.prod(Z.shape) * 6 # resize (and invalidate) gpu buffers if needed. # a reallocation can only occur together with a change in data. # i.e. reallocation ==> change in data (render_cache is None) if DirtyFlag.DIM in dirty_bits: glstate.m_vbo_pos.bind() glstate.m_vbo_pos.allocate(num_vtx_mesh * 2 * 4) glstate.m_vbo_pos.release() glstate.m_vbo_lum.bind() glstate.m_vbo_lum.allocate(num_vtx_mesh * 1 * 4) glstate.m_vbo_lum.release() if glstate.flat_shading: # let the bottom-left of each quad be its "anchor". # then each quad is made up of 2 triangles # (TR, TL, BL); (BR, TR, BL) # that have indices # (stride + 1, stride + 0, 0); (1, stride + 1, 0) # where "0" is the relative index of BL # and "stride" advances to the next row # note that both triangles are created such that their 3rd vertex is at "BL" stride = Z.shape[1] + 1 dim0 = np.arange(0, Z.shape[0]*stride, stride, dtype=np.uint32)[:, np.newaxis, np.newaxis] dim1 = np.arange(Z.shape[1], dtype=np.uint32)[np.newaxis, :, np.newaxis] dim2 = np.array([stride + 1, stride + 0, 0, 1, stride + 1, 0], dtype=np.uint32)[np.newaxis, np.newaxis, :] buf_ind = dim0 + dim1 + dim2 else: # for each quad, we store 4 vertices contiguously (BL, BR, TL, TR) # then each quad is made up of 2 triangles # (TR, TL, BL); (BR, TR, BL) # that have indices # (3, 2, 0); (1, 3, 0) strides = np.cumprod(vtx_array_shape[::-1])[::-1] dim0 = np.arange(0, strides[0], strides[1], dtype=np.uint32)[:, np.newaxis, np.newaxis] dim1 = np.arange(0, strides[1], strides[2], dtype=np.uint32)[np.newaxis, :, np.newaxis] dim2 = np.array([3, 2, 0, 1, 3, 0], dtype=np.uint32)[np.newaxis, np.newaxis, :] buf_ind = dim0 + dim1 + dim2 glstate.m_vbo_ind.bind() glstate.m_vbo_ind.allocate(buf_ind, buf_ind.nbytes) glstate.m_vbo_ind.release() dirty_bits &= ~DirtyFlag.DIM if DirtyFlag.LUT in dirty_bits: lut = self.cmap.getLookupTable(nPts=256, alpha=True) glstate.setTextureLut(lut) dirty_bits &= ~DirtyFlag.LUT if DirtyFlag.XY in dirty_bits: pos = np.empty(vtx_array_shape + (2,), dtype=np.float32) if glstate.flat_shading: pos[..., 0] = X - xc pos[..., 1] = Y - yc else: XY = np.dstack((X - xc, Y - yc)).astype(np.float32) pos[..., 0, :] = XY[:-1, :-1, :] # BL pos[..., 1, :] = XY[1:, :-1, :] # BR pos[..., 2, :] = XY[:-1, 1:, :] # TL pos[..., 3, :] = XY[1:, 1:, :] # TR glstate.m_vbo_pos.bind() glstate.m_vbo_pos.write(0, pos, pos.nbytes) glstate.m_vbo_pos.release() dirty_bits &= ~DirtyFlag.XY if DirtyFlag.Z in dirty_bits: lum = np.empty(vtx_array_shape, dtype=np.float32) if glstate.flat_shading: lum[:-1, :-1] = Z else: lum[..., :] = np.expand_dims(Z, axis=2) glstate.m_vbo_lum.bind() glstate.m_vbo_lum.write(0, lum, lum.nbytes) glstate.m_vbo_lum.release() dirty_bits &= ~DirtyFlag.Z glstate.render_cache = [origin, dirty_bits] widget.setViewboxClip(view) glstate.m_vao.bind() glstate.m_texture.bind() program.bind() lo, hi = self.levels rng = hi - lo if rng == 0: rng = 1 program.setUniformValue("u_rescale", QtGui.QVector2D(1/rng, lo)) program.setUniformValue("u_mvp", mvp) NULL = compat.voidptr(0) if QT_LIB.startswith("PySide") else None glfn.glDrawElements(GLC.GL_TRIANGLES, num_ind_mesh, GLC.GL_UNSIGNED_INT, NULL) glstate.m_vao.release()
PColorMeshItem
python
streamlit__streamlit
lib/tests/streamlit/runtime/scriptrunner/script_cache_test.py
{ "start": 937, "end": 2859 }
class ____(unittest.TestCase): def test_load_valid_script(self): """`get_bytecode` works as expected.""" cache = ScriptCache() result = cache.get_bytecode(_get_script_path("good_script.py")) assert result is not None # Execing the code shouldn't raise an error exec(result) @mock.patch("streamlit.runtime.scriptrunner.script_cache.open_python_file") def test_returns_cached_data(self, mock_open_python_file: Mock): """`get_bytecode` caches its results.""" mock_open_python_file.side_effect = source_util.open_python_file cache = ScriptCache() # The first time we get a script's bytecode, the script is loaded from disk. result = cache.get_bytecode(_get_script_path("good_script.py")) assert result is not None mock_open_python_file.assert_called_once() # Subsequent calls don't reload the script from disk and return the same object. mock_open_python_file.reset_mock() assert cache.get_bytecode(_get_script_path("good_script.py")) is result mock_open_python_file.assert_not_called() def test_clear(self): """`clear` removes cached entries.""" cache = ScriptCache() cache.get_bytecode(_get_script_path("good_script.py")) assert len(cache._cache) == 1 cache.clear() assert len(cache._cache) == 0 def test_file_not_found_error(self): """An exception is thrown when a script file doesn't exist.""" cache = ScriptCache() with pytest.raises(FileNotFoundError): cache.get_bytecode(_get_script_path("not_a_valid_path.py")) def test_syntax_error(self): """An exception is thrown when a script has a compile error.""" cache = ScriptCache() with pytest.raises(SyntaxError): cache.get_bytecode(_get_script_path("compile_error.py.txt"))
ScriptCacheTest
python
RaRe-Technologies__gensim
gensim/test/test_utils.py
{ "start": 2463, "end": 3719 }
class ____(unittest.TestCase): def test_decode_entities(self): # create a string that fails to decode with unichr on narrow python builds body = u'It&#146;s the Year of the Horse. YES VIN DIESEL &#128588; &#128175;' expected = u'It\x92s the Year of the Horse. YES VIN DIESEL \U0001f64c \U0001f4af' self.assertEqual(utils.decode_htmlentities(body), expected) def test_open_file_existent_file(self): number_of_lines_in_file = 30 with utils.open_file(datapath('testcorpus.mm')) as infile: self.assertEqual(sum(1 for _ in infile), number_of_lines_in_file) def test_open_file_non_existent_file(self): with self.assertRaises(Exception): with utils.open_file('non_existent_file.txt'): pass def test_open_file_existent_file_object(self): number_of_lines_in_file = 30 file_obj = open(datapath('testcorpus.mm')) with utils.open_file(file_obj) as infile: self.assertEqual(sum(1 for _ in infile), number_of_lines_in_file) def test_open_file_non_existent_file_object(self): file_obj = None with self.assertRaises(Exception): with utils.open_file(file_obj): pass
TestUtils
python
kubernetes-client__python
kubernetes/client/models/v1_preconditions.py
{ "start": 383, "end": 4314 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'resource_version': 'str', 'uid': 'str' } attribute_map = { 'resource_version': 'resourceVersion', 'uid': 'uid' } def __init__(self, resource_version=None, uid=None, local_vars_configuration=None): # noqa: E501 """V1Preconditions - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._resource_version = None self._uid = None self.discriminator = None if resource_version is not None: self.resource_version = resource_version if uid is not None: self.uid = uid @property def resource_version(self): """Gets the resource_version of this V1Preconditions. # noqa: E501 Specifies the target ResourceVersion # noqa: E501 :return: The resource_version of this V1Preconditions. # noqa: E501 :rtype: str """ return self._resource_version @resource_version.setter def resource_version(self, resource_version): """Sets the resource_version of this V1Preconditions. Specifies the target ResourceVersion # noqa: E501 :param resource_version: The resource_version of this V1Preconditions. # noqa: E501 :type: str """ self._resource_version = resource_version @property def uid(self): """Gets the uid of this V1Preconditions. # noqa: E501 Specifies the target UID. # noqa: E501 :return: The uid of this V1Preconditions. # noqa: E501 :rtype: str """ return self._uid @uid.setter def uid(self, uid): """Sets the uid of this V1Preconditions. Specifies the target UID. # noqa: E501 :param uid: The uid of this V1Preconditions. # noqa: E501 :type: str """ self._uid = uid def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1Preconditions): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1Preconditions): return True return self.to_dict() != other.to_dict()
V1Preconditions
python
pytorch__pytorch
torch/testing/_internal/distributed/distributed_test.py
{ "start": 10732, "end": 15093 }
class ____(nn.Module): def __init__(self) -> None: super().__init__() self.lin1 = nn.Linear(10, 10, bias=False) self.lin2 = nn.Linear(10, 10, bias=False) def forward(self, x): # Second layer is used dependent on input x. use_second_layer = torch.equal(x, torch.ones(20, 10, device=x.device)) if use_second_layer: return self.lin2(F.relu(self.lin1(x))) else: return F.relu(self.lin1(x)) def get_timeout(test_id): test_name = test_id.split(".")[-1] if test_name in CUSTOMIZED_TIMEOUT: return CUSTOMIZED_TIMEOUT[test_name] else: return DEFAULT_TIMEOUT default_pg_timeout = 60 CUSTOM_PG_TIMEOUT = { # This test runs slowly and needs additional time to complete, otherwise can # be taken down by TORCH_NCCL_ASYNC_ERROR_HANDLING "test_ddp_uneven_inputs": 300, # This test has a short timeout since it tests being taken down by # TORCH_NCCL_ASYNC_ERROR_HANDLING which we want to happen quickly. "test_ddp_model_diff_across_ranks": 5, # This test has a short timeout since it tests being taken down by # TORCH_NCCL_ASYNC_ERROR_HANDLING which we want to happen quickly. "test_ddp_has_finalized": 5, } def require_backend_is_available(backends): def check(backend): if backend == dist.Backend.GLOO: return dist.is_gloo_available() if backend == dist.Backend.NCCL: return dist.is_nccl_available() if backend == dist.Backend.MPI: return dist.is_mpi_available() if backend == dist.Backend.UCC: return dist.is_ucc_available() if backend in DistTestCases.backend_feature["plugin"]: return True return False if BACKEND not in backends: return skip_but_pass_in_sandcastle( f"Test requires backend {BACKEND} to be one of {backends}" ) if not check(dist.Backend(BACKEND)): return skip_but_pass_in_sandcastle( f"Test requires backend {BACKEND} to be available" ) return lambda func: func def require_world_size(world_size): if int(os.environ["WORLD_SIZE"]) < world_size: return skip_but_pass_in_sandcastle( f"Test requires world size of {world_size:d}" ) return lambda func: func def require_exact_world_size(world_size): if int(os.environ["WORLD_SIZE"]) != world_size: return skip_but_pass_in_sandcastle( f"Test requires an exact world size of {world_size:d}" ) return lambda func: func @contextmanager def _lock(): TEMP_DIR = os.environ["TEMP_DIR"] lockfile = os.path.join(TEMP_DIR, "lockfile") with open(lockfile, "w") as lf: try: if sys.platform == "win32": msvcrt.locking(lf.fileno(), msvcrt.LK_RLCK, 1) yield else: fcntl.flock(lf.fileno(), fcntl.LOCK_EX) yield finally: if sys.platform == "win32": msvcrt.locking(lf.fileno(), msvcrt.LK_UNLCK, 1) else: fcntl.flock(lf.fileno(), fcntl.LOCK_UN) lf.close() @contextmanager def _rank_temp_file(): if dist.get_rank() == 0: fd, name = tempfile.mkstemp() os.close(fd) else: name = None object_list = [name] dist.broadcast_object_list(object_list) name = object_list[0] try: yield name finally: if dist.get_rank() == 0: os.remove(name) def _build_tensor(size, value=None, dtype=torch.float, device_id=None): if value is None: value = size if device_id is None: return torch.empty(size, size, size, dtype=dtype).fill_(value) else: return torch.empty(size, size, size, dtype=dtype).fill_(value).cuda(device_id) def _build_multidim_tensor(dim, dim_size, value=None, dtype=torch.float): if value is None: value = dim return torch.empty(size=[dim_size for _ in range(dim)], dtype=dtype).fill_(value) def _create_autograd_profiler(): return torch.autograd.profiler.profile(record_shapes=True) def _create_torch_profiler(): return torch.profiler.profile( activities=[ torch.profiler.ProfilerActivity.CPU, ], record_shapes=True, )
ControlFlowToyModel
python
tensorflow__tensorflow
tensorflow/python/keras/metrics.py
{ "start": 113354, "end": 115571 }
class ____(MeanMetricWrapper): """Computes the crossentropy metric between the labels and predictions. This is the crossentropy metric class to be used when there are multiple label classes (2 or more). Here we assume that labels are given as a `one_hot` representation. eg., When labels values are [2, 0, 1], `y_true` = [[0, 0, 1], [1, 0, 0], [0, 1, 0]]. Args: name: (Optional) string name of the metric instance. dtype: (Optional) data type of the metric result. from_logits: (Optional) Whether output is expected to be a logits tensor. By default, we consider that output encodes a probability distribution. label_smoothing: (Optional) Float in [0, 1]. When > 0, label values are smoothed, meaning the confidence on label values are relaxed. e.g. `label_smoothing=0.2` means that we will use a value of `0.1` for label `0` and `0.9` for label `1`" Standalone usage: >>> # EPSILON = 1e-7, y = y_true, y` = y_pred >>> # y` = clip_ops.clip_by_value(output, EPSILON, 1. - EPSILON) >>> # y` = [[0.05, 0.95, EPSILON], [0.1, 0.8, 0.1]] >>> # xent = -sum(y * log(y'), axis = -1) >>> # = -((log 0.95), (log 0.1)) >>> # = [0.051, 2.302] >>> # Reduced xent = (0.051 + 2.302) / 2 >>> m = tf.keras.metrics.CategoricalCrossentropy() >>> m.update_state([[0, 1, 0], [0, 0, 1]], ... [[0.05, 0.95, 0], [0.1, 0.8, 0.1]]) >>> m.result().numpy() 1.1769392 >>> m.reset_state() >>> m.update_state([[0, 1, 0], [0, 0, 1]], ... [[0.05, 0.95, 0], [0.1, 0.8, 0.1]], ... sample_weight=tf.constant([0.3, 0.7])) >>> m.result().numpy() 1.6271976 Usage with `compile()` API: ```python model.compile( optimizer='sgd', loss='mse', metrics=[tf.keras.metrics.CategoricalCrossentropy()]) ``` """ def __init__(self, name='categorical_crossentropy', dtype=None, from_logits=False, label_smoothing=0): super(CategoricalCrossentropy, self).__init__( categorical_crossentropy, name, dtype=dtype, from_logits=from_logits, label_smoothing=label_smoothing)
CategoricalCrossentropy
python
python-attrs__attrs
tests/test_funcs.py
{ "start": 16344, "end": 17524 }
class ____: """ Tests for `has`. """ def test_positive(self, C): """ Returns `True` on decorated classes. """ assert has(C) def test_positive_empty(self): """ Returns `True` on decorated classes even if there are no attributes. """ @attr.s class D: pass assert has(D) def test_negative(self): """ Returns `False` on non-decorated classes. """ assert not has(object) def test_generics(self): """ Works with generic classes. """ T = TypeVar("T") @attr.define class A(Generic[T]): a: T assert has(A) assert has(A[str]) # Verify twice, since there's caching going on. assert has(A[str]) def test_generics_negative(self): """ Returns `False` on non-decorated generic classes. """ T = TypeVar("T") class A(Generic[T]): a: T assert not has(A) assert not has(A[str]) # Verify twice, since there's caching going on. assert not has(A[str])
TestHas
python
kamyu104__LeetCode-Solutions
Python/search-in-rotated-sorted-array-ii.py
{ "start": 39, "end": 721 }
class ____(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ left, right = 0, len(nums) - 1 while left <= right: mid = left + (right - left) / 2 if nums[mid] == target: return True elif nums[mid] == nums[left]: left += 1 elif (nums[mid] > nums[left] and nums[left] <= target < nums[mid]) or \ (nums[mid] < nums[left] and not (nums[mid] < target <= nums[right])): right = mid - 1 else: left = mid + 1 return False
Solution
python
ray-project__ray
doc/source/ray-core/doc_code/anti_pattern_return_ray_put.py
{ "start": 2974, "end": 4576 }
class ____: @ray.method(num_returns=1) def task_with_static_multiple_returns_bad1(self): return_value_1_ref = ray.put(1) return_value_2_ref = ray.put(2) return (return_value_1_ref, return_value_2_ref) @ray.method(num_returns=2) def task_with_static_multiple_returns_bad2(self): return_value_1_ref = ray.put(1) return_value_2_ref = ray.put(2) return (return_value_1_ref, return_value_2_ref) @ray.method(num_returns=2) def task_with_static_multiple_returns_good(self): # This is faster and more fault tolerant. return_value_1 = 1 return_value_2 = 2 return (return_value_1, return_value_2) actor = Actor.remote() assert ( ray.get(ray.get(actor.task_with_static_multiple_returns_bad1.remote())[0]) == ray.get(ray.get(actor.task_with_static_multiple_returns_bad2.remote()[0])) == ray.get(actor.task_with_static_multiple_returns_good.remote()[0]) ) # __return_static_multi_values_end__ # __return_dynamic_multi_values_start__ @ray.remote(num_returns=1) def task_with_dynamic_returns_bad(n): return_value_refs = [] for i in range(n): return_value_refs.append(ray.put(np.zeros(i * 1024 * 1024))) return return_value_refs @ray.remote(num_returns="dynamic") def task_with_dynamic_returns_good(n): for i in range(n): yield np.zeros(i * 1024 * 1024) assert np.array_equal( ray.get(ray.get(task_with_dynamic_returns_bad.remote(2))[0]), ray.get(next(iter(ray.get(task_with_dynamic_returns_good.remote(2))))), ) # __return_dynamic_multi_values_end__
Actor
python
google__jax
jax/_src/lax/linalg.py
{ "start": 4253, "end": 8247 }
class ____(enum.Enum): """Enum for eigendecomposition algorithm.""" CUSOLVER = "cusolver" MAGMA = "magma" LAPACK = "lapack" def eig( x: ArrayLike, *, compute_left_eigenvectors: bool = True, compute_right_eigenvectors: bool = True, implementation: EigImplementation | None = None, use_magma: bool | None = None, ) -> list[Array]: """Eigendecomposition of a general matrix. Nonsymmetric eigendecomposition is only implemented on CPU and GPU. On GPU, the default implementation calls LAPACK directly on the host CPU, but an experimental GPU implementation using `MAGMA <https://icl.utk.edu/magma/>`_ is also available. The MAGMA implementation is typically slower than the equivalent LAPACK implementation for small matrices (less than about 2048), but it may perform better for larger matrices. To enable the MAGMA implementation, you must install MAGMA yourself (there are Debian and conda-forge packages, or you can build from source). Then set the ``use_magma`` argument to ``True``, or set the ``jax_use_magma`` configuration variable to ``"on"`` or ``"auto"``: .. code-block:: python jax.config.update('jax_use_magma', 'on') JAX will try to ``dlopen`` the installed MAGMA shared library, raising an error if it is not found. To explicitly specify the path to the MAGMA library, set the environment variable `JAX_GPU_MAGMA_PATH` to the full installation path. If ``jax_use_magma`` is set to ``"auto"``, the MAGMA implementation will be used if the library can be found, and the input matrix is sufficiently large (>= 2048x2048). Args: x: A batch of square matrices with shape ``[..., n, n]``. compute_left_eigenvectors: If true, the left eigenvectors will be computed. compute_right_eigenvectors: If true, the right eigenvectors will be computed. use_magma: Deprecated, please use ``implementation`` instead. Locally override the ``jax_use_magma`` flag. If ``True``, the eigendecomposition is computed using MAGMA. If ``False``, the computation is done using LAPACK on to the host CPU. If ``None`` (default), the behavior is controlled by the ``jax_use_magma`` flag. This argument is only used on GPU. Will be removed in JAX 0.9. implementation: Controls the choice of eigendecomposition algorithm. If ``LAPACK``, the computation will be performed using LAPACK on the host CPU. If ``MAGMA``, the computation will be performed using the MAGMA library on the GPU. If ``CUSOLVER``, the computation will be performed using the Cusolver library on the GPU. The ``CUSOLVER`` implementation requires Cusolver 11.7.1 (from CUDA 12.6 update 2) to be installed, and does not support computing left eigenvectors. If ``None`` (default), an automatic choice will be made, depending on the Cusolver version, whether left eigenvectors were requested, and the ``jax_use_magma`` configuration variable. Returns: The eigendecomposition of ``x``, which is a tuple of the form ``(w, vl, vr)`` where ``w`` are the eigenvalues, ``vl`` are the left eigenvectors, and ``vr`` are the right eigenvectors. ``vl`` and ``vr`` are optional and will only be included if ``compute_left_eigenvectors`` or ``compute_right_eigenvectors`` respectively are ``True``. If the eigendecomposition fails, then arrays full of NaNs will be returned for that batch element. """ if use_magma is not None: warnings.warn( "use_magma is deprecated, please use" " implementation=EigImplementation.MAGMA instead.", DeprecationWarning, stacklevel=2, ) implementation = ( EigImplementation.MAGMA if use_magma else EigImplementation.LAPACK ) return eig_p.bind(x, compute_left_eigenvectors=compute_left_eigenvectors, compute_right_eigenvectors=compute_right_eigenvectors, implementation=implementation)
EigImplementation
python
huggingface__transformers
src/transformers/models/encodec/modeling_encodec.py
{ "start": 1127, "end": 1655 }
class ____(ModelOutput): r""" audio_codes (`torch.LongTensor` of shape `(nb_frames, batch_size, nb_quantizers, frame_len)`, *optional*): Discrete code embeddings computed using `model.encode`. audio_values (`torch.FloatTensor` of shape `(batch_size, segment_length)`, *optional*): Decoded audio values, obtained using the decoder part of Encodec. """ audio_codes: Optional[torch.LongTensor] = None audio_values: Optional[torch.FloatTensor] = None @dataclass @auto_docstring
EncodecOutput
python
plotly__plotly.py
plotly/graph_objs/_figure.py
{ "start": 173, "end": 1111376 }
class ____(BaseFigure): def __init__( self, data=None, layout=None, frames=None, skip_invalid=False, **kwargs ): """ Create a new :class:Figure instance Parameters ---------- data The 'data' property is a tuple of trace instances that may be specified as: - A list or tuple of trace instances (e.g. [Scatter(...), Bar(...)]) - A single trace instance (e.g. Scatter(...), Bar(...), etc.) - A list or tuple of dicts of string/value properties where: - The 'type' property specifies the trace type One of: ['bar', 'barpolar', 'box', 'candlestick', 'carpet', 'choropleth', 'choroplethmap', 'choroplethmapbox', 'cone', 'contour', 'contourcarpet', 'densitymap', 'densitymapbox', 'funnel', 'funnelarea', 'heatmap', 'histogram', 'histogram2d', 'histogram2dcontour', 'icicle', 'image', 'indicator', 'isosurface', 'mesh3d', 'ohlc', 'parcats', 'parcoords', 'pie', 'sankey', 'scatter', 'scatter3d', 'scattercarpet', 'scattergeo', 'scattergl', 'scattermap', 'scattermapbox', 'scatterpolar', 'scatterpolargl', 'scattersmith', 'scatterternary', 'splom', 'streamtube', 'sunburst', 'surface', 'table', 'treemap', 'violin', 'volume', 'waterfall'] - All remaining properties are passed to the constructor of the specified trace type (e.g. [{'type': 'scatter', ...}, {'type': 'bar, ...}]) layout The 'layout' property is an instance of Layout that may be specified as: - An instance of :class:`plotly.graph_objs.Layout` - A dict of string/value properties that will be passed to the Layout constructor frames The 'frames' property is a tuple of instances of Frame that may be specified as: - A list or tuple of instances of plotly.graph_objs.Frame - A list or tuple of dicts of string/value properties that will be passed to the Frame constructor skip_invalid: bool If True, invalid properties in the figure specification will be skipped silently. If False (default) invalid properties in the figure specification will result in a ValueError Raises ------ ValueError if a property in the specification of data, layout, or frames is invalid AND skip_invalid is False """ super().__init__(data, layout, frames, skip_invalid, **kwargs) def update(self, dict1=None, overwrite=False, **kwargs) -> "Figure": """ Update the properties of the figure with a dict and/or with keyword arguments. This recursively updates the structure of the figure object with the values in the input dict / keyword arguments. Parameters ---------- dict1 : dict Dictionary of properties to be updated overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. kwargs : Keyword/value pair of properties to be updated Examples -------- >>> import plotly.graph_objs as go >>> fig = go.Figure(data=[{'y': [1, 2, 3]}]) >>> fig.update(data=[{'y': [4, 5, 6]}]) # doctest: +ELLIPSIS Figure(...) >>> fig.to_plotly_json() # doctest: +SKIP {'data': [{'type': 'scatter', 'uid': 'e86a7c7a-346a-11e8-8aa8-a0999b0c017b', 'y': array([4, 5, 6], dtype=int32)}], 'layout': {}} >>> fig = go.Figure(layout={'xaxis': ... {'color': 'green', ... 'range': [0, 1]}}) >>> fig.update({'layout': {'xaxis': {'color': 'pink'}}}) # doctest: +ELLIPSIS Figure(...) >>> fig.to_plotly_json() # doctest: +SKIP {'data': [], 'layout': {'xaxis': {'color': 'pink', 'range': [0, 1]}}} Returns ------- BaseFigure Updated figure """ return super().update(dict1, overwrite, **kwargs) def update_traces( self, patch=None, selector=None, row=None, col=None, secondary_y=None, overwrite=False, **kwargs, ) -> "Figure": """ Perform a property update operation on all traces that satisfy the specified selection criteria Parameters ---------- patch: dict or None (default None) Dictionary of property updates to be applied to all traces that satisfy the selection criteria. selector: dict, function, int, str or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all traces are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each trace and those for which the function returned True will be in the selection. If an int N, the Nth trace matching row and col will be selected (N can be negative). If a string S, the selector is equivalent to dict(type=S). row, col: int or None (default None) Subplot row and column index of traces to select. To select traces by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all traces are selected. secondary_y: boolean or None (default None) * If True, only select traces associated with the secondary y-axis of the subplot. * If False, only select traces associated with the primary y-axis of the subplot. * If None (the default), do not filter traces based on secondary y-axis. To select traces by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. **kwargs Additional property updates to apply to each selected trace. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ return super().update_traces( patch, selector, row, col, secondary_y, overwrite, **kwargs ) def update_layout(self, dict1=None, overwrite=False, **kwargs) -> "Figure": """ Update the properties of the figure's layout with a dict and/or with keyword arguments. This recursively updates the structure of the original layout with the values in the input dict / keyword arguments. Parameters ---------- dict1 : dict Dictionary of properties to be updated overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. kwargs : Keyword/value pair of properties to be updated Returns ------- BaseFigure The Figure object that the update_layout method was called on """ return super().update_layout(dict1, overwrite, **kwargs) def for_each_trace( self, fn, selector=None, row=None, col=None, secondary_y=None ) -> "Figure": """ Apply a function to all traces that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single trace object. selector: dict, function, int, str or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all traces are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each trace and those for which the function returned True will be in the selection. If an int N, the Nth trace matching row and col will be selected (N can be negative). If a string S, the selector is equivalent to dict(type=S). row, col: int or None (default None) Subplot row and column index of traces to select. To select traces by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all traces are selected. secondary_y: boolean or None (default None) * If True, only select traces associated with the secondary y-axis of the subplot. * If False, only select traces associated with the primary y-axis of the subplot. * If None (the default), do not filter traces based on secondary y-axis. To select traces by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- self Returns the Figure object that the method was called on """ return super().for_each_trace(fn, selector, row, col, secondary_y) def add_trace( self, trace, row=None, col=None, secondary_y=None, exclude_empty_subplots=False ) -> "Figure": """ 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(...) """ return super().add_trace(trace, row, col, secondary_y, exclude_empty_subplots) def add_traces( self, data, rows=None, cols=None, secondary_ys=None, exclude_empty_subplots=False, ) -> "Figure": """ Add traces to the figure Parameters ---------- data : list[BaseTraceType or dict] A list of trace specifications to be added. Trace specifications may be either: - Instances of trace classes from the plotly.graph_objs package (e.g plotly.graph_objs.Scatter, plotly.graph_objs.Bar) - Dicts where: - The 'type' property specifies the trace type (e.g. 'scatter', 'bar', 'area', etc.). If the dict has no 'type' property then 'scatter' is assumed. - All remaining properties are passed to the constructor of the specified trace type. rows : None, list[int], or int (default None) List of subplot row indexes (starting from 1) for the traces to be added. Only valid if figure was created using `plotly.tools.make_subplots` If a single integer is passed, all traces will be added to row number cols : None or list[int] (default None) List of subplot column indexes (starting from 1) for the traces to be added. Only valid if figure was created using `plotly.tools.make_subplots` If a single integer is passed, all traces will be added to column number secondary_ys: None or list[boolean] (default None) List of secondary_y booleans for traces to be added. See the docstring for `add_trace` for more info. exclude_empty_subplots: boolean If True, the trace will not be added to subplots that don't already have traces. Returns ------- BaseFigure The Figure that add_traces 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_traces([go.Scatter(x=[1,2,3], y=[2,1,2]), ... 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_traces([go.Scatter(x=[1,2,3], y=[2,1,2]), ... go.Scatter(x=[1,2,3], y=[2,1,2])], ... rows=[1, 2], cols=[1, 1]) # doctest: +ELLIPSIS Figure(...) """ return super().add_traces( data, rows, cols, secondary_ys, exclude_empty_subplots ) def add_vline( self, x, row="all", col="all", exclude_empty_subplots=True, annotation=None, **kwargs, ) -> "Figure": """ Add a vertical line to a plot or subplot that extends infinitely in the y-dimension. Parameters ---------- x: float or int A number representing the x coordinate of the vertical line. exclude_empty_subplots: Boolean If True (default) do not place the shape on subplots that have no data plotted on them. row: None, int or 'all' Subplot row for shape indexed starting at 1. If 'all', addresses all rows in the specified column(s). If both row and col are None, addresses the first subplot if subplots exist, or the only plot. By default is "all". col: None, int or 'all' Subplot column for shape indexed starting at 1. If 'all', addresses all rows in the specified column(s). If both row and col are None, addresses the first subplot if subplots exist, or the only plot. By default is "all". annotation: dict or plotly.graph_objects.layout.Annotation. If dict(), it is interpreted as describing an annotation. The annotation is placed relative to the shape based on annotation_position (see below) unless its x or y value has been specified for the annotation passed here. xref and yref are always the same as for the added shape and cannot be overridden. annotation_position: a string containing optionally ["top", "bottom"] and ["left", "right"] specifying where the text should be anchored to on the line. Example positions are "bottom left", "right top", "right", "bottom". If an annotation is added but annotation_position is not specified, this defaults to "top right". annotation_*: any parameters to go.layout.Annotation can be passed as keywords by prefixing them with "annotation_". For example, to specify the annotation text "example" you can pass annotation_text="example" as a keyword argument. **kwargs: Any named function parameters that can be passed to 'add_shape', except for x0, x1, y0, y1 or type. """ return super().add_vline( x, row, col, exclude_empty_subplots, annotation, **kwargs ) def add_hline( self, y, row="all", col="all", exclude_empty_subplots=True, annotation=None, **kwargs, ) -> "Figure": """ Add a horizontal line to a plot or subplot that extends infinitely in the x-dimension. Parameters ---------- y: float or int A number representing the y coordinate of the horizontal line. exclude_empty_subplots: Boolean If True (default) do not place the shape on subplots that have no data plotted on them. row: None, int or 'all' Subplot row for shape indexed starting at 1. If 'all', addresses all rows in the specified column(s). If both row and col are None, addresses the first subplot if subplots exist, or the only plot. By default is "all". col: None, int or 'all' Subplot column for shape indexed starting at 1. If 'all', addresses all rows in the specified column(s). If both row and col are None, addresses the first subplot if subplots exist, or the only plot. By default is "all". annotation: dict or plotly.graph_objects.layout.Annotation. If dict(), it is interpreted as describing an annotation. The annotation is placed relative to the shape based on annotation_position (see below) unless its x or y value has been specified for the annotation passed here. xref and yref are always the same as for the added shape and cannot be overridden. annotation_position: a string containing optionally ["top", "bottom"] and ["left", "right"] specifying where the text should be anchored to on the line. Example positions are "bottom left", "right top", "right", "bottom". If an annotation is added but annotation_position is not specified, this defaults to "top right". annotation_*: any parameters to go.layout.Annotation can be passed as keywords by prefixing them with "annotation_". For example, to specify the annotation text "example" you can pass annotation_text="example" as a keyword argument. **kwargs: Any named function parameters that can be passed to 'add_shape', except for x0, x1, y0, y1 or type. """ return super().add_hline( y, row, col, exclude_empty_subplots, annotation, **kwargs ) def add_vrect( self, x0, x1, row="all", col="all", exclude_empty_subplots=True, annotation=None, **kwargs, ) -> "Figure": """ Add a rectangle to a plot or subplot that extends infinitely in the y-dimension. Parameters ---------- x0: float or int A number representing the x coordinate of one side of the rectangle. x1: float or int A number representing the x coordinate of the other side of the rectangle. exclude_empty_subplots: Boolean If True (default) do not place the shape on subplots that have no data plotted on them. row: None, int or 'all' Subplot row for shape indexed starting at 1. If 'all', addresses all rows in the specified column(s). If both row and col are None, addresses the first subplot if subplots exist, or the only plot. By default is "all". col: None, int or 'all' Subplot column for shape indexed starting at 1. If 'all', addresses all rows in the specified column(s). If both row and col are None, addresses the first subplot if subplots exist, or the only plot. By default is "all". annotation: dict or plotly.graph_objects.layout.Annotation. If dict(), it is interpreted as describing an annotation. The annotation is placed relative to the shape based on annotation_position (see below) unless its x or y value has been specified for the annotation passed here. xref and yref are always the same as for the added shape and cannot be overridden. annotation_position: a string containing optionally ["inside", "outside"], ["top", "bottom"] and ["left", "right"] specifying where the text should be anchored to on the rectangle. Example positions are "outside top left", "inside bottom", "right", "inside left", "inside" ("outside" is not supported). If an annotation is added but annotation_position is not specified this defaults to "inside top right". annotation_*: any parameters to go.layout.Annotation can be passed as keywords by prefixing them with "annotation_". For example, to specify the annotation text "example" you can pass annotation_text="example" as a keyword argument. **kwargs: Any named function parameters that can be passed to 'add_shape', except for x0, x1, y0, y1 or type. """ return super().add_vrect( x0, x1, row, col, exclude_empty_subplots, annotation, **kwargs ) def add_hrect( self, y0, y1, row="all", col="all", exclude_empty_subplots=True, annotation=None, **kwargs, ) -> "Figure": """ Add a rectangle to a plot or subplot that extends infinitely in the x-dimension. Parameters ---------- y0: float or int A number representing the y coordinate of one side of the rectangle. y1: float or int A number representing the y coordinate of the other side of the rectangle. exclude_empty_subplots: Boolean If True (default) do not place the shape on subplots that have no data plotted on them. row: None, int or 'all' Subplot row for shape indexed starting at 1. If 'all', addresses all rows in the specified column(s). If both row and col are None, addresses the first subplot if subplots exist, or the only plot. By default is "all". col: None, int or 'all' Subplot column for shape indexed starting at 1. If 'all', addresses all rows in the specified column(s). If both row and col are None, addresses the first subplot if subplots exist, or the only plot. By default is "all". annotation: dict or plotly.graph_objects.layout.Annotation. If dict(), it is interpreted as describing an annotation. The annotation is placed relative to the shape based on annotation_position (see below) unless its x or y value has been specified for the annotation passed here. xref and yref are always the same as for the added shape and cannot be overridden. annotation_position: a string containing optionally ["inside", "outside"], ["top", "bottom"] and ["left", "right"] specifying where the text should be anchored to on the rectangle. Example positions are "outside top left", "inside bottom", "right", "inside left", "inside" ("outside" is not supported). If an annotation is added but annotation_position is not specified this defaults to "inside top right". annotation_*: any parameters to go.layout.Annotation can be passed as keywords by prefixing them with "annotation_". For example, to specify the annotation text "example" you can pass annotation_text="example" as a keyword argument. **kwargs: Any named function parameters that can be passed to 'add_shape', except for x0, x1, y0, y1 or type. """ return super().add_hrect( y0, y1, row, col, exclude_empty_subplots, annotation, **kwargs ) def set_subplots(self, rows=None, cols=None, **make_subplots_args) -> "Figure": """ Add subplots to this figure. If the figure already contains subplots, then this throws an error. Accepts any keyword arguments that plotly.subplots.make_subplots accepts. """ return super().set_subplots(rows, cols, **make_subplots_args) def add_bar( self, alignmentgroup=None, base=None, basesrc=None, cliponaxis=None, constraintext=None, customdata=None, customdatasrc=None, dx=None, dy=None, error_x=None, error_y=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=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, offsetsrc=None, opacity=None, orientation=None, outsidetextfont=None, selected=None, selectedpoints=None, showlegend=None, stream=None, text=None, textangle=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatefallback=None, texttemplatesrc=None, uid=None, uirevision=None, unselected=None, visible=None, width=None, widthsrc=None, x=None, x0=None, xaxis=None, xcalendar=None, xhoverformat=None, xperiod=None, xperiod0=None, xperiodalignment=None, xsrc=None, y=None, y0=None, yaxis=None, ycalendar=None, yhoverformat=None, yperiod=None, yperiod0=None, yperiodalignment=None, ysrc=None, zorder=None, row=None, col=None, secondary_y=None, **kwargs, ) -> "Figure": """ Add a new Bar trace 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 ---------- 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). In "stack" or "relative" barmode, traces that set "base" will be excluded and drawn in "overlay" mode instead. basesrc Sets the source reference on Chart Studio Cloud for `base`. 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*. 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. error_x :class:`plotly.graph_objects.bar.ErrorX` instance or dict with compatible properties error_y :class:`plotly.graph_objects.bar.ErrorY` 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.bar.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `value` and `label`. 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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.bar.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.bar.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. 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. selected :class:`plotly.graph_objects.bar.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. stream :class:`plotly.graph_objects.bar.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`. 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 appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `value` and `label`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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. unselected :class:`plotly.graph_objects.bar.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 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. xcalendar Sets the calendar system to use with `x` date data. 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. ycalendar Sets the calendar system to use with `y` date data. 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`. 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. Returns ------- Figure """ from plotly.graph_objs import Bar new_trace = Bar( alignmentgroup=alignmentgroup, base=base, basesrc=basesrc, cliponaxis=cliponaxis, constraintext=constraintext, customdata=customdata, customdatasrc=customdatasrc, dx=dx, dy=dy, error_x=error_x, error_y=error_y, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, insidetextanchor=insidetextanchor, insidetextfont=insidetextfont, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, marker=marker, meta=meta, metasrc=metasrc, name=name, offset=offset, offsetgroup=offsetgroup, offsetsrc=offsetsrc, opacity=opacity, orientation=orientation, outsidetextfont=outsidetextfont, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, text=text, textangle=textangle, textfont=textfont, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, texttemplatesrc=texttemplatesrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, width=width, widthsrc=widthsrc, x=x, x0=x0, xaxis=xaxis, xcalendar=xcalendar, xhoverformat=xhoverformat, xperiod=xperiod, xperiod0=xperiod0, xperiodalignment=xperiodalignment, xsrc=xsrc, y=y, y0=y0, yaxis=yaxis, ycalendar=ycalendar, yhoverformat=yhoverformat, yperiod=yperiod, yperiod0=yperiod0, yperiodalignment=yperiodalignment, ysrc=ysrc, zorder=zorder, **kwargs, ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_barpolar( self, base=None, basesrc=None, customdata=None, customdatasrc=None, dr=None, dtheta=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=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, offset=None, offsetsrc=None, opacity=None, r=None, r0=None, rsrc=None, selected=None, selectedpoints=None, showlegend=None, stream=None, subplot=None, text=None, textsrc=None, theta=None, theta0=None, thetasrc=None, thetaunit=None, uid=None, uirevision=None, unselected=None, visible=None, width=None, widthsrc=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Barpolar trace The data visualized by the radial span of the bars is set in `r` Parameters ---------- base Sets where the bar base is drawn (in radial axis units). In "stack" barmode, traces that set "base" will be excluded and drawn in "overlay" mode instead. basesrc Sets the source reference on Chart Studio Cloud for `base`. 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`. dr Sets the r coordinate step. dtheta Sets the theta coordinate step. By default, the `dtheta` step equals the subplot's period divided by the length of the `r` coordinates. 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.barpolar.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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.barpolar.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.barpolar.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 angular position where the bar is drawn (in "thetatunit" units). offsetsrc Sets the source reference on Chart Studio Cloud for `offset`. opacity Sets the opacity of the trace. r Sets the radial coordinates r0 Alternate to `r`. Builds a linear space of r coordinates. Use with `dr` where `r0` is the starting coordinate and `dr` the step. rsrc Sets the source reference on Chart Studio Cloud for `r`. selected :class:`plotly.graph_objects.barpolar.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. stream :class:`plotly.graph_objects.barpolar.Stream` instance or dict with compatible properties subplot Sets a reference between this trace's data coordinates and a polar subplot. If "polar" (the default value), the data refer to `layout.polar`. If "polar2", the data refer to `layout.polar2`, and so on. text Sets hover text elements associated with each bar. If a single string, the same string appears over all bars. If an array of string, the items are mapped in order to the this trace's coordinates. textsrc Sets the source reference on Chart Studio Cloud for `text`. theta Sets the angular coordinates theta0 Alternate to `theta`. Builds a linear space of theta coordinates. Use with `dtheta` where `theta0` is the starting coordinate and `dtheta` the step. thetasrc Sets the source reference on Chart Studio Cloud for `theta`. thetaunit Sets the unit of input "theta" values. Has an effect only when on "linear" angular axes. 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.barpolar.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 bar angular width (in "thetaunit" units). widthsrc Sets the source reference on Chart Studio Cloud for `width`. 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). Returns ------- Figure """ from plotly.graph_objs import Barpolar new_trace = Barpolar( base=base, basesrc=basesrc, customdata=customdata, customdatasrc=customdatasrc, dr=dr, dtheta=dtheta, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, marker=marker, meta=meta, metasrc=metasrc, name=name, offset=offset, offsetsrc=offsetsrc, opacity=opacity, r=r, r0=r0, rsrc=rsrc, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, subplot=subplot, text=text, textsrc=textsrc, theta=theta, theta0=theta0, thetasrc=thetasrc, thetaunit=thetaunit, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, width=width, widthsrc=widthsrc, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_box( self, alignmentgroup=None, boxmean=None, boxpoints=None, customdata=None, customdatasrc=None, dx=None, dy=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hoveron=None, hovertemplate=None, hovertemplatefallback=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, lowerfence=None, lowerfencesrc=None, marker=None, mean=None, meansrc=None, median=None, mediansrc=None, meta=None, metasrc=None, name=None, notched=None, notchspan=None, notchspansrc=None, notchwidth=None, offsetgroup=None, opacity=None, orientation=None, pointpos=None, q1=None, q1src=None, q3=None, q3src=None, quartilemethod=None, sd=None, sdmultiple=None, sdsrc=None, selected=None, selectedpoints=None, showlegend=None, showwhiskers=None, sizemode=None, stream=None, text=None, textsrc=None, uid=None, uirevision=None, unselected=None, upperfence=None, upperfencesrc=None, visible=None, whiskerwidth=None, width=None, x=None, x0=None, xaxis=None, xcalendar=None, xhoverformat=None, xperiod=None, xperiod0=None, xperiodalignment=None, xsrc=None, y=None, y0=None, yaxis=None, ycalendar=None, yhoverformat=None, yperiod=None, yperiod0=None, yperiodalignment=None, ysrc=None, zorder=None, row=None, col=None, secondary_y=None, **kwargs, ) -> "Figure": """ Add a new Box trace Each box spans from quartile 1 (Q1) to quartile 3 (Q3). The second quartile (Q2, i.e. the median) is marked by a line inside the box. The fences grow outward from the boxes' edges, by default they span +/- 1.5 times the interquartile range (IQR: Q3-Q1), The sample mean and standard deviation as well as notches and the sample, outlier and suspected outliers points can be optionally added to the box plot. The values and positions corresponding to each boxes can be input using two signatures. The first signature expects users to supply the sample values in the `y` data array for vertical boxes (`x` for horizontal boxes). By supplying an `x` (`y`) array, one box per distinct `x` (`y`) value is drawn If no `x` (`y`) list is provided, a single box is drawn. In this case, the box is positioned with the trace `name` or with `x0` (`y0`) if provided. The second signature expects users to supply the boxes corresponding Q1, median and Q3 statistics in the `q1`, `median` and `q3` data arrays respectively. Other box features relying on statistics namely `lowerfence`, `upperfence`, `notchspan` can be set directly by the users. To have plotly compute them or to show sample points besides the boxes, users can set the `y` data array for vertical boxes (`x` for horizontal boxes) to a 2D array with the outer length corresponding to the number of boxes in the traces and the inner length corresponding the sample size. Parameters ---------- 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. boxmean If True, the mean of the box(es)' underlying distribution is drawn as a dashed line inside the box(es). If "sd" the standard deviation is also drawn. Defaults to True when `mean` is set. Defaults to "sd" when `sd` is set Otherwise defaults to False. boxpoints 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 box(es) are shown with no sample points Defaults to "suspectedoutliers" when `marker.outliercolor` or `marker.line.outliercolor` is set. Defaults to "all" under the q1/median/q3 signature. Otherwise defaults to "outliers". 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 for multi-box traces set using q1/median/q3. dy Sets the y coordinate step for multi-box traces set using q1/median/q3. 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.box.Hoverlabel` instance or dict with compatible properties hoveron Do the hover effects highlight individual boxes or sample points or both? 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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 box(es). 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.box.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.box.Line` instance or dict with compatible properties lowerfence Sets the lower fence values. There should be as many items as the number of boxes desired. This attribute has effect only under the q1/median/q3 signature. If `lowerfence` is not provided but a sample (in `y` or `x`) is set, we compute the lower as the last sample point below 1.5 times the IQR. lowerfencesrc Sets the source reference on Chart Studio Cloud for `lowerfence`. marker :class:`plotly.graph_objects.box.Marker` instance or dict with compatible properties mean Sets the mean values. There should be as many items as the number of boxes desired. This attribute has effect only under the q1/median/q3 signature. If `mean` is not provided but a sample (in `y` or `x`) is set, we compute the mean for each box using the sample values. meansrc Sets the source reference on Chart Studio Cloud for `mean`. median Sets the median values. There should be as many items as the number of boxes desired. mediansrc Sets the source reference on Chart Studio Cloud for `median`. 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 box 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 notched Determines whether or not notches are drawn. Notches displays a confidence interval around the median. We compute the confidence interval as median +/- 1.57 * IQR / sqrt(N), where IQR is the interquartile range and N is the sample size. If two boxes' notches do not overlap there is 95% confidence their medians differ. See https://sites.google.com/site/davidsstatistics/home /notched-box-plots for more info. Defaults to False unless `notchwidth` or `notchspan` is set. notchspan Sets the notch span from the boxes' `median` values. There should be as many items as the number of boxes desired. This attribute has effect only under the q1/median/q3 signature. If `notchspan` is not provided but a sample (in `y` or `x`) is set, we compute it as 1.57 * IQR / sqrt(N), where N is the sample size. notchspansrc Sets the source reference on Chart Studio Cloud for `notchspan`. notchwidth Sets the width of the notches relative to the box width. For example, with 0, the notches are as wide as the box(es). 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 box(es). If "v" ("h"), the distribution is visualized along the vertical (horizontal). pointpos Sets the position of the sample points in relation to the box(es). If 0, the sample points are places over the center of the box(es). Positive (negative) values correspond to positions to the right (left) for vertical boxes and above (below) for horizontal boxes q1 Sets the Quartile 1 values. There should be as many items as the number of boxes desired. q1src Sets the source reference on Chart Studio Cloud for `q1`. q3 Sets the Quartile 3 values. There should be as many items as the number of boxes desired. q3src Sets the source reference on Chart Studio Cloud for `q3`. 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. sd Sets the standard deviation values. There should be as many items as the number of boxes desired. This attribute has effect only under the q1/median/q3 signature. If `sd` is not provided but a sample (in `y` or `x`) is set, we compute the standard deviation for each box using the sample values. sdmultiple Scales the box size when sizemode=sd Allowing boxes to be drawn across any stddev range For example 1-stddev, 3-stddev, 5-stddev sdsrc Sets the source reference on Chart Studio Cloud for `sd`. selected :class:`plotly.graph_objects.box.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. showwhiskers Determines whether or not whiskers are visible. Defaults to true for `sizemode` "quartiles", false for "sd". sizemode Sets the upper and lower bound for the boxes quartiles means box is drawn between Q1 and Q3 SD means the box is drawn between Mean +- Standard Deviation Argument sdmultiple (default 1) to scale the box size So it could be drawn 1-stddev, 3-stddev etc stream :class:`plotly.graph_objects.box.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.box.Unselected` instance or dict with compatible properties upperfence Sets the upper fence values. There should be as many items as the number of boxes desired. This attribute has effect only under the q1/median/q3 signature. If `upperfence` is not provided but a sample (in `y` or `x`) is set, we compute the upper as the last sample point above 1.5 times the IQR. upperfencesrc Sets the source reference on Chart Studio Cloud for `upperfence`. 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). whiskerwidth Sets the width of the whiskers relative to the box width. For example, with 1, the whiskers are as wide as the box(es). width Sets the width of the box in data coordinate If 0 (default value) the width is automatically selected based on the positions of other box 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. xcalendar Sets the calendar system to use with `x` date data. 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 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. ycalendar Sets the calendar system to use with `y` date data. 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`. 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. Returns ------- Figure """ from plotly.graph_objs import Box new_trace = Box( alignmentgroup=alignmentgroup, boxmean=boxmean, boxpoints=boxpoints, customdata=customdata, customdatasrc=customdatasrc, dx=dx, dy=dy, fillcolor=fillcolor, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hoveron=hoveron, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, jitter=jitter, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, line=line, lowerfence=lowerfence, lowerfencesrc=lowerfencesrc, marker=marker, mean=mean, meansrc=meansrc, median=median, mediansrc=mediansrc, meta=meta, metasrc=metasrc, name=name, notched=notched, notchspan=notchspan, notchspansrc=notchspansrc, notchwidth=notchwidth, offsetgroup=offsetgroup, opacity=opacity, orientation=orientation, pointpos=pointpos, q1=q1, q1src=q1src, q3=q3, q3src=q3src, quartilemethod=quartilemethod, sd=sd, sdmultiple=sdmultiple, sdsrc=sdsrc, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, showwhiskers=showwhiskers, sizemode=sizemode, stream=stream, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, unselected=unselected, upperfence=upperfence, upperfencesrc=upperfencesrc, visible=visible, whiskerwidth=whiskerwidth, width=width, x=x, x0=x0, xaxis=xaxis, xcalendar=xcalendar, xhoverformat=xhoverformat, xperiod=xperiod, xperiod0=xperiod0, xperiodalignment=xperiodalignment, xsrc=xsrc, y=y, y0=y0, yaxis=yaxis, ycalendar=ycalendar, yhoverformat=yhoverformat, yperiod=yperiod, yperiod0=yperiod0, yperiodalignment=yperiodalignment, ysrc=ysrc, zorder=zorder, **kwargs, ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_candlestick( self, close=None, closesrc=None, customdata=None, customdatasrc=None, decreasing=None, high=None, highsrc=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, increasing=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, line=None, low=None, lowsrc=None, meta=None, metasrc=None, name=None, opacity=None, open=None, opensrc=None, selectedpoints=None, showlegend=None, stream=None, text=None, textsrc=None, uid=None, uirevision=None, visible=None, whiskerwidth=None, x=None, xaxis=None, xcalendar=None, xhoverformat=None, xperiod=None, xperiod0=None, xperiodalignment=None, xsrc=None, yaxis=None, yhoverformat=None, zorder=None, row=None, col=None, secondary_y=None, **kwargs, ) -> "Figure": """ Add a new Candlestick trace The candlestick is a style of financial chart describing open, high, low and close for a given `x` coordinate (most likely time). The boxes represent the spread between the `open` and `close` values and the lines represent the spread between the `low` and `high` values Sample points where the close value is higher (lower) then the open value are called increasing (decreasing). By default, increasing candles are drawn in green whereas decreasing are drawn in red. Parameters ---------- close Sets the close values. closesrc Sets the source reference on Chart Studio Cloud for `close`. 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.candlestick.Decreasing` instance or dict with compatible properties high Sets the high values. highsrc Sets the source reference on Chart Studio Cloud for `high`. 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.candlestick.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `open`, `high`, `low` and `close`. 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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`. increasing :class:`plotly.graph_objects.candlestick.Increasing` 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. 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.candlestick.Legendgrouptit le` 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.candlestick.Line` instance or dict with compatible properties low Sets the low values. lowsrc Sets the source reference on Chart Studio Cloud for `low`. 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. open Sets the open values. opensrc Sets the source reference on Chart Studio Cloud for `open`. 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.candlestick.Stream` instance or dict with compatible properties text Sets hover text elements associated with each sample point. 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 this trace's sample points. 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. 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). whiskerwidth Sets the width of the whiskers relative to the box width. For example, with 1, the whiskers are as wide as the box(es). x Sets the x coordinates. If absent, linear coordinate will be generated. 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. xcalendar Sets the calendar system to use with `x` date data. 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`. 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`. 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`. 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. Returns ------- Figure """ from plotly.graph_objs import Candlestick new_trace = Candlestick( close=close, closesrc=closesrc, customdata=customdata, customdatasrc=customdatasrc, decreasing=decreasing, high=high, highsrc=highsrc, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, increasing=increasing, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, line=line, low=low, lowsrc=lowsrc, meta=meta, metasrc=metasrc, name=name, opacity=opacity, open=open, opensrc=opensrc, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, visible=visible, whiskerwidth=whiskerwidth, x=x, xaxis=xaxis, xcalendar=xcalendar, xhoverformat=xhoverformat, xperiod=xperiod, xperiod0=xperiod0, xperiodalignment=xperiodalignment, xsrc=xsrc, yaxis=yaxis, yhoverformat=yhoverformat, zorder=zorder, **kwargs, ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_carpet( self, a=None, a0=None, aaxis=None, asrc=None, b=None, b0=None, baxis=None, bsrc=None, carpet=None, cheaterslope=None, color=None, customdata=None, customdatasrc=None, da=None, db=None, font=None, ids=None, idssrc=None, legend=None, legendgrouptitle=None, legendrank=None, legendwidth=None, meta=None, metasrc=None, name=None, opacity=None, stream=None, uid=None, uirevision=None, visible=None, x=None, xaxis=None, xsrc=None, y=None, yaxis=None, ysrc=None, zorder=None, row=None, col=None, secondary_y=None, **kwargs, ) -> "Figure": """ Add a new Carpet trace The data describing carpet axis layout is set in `y` and (optionally) also `x`. If only `y` is present, `x` the plot is interpreted as a cheater plot and is filled in using the `y` values. `x` and `y` may either be 2D arrays matching with each dimension matching that of `a` and `b`, or they may be 1D arrays with total length equal to that of `a` and `b`. Parameters ---------- a An array containing values of the first parameter value a0 Alternate to `a`. Builds a linear space of a coordinates. Use with `da` where `a0` is the starting coordinate and `da` the step. aaxis :class:`plotly.graph_objects.carpet.Aaxis` instance or dict with compatible properties asrc Sets the source reference on Chart Studio Cloud for `a`. b A two dimensional array of y coordinates at each carpet point. b0 Alternate to `b`. Builds a linear space of a coordinates. Use with `db` where `b0` is the starting coordinate and `db` the step. baxis :class:`plotly.graph_objects.carpet.Baxis` instance or dict with compatible properties bsrc Sets the source reference on Chart Studio Cloud for `b`. carpet An identifier for this carpet, so that `scattercarpet` and `contourcarpet` traces can specify a carpet plot on which they lie cheaterslope The shift applied to each successive row of data in creating a cheater plot. Only used if `x` is been omitted. 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. 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`. da Sets the a coordinate step. See `a0` for more info. db Sets the b coordinate step. See `b0` for more info. font The default font used for axis & tick labels on this carpet 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.carpet.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. 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. stream :class:`plotly.graph_objects.carpet.Stream` 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). x A two dimensional array of x coordinates at each carpet point. If omitted, the plot is a cheater plot and the xaxis is hidden by default. 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. xsrc Sets the source reference on Chart Studio Cloud for `x`. y A two dimensional array of y coordinates at each carpet point. 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. 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`. 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. Returns ------- Figure """ from plotly.graph_objs import Carpet new_trace = Carpet( a=a, a0=a0, aaxis=aaxis, asrc=asrc, b=b, b0=b0, baxis=baxis, bsrc=bsrc, carpet=carpet, cheaterslope=cheaterslope, color=color, customdata=customdata, customdatasrc=customdatasrc, da=da, db=db, font=font, ids=ids, idssrc=idssrc, legend=legend, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, meta=meta, metasrc=metasrc, name=name, opacity=opacity, stream=stream, uid=uid, uirevision=uirevision, visible=visible, x=x, xaxis=xaxis, xsrc=xsrc, y=y, yaxis=yaxis, ysrc=ysrc, zorder=zorder, **kwargs, ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_choropleth( self, autocolorscale=None, coloraxis=None, colorbar=None, colorscale=None, customdata=None, customdatasrc=None, featureidkey=None, geo=None, geojson=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, locationmode=None, locations=None, locationssrc=None, marker=None, meta=None, metasrc=None, name=None, reversescale=None, selected=None, selectedpoints=None, showlegend=None, showscale=None, stream=None, text=None, textsrc=None, uid=None, uirevision=None, unselected=None, visible=None, z=None, zauto=None, zmax=None, zmid=None, zmin=None, zsrc=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Choropleth trace The data that describes the choropleth value-to-color mapping is set in `z`. The geographic locations corresponding to each value in `z` are set in `locations`. Parameters ---------- 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. 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.choropleth.ColorBar` 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 `zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,C ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd. 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`. featureidkey Sets the key in GeoJSON features which is used as id to match the items included in the `locations` array. Only has an effect when `geojson` is set. Support nested property, for example "properties.name". geo Sets a reference between this trace's geospatial coordinates and a geographic map. If "geo" (the default value), the geospatial coordinates refer to `layout.geo`. If "geo2", the geospatial coordinates refer to `layout.geo2`, and so on. geojson Sets optional GeoJSON data associated with this trace. If not given, the features on the base map are used. It can be set as a valid GeoJSON object or as a URL string. Note that we only accept GeoJSONs of type "FeatureCollection" or "Feature" with geometries of type "Polygon" or "MultiPolygon". 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.choropleth.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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.choropleth.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. locationmode The library used by the *country names* `locationmode` option is changing in an upcoming version. Country names in existing plots may not work in the new version. Determines the set of locations used to match entries in `locations` to regions on the map. Values "ISO-3", "USA-states", *country names* correspond to features on the base map and value "geojson-id" corresponds to features from a custom GeoJSON linked to the `geojson` attribute. locations Sets the coordinates via location IDs or names. See `locationmode` for more info. locationssrc Sets the source reference on Chart Studio Cloud for `locations`. marker :class:`plotly.graph_objects.choropleth.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. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. selected :class:`plotly.graph_objects.choropleth.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. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.choropleth.Stream` instance or dict with compatible properties text Sets the text elements associated with each location. 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.choropleth.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). z Sets the color values. zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. zsrc Sets the source reference on Chart Studio Cloud for `z`. 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). Returns ------- Figure """ from plotly.graph_objs import Choropleth new_trace = Choropleth( autocolorscale=autocolorscale, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, customdata=customdata, customdatasrc=customdatasrc, featureidkey=featureidkey, geo=geo, geojson=geojson, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, locationmode=locationmode, locations=locations, locationssrc=locationssrc, marker=marker, meta=meta, metasrc=metasrc, name=name, reversescale=reversescale, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, showscale=showscale, stream=stream, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, z=z, zauto=zauto, zmax=zmax, zmid=zmid, zmin=zmin, zsrc=zsrc, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_choroplethmap( self, autocolorscale=None, below=None, coloraxis=None, colorbar=None, colorscale=None, customdata=None, customdatasrc=None, featureidkey=None, geojson=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, locations=None, locationssrc=None, marker=None, meta=None, metasrc=None, name=None, reversescale=None, selected=None, selectedpoints=None, showlegend=None, showscale=None, stream=None, subplot=None, text=None, textsrc=None, uid=None, uirevision=None, unselected=None, visible=None, z=None, zauto=None, zmax=None, zmid=None, zmin=None, zsrc=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Choroplethmap trace GeoJSON features to be filled are set in `geojson` The data that describes the choropleth value-to-color mapping is set in `locations` and `z`. Parameters ---------- 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. below Determines if the choropleth polygons will be inserted before the layer with the specified ID. By default, choroplethmap traces are placed above the water layers. If set to '', the layer will be inserted above every existing layer. 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.choroplethmap.ColorBar` 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 `zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,C ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd. 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`. featureidkey Sets the key in GeoJSON features which is used as id to match the items included in the `locations` array. Support nested property, for example "properties.name". geojson Sets the GeoJSON data associated with this trace. It can be set as a valid GeoJSON object or as a URL string. Note that we only accept GeoJSONs of type "FeatureCollection" or "Feature" with geometries of type "Polygon" or "MultiPolygon". 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.choroplethmap.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variable `properties` 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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.choroplethmap.Legendgroupt itle` 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. locations Sets which features found in "geojson" to plot using their feature `id` field. locationssrc Sets the source reference on Chart Studio Cloud for `locations`. marker :class:`plotly.graph_objects.choroplethmap.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. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. selected :class:`plotly.graph_objects.choroplethmap.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. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.choroplethmap.Stream` instance or dict with compatible properties subplot Sets a reference between this trace's data coordinates and a map subplot. If "map" (the default value), the data refer to `layout.map`. If "map2", the data refer to `layout.map2`, and so on. text Sets the text elements associated with each location. 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.choroplethmap.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). z Sets the color values. zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. zsrc Sets the source reference on Chart Studio Cloud for `z`. 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). Returns ------- Figure """ from plotly.graph_objs import Choroplethmap new_trace = Choroplethmap( autocolorscale=autocolorscale, below=below, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, customdata=customdata, customdatasrc=customdatasrc, featureidkey=featureidkey, geojson=geojson, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, locations=locations, locationssrc=locationssrc, marker=marker, meta=meta, metasrc=metasrc, name=name, reversescale=reversescale, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, showscale=showscale, stream=stream, subplot=subplot, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, z=z, zauto=zauto, zmax=zmax, zmid=zmid, zmin=zmin, zsrc=zsrc, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_choroplethmapbox( self, autocolorscale=None, below=None, coloraxis=None, colorbar=None, colorscale=None, customdata=None, customdatasrc=None, featureidkey=None, geojson=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, locations=None, locationssrc=None, marker=None, meta=None, metasrc=None, name=None, reversescale=None, selected=None, selectedpoints=None, showlegend=None, showscale=None, stream=None, subplot=None, text=None, textsrc=None, uid=None, uirevision=None, unselected=None, visible=None, z=None, zauto=None, zmax=None, zmid=None, zmin=None, zsrc=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Choroplethmapbox trace "choroplethmapbox" trace is deprecated! Please consider switching to the "choroplethmap" trace type and `map` subplots. Learn more at: https://plotly.com/python/maplibre-migration/ as well as https://plotly.com/javascript/maplibre-migration/ GeoJSON features to be filled are set in `geojson` The data that describes the choropleth value-to-color mapping is set in `locations` and `z`. Parameters ---------- 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. below Determines if the choropleth polygons will be inserted before the layer with the specified ID. By default, choroplethmapbox traces are placed above the water layers. If set to '', the layer will be inserted above every existing layer. 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.choroplethmapbox.ColorBar` 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 `zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,C ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd. 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`. featureidkey Sets the key in GeoJSON features which is used as id to match the items included in the `locations` array. Support nested property, for example "properties.name". geojson Sets the GeoJSON data associated with this trace. It can be set as a valid GeoJSON object or as a URL string. Note that we only accept GeoJSONs of type "FeatureCollection" or "Feature" with geometries of type "Polygon" or "MultiPolygon". 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.choroplethmapbox.Hoverlabe l` 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variable `properties` 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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.choroplethmapbox.Legendgro uptitle` 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. locations Sets which features found in "geojson" to plot using their feature `id` field. locationssrc Sets the source reference on Chart Studio Cloud for `locations`. marker :class:`plotly.graph_objects.choroplethmapbox.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. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. selected :class:`plotly.graph_objects.choroplethmapbox.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. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.choroplethmapbox.Stream` instance or dict with compatible properties subplot mapbox subplots and traces are deprecated! Please consider switching to `map` subplots and traces. Learn more at: https://plotly.com/python/maplibre-migration/ as well as https://plotly.com/javascript/maplibre- migration/ Sets a reference between this trace's data coordinates and a mapbox subplot. If "mapbox" (the default value), the data refer to `layout.mapbox`. If "mapbox2", the data refer to `layout.mapbox2`, and so on. text Sets the text elements associated with each location. 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.choroplethmapbox.Unselecte d` 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). z Sets the color values. zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. zsrc Sets the source reference on Chart Studio Cloud for `z`. 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). Returns ------- Figure """ from plotly.graph_objs import Choroplethmapbox new_trace = Choroplethmapbox( autocolorscale=autocolorscale, below=below, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, customdata=customdata, customdatasrc=customdatasrc, featureidkey=featureidkey, geojson=geojson, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, locations=locations, locationssrc=locationssrc, marker=marker, meta=meta, metasrc=metasrc, name=name, reversescale=reversescale, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, showscale=showscale, stream=stream, subplot=subplot, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, z=z, zauto=zauto, zmax=zmax, zmid=zmid, zmin=zmin, zsrc=zsrc, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_cone( self, anchor=None, autocolorscale=None, cauto=None, cmax=None, cmid=None, cmin=None, coloraxis=None, colorbar=None, colorscale=None, customdata=None, customdatasrc=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, lighting=None, lightposition=None, meta=None, metasrc=None, name=None, opacity=None, reversescale=None, scene=None, showlegend=None, showscale=None, sizemode=None, sizeref=None, stream=None, text=None, textsrc=None, u=None, uhoverformat=None, uid=None, uirevision=None, usrc=None, v=None, vhoverformat=None, visible=None, vsrc=None, w=None, whoverformat=None, wsrc=None, x=None, xhoverformat=None, xsrc=None, y=None, yhoverformat=None, ysrc=None, z=None, zhoverformat=None, zsrc=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Cone trace Use cone traces to visualize vector fields. Specify a vector field using 6 1D arrays, 3 position arrays `x`, `y` and `z` and 3 vector component arrays `u`, `v`, `w`. The cones are drawn exactly at the positions given by `x`, `y` and `z`. Parameters ---------- anchor Sets the cones' anchor with respect to their x/y/z positions. Note that "cm" denote the cone's center of mass which corresponds to 1/4 from the tail to tip. 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 u/v/w norm) 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 u/v/w norm 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 u/v/w norm. Has no effect when `cauto` is `false`. cmin Sets the lower bound of the color domain. Value should have the same units as u/v/w norm and if set, `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.cone.ColorBar` 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: Blackbody,Bluered,Blues,C ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd. 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`. 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.cone.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variable `norm` 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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.cone.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. lighting :class:`plotly.graph_objects.cone.Lighting` instance or dict with compatible properties lightposition :class:`plotly.graph_objects.cone.Lightposition` 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 surface. Please note that in the case of using high `opacity` values for example a value greater than or equal to 0.5 on two surfaces (and 0.25 with four surfaces), an overlay of multiple transparent surfaces may not perfectly be sorted in depth by the webgl API. This behavior may be improved in the near future and is subject to change. 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. scene Sets a reference between this trace's 3D coordinate system and a 3D scene. If "scene" (the default value), the (x,y,z) coordinates refer to `layout.scene`. If "scene2", the (x,y,z) coordinates refer to `layout.scene2`, and so on. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. sizemode Determines whether `sizeref` is set as a "scaled" (i.e unitless) scalar (normalized by the max u/v/w norm in the vector field) or as "absolute" value (in the same units as the vector field). To display sizes in actual vector length use "raw". sizeref Adjusts the cone size scaling. The size of the cones is determined by their u/v/w norm multiplied a factor and `sizeref`. This factor (computed internally) corresponds to the minimum "time" to travel across two successive x/y/z positions at the average velocity of those two successive positions. All cones in a given trace use the same factor. With `sizemode` set to "raw", its default value is 1. With `sizemode` set to "scaled", `sizeref` is unitless, its default value is 0.5. With `sizemode` set to "absolute", `sizeref` has the same units as the u/v/w vector field, its the default value is half the sample's maximum vector norm. stream :class:`plotly.graph_objects.cone.Stream` instance or dict with compatible properties text Sets the text elements associated with the cones. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textsrc Sets the source reference on Chart Studio Cloud for `text`. u Sets the x components of the vector field. uhoverformat Sets the hover text formatting rulefor `u` using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d 3/d3-format/tree/v1.4.5#d3-format.By default the values are formatted using generic number format. 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. usrc Sets the source reference on Chart Studio Cloud for `u`. v Sets the y components of the vector field. vhoverformat Sets the hover text formatting rulefor `v` using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d 3/d3-format/tree/v1.4.5#d3-format.By default the values are formatted using generic number format. 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). vsrc Sets the source reference on Chart Studio Cloud for `v`. w Sets the z components of the vector field. whoverformat Sets the hover text formatting rulefor `w` using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d 3/d3-format/tree/v1.4.5#d3-format.By default the values are formatted using generic number format. wsrc Sets the source reference on Chart Studio Cloud for `w`. x Sets the x coordinates of the vector field and of the displayed cones. 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 coordinates of the vector field and of the displayed cones. 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`. z Sets the z coordinates of the vector field and of the displayed cones. zhoverformat Sets the hover text formatting rulefor `z` 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 `zaxis.hoverformat`. zsrc Sets the source reference on Chart Studio Cloud for `z`. 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). Returns ------- Figure """ from plotly.graph_objs import Cone new_trace = Cone( anchor=anchor, autocolorscale=autocolorscale, cauto=cauto, cmax=cmax, cmid=cmid, cmin=cmin, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, customdata=customdata, customdatasrc=customdatasrc, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, lighting=lighting, lightposition=lightposition, meta=meta, metasrc=metasrc, name=name, opacity=opacity, reversescale=reversescale, scene=scene, showlegend=showlegend, showscale=showscale, sizemode=sizemode, sizeref=sizeref, stream=stream, text=text, textsrc=textsrc, u=u, uhoverformat=uhoverformat, uid=uid, uirevision=uirevision, usrc=usrc, v=v, vhoverformat=vhoverformat, visible=visible, vsrc=vsrc, w=w, whoverformat=whoverformat, wsrc=wsrc, x=x, xhoverformat=xhoverformat, xsrc=xsrc, y=y, yhoverformat=yhoverformat, ysrc=ysrc, z=z, zhoverformat=zhoverformat, zsrc=zsrc, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_contour( self, autocolorscale=None, autocontour=None, coloraxis=None, colorbar=None, colorscale=None, connectgaps=None, contours=None, customdata=None, customdatasrc=None, dx=None, dy=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hoverongaps=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, line=None, meta=None, metasrc=None, name=None, ncontours=None, opacity=None, reversescale=None, showlegend=None, showscale=None, stream=None, text=None, textfont=None, textsrc=None, texttemplate=None, texttemplatefallback=None, transpose=None, uid=None, uirevision=None, visible=None, x=None, x0=None, xaxis=None, xcalendar=None, xhoverformat=None, xperiod=None, xperiod0=None, xperiodalignment=None, xsrc=None, xtype=None, y=None, y0=None, yaxis=None, ycalendar=None, yhoverformat=None, yperiod=None, yperiod0=None, yperiodalignment=None, ysrc=None, ytype=None, z=None, zauto=None, zhoverformat=None, zmax=None, zmid=None, zmin=None, zorder=None, zsrc=None, row=None, col=None, secondary_y=None, **kwargs, ) -> "Figure": """ Add a new Contour trace The data from which contour lines are computed is set in `z`. Data in `z` must be a 2D list of numbers. Say that `z` has N rows and M columns, then by default, these N rows correspond to N y coordinates (set in `y` or auto-generated) and the M columns correspond to M x coordinates (set in `x` or auto- generated). By setting `transpose` to True, the above behavior is flipped. Parameters ---------- 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. autocontour Determines whether or not the contour level attributes are picked by an algorithm. If True, the number of contour levels can be set in `ncontours`. If False, set the contour level attributes in `contours`. 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.contour.ColorBar` 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 `zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,C ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd. connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data are filled in. It is defaulted to true if `z` is a one dimensional array otherwise it is defaulted to false. contours :class:`plotly.graph_objects.contour.Contours` 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`. dx Sets the x coordinate step. See `x0` for more info. dy Sets the y coordinate step. See `y0` for more info. fillcolor Sets the fill color if `contours.type` is "constraint". 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.contour.Hoverlabel` instance or dict with compatible properties hoverongaps Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data have hover labels associated with 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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.contour.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.contour.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. ncontours Sets the maximum number of contour levels. The actual number of contours will be chosen automatically to be less than or equal to the value of `ncontours`. Has an effect only if `autocontour` is True or if `contours.size` is missing. opacity Sets the opacity of the trace. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.contour.Stream` instance or dict with compatible properties text Sets the text elements associated with each z value. textfont For this trace it only has an effect if `coloring` is set to "heatmap". Sets the text font. textsrc Sets the source reference on Chart Studio Cloud for `text`. texttemplate For this trace it only has an effect if `coloring` is set to "heatmap". Template string used for rendering the information text that appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `x`, `y`, `z` and `text`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. transpose Transposes the z data. 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). 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. xcalendar Sets the calendar system to use with `x` date data. 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`. xtype If "array", the heatmap's x coordinates are given by "x" (the default behavior when `x` is provided). If "scaled", the heatmap's x coordinates are given by "x0" and "dx" (the default behavior when `x` is not provided). 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. ycalendar Sets the calendar system to use with `y` date data. 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`. ytype If "array", the heatmap's y coordinates are given by "y" (the default behavior when `y` is provided) If "scaled", the heatmap's y coordinates are given by "y0" and "dy" (the default behavior when `y` is not provided) z Sets the z data. zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zhoverformat Sets the hover text formatting rulefor `z` using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d 3/d3-format/tree/v1.4.5#d3-format.By default the values are formatted using generic number format. zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. 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`. zsrc Sets the source reference on Chart Studio Cloud for `z`. 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. Returns ------- Figure """ from plotly.graph_objs import Contour new_trace = Contour( autocolorscale=autocolorscale, autocontour=autocontour, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, connectgaps=connectgaps, contours=contours, customdata=customdata, customdatasrc=customdatasrc, dx=dx, dy=dy, fillcolor=fillcolor, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hoverongaps=hoverongaps, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, line=line, meta=meta, metasrc=metasrc, name=name, ncontours=ncontours, opacity=opacity, reversescale=reversescale, showlegend=showlegend, showscale=showscale, stream=stream, text=text, textfont=textfont, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, transpose=transpose, uid=uid, uirevision=uirevision, visible=visible, x=x, x0=x0, xaxis=xaxis, xcalendar=xcalendar, xhoverformat=xhoverformat, xperiod=xperiod, xperiod0=xperiod0, xperiodalignment=xperiodalignment, xsrc=xsrc, xtype=xtype, y=y, y0=y0, yaxis=yaxis, ycalendar=ycalendar, yhoverformat=yhoverformat, yperiod=yperiod, yperiod0=yperiod0, yperiodalignment=yperiodalignment, ysrc=ysrc, ytype=ytype, z=z, zauto=zauto, zhoverformat=zhoverformat, zmax=zmax, zmid=zmid, zmin=zmin, zorder=zorder, zsrc=zsrc, **kwargs, ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_contourcarpet( self, a=None, a0=None, asrc=None, atype=None, autocolorscale=None, autocontour=None, b=None, b0=None, bsrc=None, btype=None, carpet=None, coloraxis=None, colorbar=None, colorscale=None, contours=None, customdata=None, customdatasrc=None, da=None, db=None, fillcolor=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, line=None, meta=None, metasrc=None, name=None, ncontours=None, opacity=None, reversescale=None, showlegend=None, showscale=None, stream=None, text=None, textsrc=None, transpose=None, uid=None, uirevision=None, visible=None, xaxis=None, yaxis=None, z=None, zauto=None, zmax=None, zmid=None, zmin=None, zorder=None, zsrc=None, row=None, col=None, secondary_y=None, **kwargs, ) -> "Figure": """ Add a new Contourcarpet trace Plots contours on either the first carpet axis or the carpet axis with a matching `carpet` attribute. Data `z` is interpreted as matching that of the corresponding carpet axis. Parameters ---------- a Sets the x coordinates. a0 Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step. asrc Sets the source reference on Chart Studio Cloud for `a`. atype If "array", the heatmap's x coordinates are given by "x" (the default behavior when `x` is provided). If "scaled", the heatmap's x coordinates are given by "x0" and "dx" (the default behavior when `x` is not provided). 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. autocontour Determines whether or not the contour level attributes are picked by an algorithm. If True, the number of contour levels can be set in `ncontours`. If False, set the contour level attributes in `contours`. b Sets the y coordinates. b0 Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step. bsrc Sets the source reference on Chart Studio Cloud for `b`. btype If "array", the heatmap's y coordinates are given by "y" (the default behavior when `y` is provided) If "scaled", the heatmap's y coordinates are given by "y0" and "dy" (the default behavior when `y` is not provided) carpet The `carpet` of the carpet axes on which this contour trace lies 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.contourcarpet.ColorBar` 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 `zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,C ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd. contours :class:`plotly.graph_objects.contourcarpet.Contours` 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`. da Sets the x coordinate step. See `x0` for more info. db Sets the y coordinate step. See `y0` for more info. fillcolor Sets the fill color if `contours.type` is "constraint". Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. 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.contourcarpet.Legendgroupt itle` 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.contourcarpet.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. ncontours Sets the maximum number of contour levels. The actual number of contours will be chosen automatically to be less than or equal to the value of `ncontours`. Has an effect only if `autocontour` is True or if `contours.size` is missing. opacity Sets the opacity of the trace. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.contourcarpet.Stream` instance or dict with compatible properties text Sets the text elements associated with each z value. textsrc Sets the source reference on Chart Studio Cloud for `text`. transpose Transposes the z data. 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). 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. 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. z Sets the z data. zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. 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`. zsrc Sets the source reference on Chart Studio Cloud for `z`. 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. Returns ------- Figure """ from plotly.graph_objs import Contourcarpet new_trace = Contourcarpet( a=a, a0=a0, asrc=asrc, atype=atype, autocolorscale=autocolorscale, autocontour=autocontour, b=b, b0=b0, bsrc=bsrc, btype=btype, carpet=carpet, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, contours=contours, customdata=customdata, customdatasrc=customdatasrc, da=da, db=db, fillcolor=fillcolor, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, line=line, meta=meta, metasrc=metasrc, name=name, ncontours=ncontours, opacity=opacity, reversescale=reversescale, showlegend=showlegend, showscale=showscale, stream=stream, text=text, textsrc=textsrc, transpose=transpose, uid=uid, uirevision=uirevision, visible=visible, xaxis=xaxis, yaxis=yaxis, z=z, zauto=zauto, zmax=zmax, zmid=zmid, zmin=zmin, zorder=zorder, zsrc=zsrc, **kwargs, ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_densitymap( self, autocolorscale=None, below=None, coloraxis=None, colorbar=None, colorscale=None, customdata=None, customdatasrc=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, lat=None, latsrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, lon=None, lonsrc=None, meta=None, metasrc=None, name=None, opacity=None, radius=None, radiussrc=None, reversescale=None, showlegend=None, showscale=None, stream=None, subplot=None, text=None, textsrc=None, uid=None, uirevision=None, visible=None, z=None, zauto=None, zmax=None, zmid=None, zmin=None, zsrc=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Densitymap trace Draws a bivariate kernel density estimation with a Gaussian kernel from `lon` and `lat` coordinates and optional `z` values using a colorscale. Parameters ---------- 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. below Determines if the densitymap trace will be inserted before the layer with the specified ID. By default, densitymap traces are placed below the first layer of type symbol If set to '', the layer will be inserted above every existing layer. 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.densitymap.ColorBar` 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 `zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,C ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd. 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`. 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.densitymap.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. hovertemplatesrc Sets the source reference on Chart Studio Cloud for `hovertemplate`. hovertext Sets hover text elements associated with each (lon,lat) 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 (lon,lat) 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`. lat Sets the latitude coordinates (in degrees North). latsrc Sets the source reference on Chart Studio Cloud for `lat`. 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.densitymap.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. lon Sets the longitude coordinates (in degrees East). lonsrc Sets the source reference on Chart Studio Cloud for `lon`. 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. radius Sets the radius of influence of one `lon` / `lat` point in pixels. Increasing the value makes the densitymap trace smoother, but less detailed. radiussrc Sets the source reference on Chart Studio Cloud for `radius`. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.densitymap.Stream` instance or dict with compatible properties subplot Sets a reference between this trace's data coordinates and a map subplot. If "map" (the default value), the data refer to `layout.map`. If "map2", the data refer to `layout.map2`, and so on. text Sets text elements associated with each (lon,lat) 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 (lon,lat) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. 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. 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). z Sets the points' weight. For example, a value of 10 would be equivalent to having 10 points of weight 1 in the same spot zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. zsrc Sets the source reference on Chart Studio Cloud for `z`. 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). Returns ------- Figure """ from plotly.graph_objs import Densitymap new_trace = Densitymap( autocolorscale=autocolorscale, below=below, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, customdata=customdata, customdatasrc=customdatasrc, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, lat=lat, latsrc=latsrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, lon=lon, lonsrc=lonsrc, meta=meta, metasrc=metasrc, name=name, opacity=opacity, radius=radius, radiussrc=radiussrc, reversescale=reversescale, showlegend=showlegend, showscale=showscale, stream=stream, subplot=subplot, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, visible=visible, z=z, zauto=zauto, zmax=zmax, zmid=zmid, zmin=zmin, zsrc=zsrc, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_densitymapbox( self, autocolorscale=None, below=None, coloraxis=None, colorbar=None, colorscale=None, customdata=None, customdatasrc=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, lat=None, latsrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, lon=None, lonsrc=None, meta=None, metasrc=None, name=None, opacity=None, radius=None, radiussrc=None, reversescale=None, showlegend=None, showscale=None, stream=None, subplot=None, text=None, textsrc=None, uid=None, uirevision=None, visible=None, z=None, zauto=None, zmax=None, zmid=None, zmin=None, zsrc=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Densitymapbox trace "densitymapbox" trace is deprecated! Please consider switching to the "densitymap" trace type and `map` subplots. Learn more at: https://plotly.com/python/maplibre-migration/ as well as https://plotly.com/javascript/maplibre-migration/ Draws a bivariate kernel density estimation with a Gaussian kernel from `lon` and `lat` coordinates and optional `z` values using a colorscale. Parameters ---------- 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. below Determines if the densitymapbox trace will be inserted before the layer with the specified ID. By default, densitymapbox traces are placed below the first layer of type symbol If set to '', the layer will be inserted above every existing layer. 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.densitymapbox.ColorBar` 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 `zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,C ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd. 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`. 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.densitymapbox.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. hovertemplatesrc Sets the source reference on Chart Studio Cloud for `hovertemplate`. hovertext Sets hover text elements associated with each (lon,lat) 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 (lon,lat) 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`. lat Sets the latitude coordinates (in degrees North). latsrc Sets the source reference on Chart Studio Cloud for `lat`. 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.densitymapbox.Legendgroupt itle` 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. lon Sets the longitude coordinates (in degrees East). lonsrc Sets the source reference on Chart Studio Cloud for `lon`. 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. radius Sets the radius of influence of one `lon` / `lat` point in pixels. Increasing the value makes the densitymapbox trace smoother, but less detailed. radiussrc Sets the source reference on Chart Studio Cloud for `radius`. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.densitymapbox.Stream` instance or dict with compatible properties subplot mapbox subplots and traces are deprecated! Please consider switching to `map` subplots and traces. Learn more at: https://plotly.com/python/maplibre-migration/ as well as https://plotly.com/javascript/maplibre- migration/ Sets a reference between this trace's data coordinates and a mapbox subplot. If "mapbox" (the default value), the data refer to `layout.mapbox`. If "mapbox2", the data refer to `layout.mapbox2`, and so on. text Sets text elements associated with each (lon,lat) 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 (lon,lat) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. 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. 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). z Sets the points' weight. For example, a value of 10 would be equivalent to having 10 points of weight 1 in the same spot zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. zsrc Sets the source reference on Chart Studio Cloud for `z`. 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). Returns ------- Figure """ from plotly.graph_objs import Densitymapbox new_trace = Densitymapbox( autocolorscale=autocolorscale, below=below, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, customdata=customdata, customdatasrc=customdatasrc, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, lat=lat, latsrc=latsrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, lon=lon, lonsrc=lonsrc, meta=meta, metasrc=metasrc, name=name, opacity=opacity, radius=radius, radiussrc=radiussrc, reversescale=reversescale, showlegend=showlegend, showscale=showscale, stream=stream, subplot=subplot, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, visible=visible, z=z, zauto=zauto, zmax=zmax, zmid=zmid, zmin=zmin, zsrc=zsrc, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_funnel( self, alignmentgroup=None, cliponaxis=None, connector=None, constraintext=None, customdata=None, customdatasrc=None, dx=None, dy=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=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, texttemplatefallback=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, row=None, col=None, secondary_y=None, **kwargs, ) -> "Figure": """ Add a new Funnel trace 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 ---------- 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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 appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All 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`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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`. 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. Returns ------- Figure """ from plotly.graph_objs import Funnel new_trace = Funnel( alignmentgroup=alignmentgroup, cliponaxis=cliponaxis, connector=connector, constraintext=constraintext, customdata=customdata, customdatasrc=customdatasrc, dx=dx, dy=dy, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, insidetextanchor=insidetextanchor, insidetextfont=insidetextfont, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, marker=marker, meta=meta, metasrc=metasrc, name=name, offset=offset, offsetgroup=offsetgroup, opacity=opacity, orientation=orientation, outsidetextfont=outsidetextfont, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, text=text, textangle=textangle, textfont=textfont, textinfo=textinfo, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, texttemplatesrc=texttemplatesrc, uid=uid, uirevision=uirevision, visible=visible, width=width, x=x, x0=x0, xaxis=xaxis, xhoverformat=xhoverformat, xperiod=xperiod, xperiod0=xperiod0, xperiodalignment=xperiodalignment, xsrc=xsrc, y=y, y0=y0, yaxis=yaxis, yhoverformat=yhoverformat, yperiod=yperiod, yperiod0=yperiod0, yperiodalignment=yperiodalignment, ysrc=ysrc, zorder=zorder, **kwargs, ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_funnelarea( self, aspectratio=None, baseratio=None, customdata=None, customdatasrc=None, dlabel=None, domain=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=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, texttemplatefallback=None, texttemplatesrc=None, title=None, uid=None, uirevision=None, values=None, valuessrc=None, visible=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Funnelarea trace 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 ---------- 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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 appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All 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`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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). 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). Returns ------- Figure """ from plotly.graph_objs import Funnelarea new_trace = Funnelarea( aspectratio=aspectratio, baseratio=baseratio, customdata=customdata, customdatasrc=customdatasrc, dlabel=dlabel, domain=domain, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, insidetextfont=insidetextfont, label0=label0, labels=labels, labelssrc=labelssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, marker=marker, meta=meta, metasrc=metasrc, name=name, opacity=opacity, scalegroup=scalegroup, showlegend=showlegend, stream=stream, text=text, textfont=textfont, textinfo=textinfo, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, texttemplatesrc=texttemplatesrc, title=title, uid=uid, uirevision=uirevision, values=values, valuessrc=valuessrc, visible=visible, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_heatmap( self, autocolorscale=None, coloraxis=None, colorbar=None, colorscale=None, connectgaps=None, customdata=None, customdatasrc=None, dx=None, dy=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hoverongaps=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, meta=None, metasrc=None, name=None, opacity=None, reversescale=None, showlegend=None, showscale=None, stream=None, text=None, textfont=None, textsrc=None, texttemplate=None, texttemplatefallback=None, transpose=None, uid=None, uirevision=None, visible=None, x=None, x0=None, xaxis=None, xcalendar=None, xgap=None, xhoverformat=None, xperiod=None, xperiod0=None, xperiodalignment=None, xsrc=None, xtype=None, y=None, y0=None, yaxis=None, ycalendar=None, ygap=None, yhoverformat=None, yperiod=None, yperiod0=None, yperiodalignment=None, ysrc=None, ytype=None, z=None, zauto=None, zhoverformat=None, zmax=None, zmid=None, zmin=None, zorder=None, zsmooth=None, zsrc=None, row=None, col=None, secondary_y=None, **kwargs, ) -> "Figure": """ Add a new Heatmap trace The data that describes the heatmap value-to-color mapping is set in `z`. Data in `z` can either be a 2D list of values (ragged or not) or a 1D array of values. In the case where `z` is a 2D list, say that `z` has N rows and M columns. Then, by default, the resulting heatmap will have N partitions along the y axis and M partitions along the x axis. In other words, the i-th row/ j-th column cell in `z` is mapped to the i-th partition of the y axis (starting from the bottom of the plot) and the j-th partition of the x-axis (starting from the left of the plot). This behavior can be flipped by using `transpose`. Moreover, `x` (`y`) can be provided with M or M+1 (N or N+1) elements. If M (N), then the coordinates correspond to the center of the heatmap cells and the cells have equal width. If M+1 (N+1), then the coordinates correspond to the edges of the heatmap cells. In the case where `z` is a 1D list, the x and y coordinates must be provided in `x` and `y` respectively to form data triplets. Parameters ---------- 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. 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.heatmap.ColorBar` 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 `zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,C ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd. connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data are filled in. It is defaulted to true if `z` is a one dimensional array and `zsmooth` is not false; otherwise it is defaulted to false. 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.heatmap.Hoverlabel` instance or dict with compatible properties hoverongaps Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data have hover labels associated with 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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.heatmap.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. 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. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.heatmap.Stream` instance or dict with compatible properties text Sets the text elements associated with each z value. textfont Sets the text font. textsrc Sets the source reference on Chart Studio Cloud for `text`. texttemplate Template string used for rendering the information text that appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `x`, `y`, `z` and `text`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. transpose Transposes the z data. 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). 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. xcalendar Sets the calendar system to use with `x` date data. xgap Sets the horizontal gap (in pixels) between bricks. 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`. xtype If "array", the heatmap's x coordinates are given by "x" (the default behavior when `x` is provided). If "scaled", the heatmap's x coordinates are given by "x0" and "dx" (the default behavior when `x` is not provided). 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. ycalendar Sets the calendar system to use with `y` date data. ygap Sets the vertical gap (in pixels) between bricks. 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`. ytype If "array", the heatmap's y coordinates are given by "y" (the default behavior when `y` is provided) If "scaled", the heatmap's y coordinates are given by "y0" and "dy" (the default behavior when `y` is not provided) z Sets the z data. zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zhoverformat Sets the hover text formatting rulefor `z` using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d 3/d3-format/tree/v1.4.5#d3-format.By default the values are formatted using generic number format. zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. 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`. zsmooth Picks a smoothing algorithm use to smooth `z` data. zsrc Sets the source reference on Chart Studio Cloud for `z`. 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. Returns ------- Figure """ from plotly.graph_objs import Heatmap new_trace = Heatmap( autocolorscale=autocolorscale, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, connectgaps=connectgaps, customdata=customdata, customdatasrc=customdatasrc, dx=dx, dy=dy, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hoverongaps=hoverongaps, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, meta=meta, metasrc=metasrc, name=name, opacity=opacity, reversescale=reversescale, showlegend=showlegend, showscale=showscale, stream=stream, text=text, textfont=textfont, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, transpose=transpose, uid=uid, uirevision=uirevision, visible=visible, x=x, x0=x0, xaxis=xaxis, xcalendar=xcalendar, xgap=xgap, xhoverformat=xhoverformat, xperiod=xperiod, xperiod0=xperiod0, xperiodalignment=xperiodalignment, xsrc=xsrc, xtype=xtype, y=y, y0=y0, yaxis=yaxis, ycalendar=ycalendar, ygap=ygap, yhoverformat=yhoverformat, yperiod=yperiod, yperiod0=yperiod0, yperiodalignment=yperiodalignment, ysrc=ysrc, ytype=ytype, z=z, zauto=zauto, zhoverformat=zhoverformat, zmax=zmax, zmid=zmid, zmin=zmin, zorder=zorder, zsmooth=zsmooth, zsrc=zsrc, **kwargs, ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_histogram( self, alignmentgroup=None, autobinx=None, autobiny=None, bingroup=None, cliponaxis=None, constraintext=None, cumulative=None, customdata=None, customdatasrc=None, error_x=None, error_y=None, histfunc=None, histnorm=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=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, nbinsx=None, nbinsy=None, offsetgroup=None, opacity=None, orientation=None, outsidetextfont=None, selected=None, selectedpoints=None, showlegend=None, stream=None, text=None, textangle=None, textfont=None, textposition=None, textsrc=None, texttemplate=None, texttemplatefallback=None, uid=None, uirevision=None, unselected=None, visible=None, x=None, xaxis=None, xbins=None, xcalendar=None, xhoverformat=None, xsrc=None, y=None, yaxis=None, ybins=None, ycalendar=None, yhoverformat=None, ysrc=None, zorder=None, row=None, col=None, secondary_y=None, **kwargs, ) -> "Figure": """ Add a new Histogram trace The sample data from which statistics are computed is set in `x` for vertically spanning histograms and in `y` for horizontally spanning histograms. Binning options are set `xbins` and `ybins` respectively if no aggregation data is provided. Parameters ---------- 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. autobinx Obsolete: since v1.42 each bin attribute is auto- determined separately and `autobinx` is not needed. However, we accept `autobinx: true` or `false` and will update `xbins` accordingly before deleting `autobinx` from the trace. autobiny Obsolete: since v1.42 each bin attribute is auto- determined separately and `autobiny` is not needed. However, we accept `autobiny: true` or `false` and will update `ybins` accordingly before deleting `autobiny` from the trace. bingroup Set a group of histogram traces which will have compatible bin settings. Note that traces on the same subplot and with the same "orientation" under `barmode` "stack", "relative" and "group" are forced into the same bingroup, Using `bingroup`, traces under `barmode` "overlay" and on different axes (of the same axis type) can have compatible bin settings. Note that histogram and histogram2d* trace can share the same `bingroup` 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*. constraintext Constrain the size of text inside or outside a bar to be no larger than the bar itself. cumulative :class:`plotly.graph_objects.histogram.Cumulative` 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`. error_x :class:`plotly.graph_objects.histogram.ErrorX` instance or dict with compatible properties error_y :class:`plotly.graph_objects.histogram.ErrorY` instance or dict with compatible properties histfunc Specifies the binning function used for this histogram trace. If "count", the histogram values are computed by counting the number of values lying inside each bin. If "sum", "avg", "min", "max", the histogram values are computed using the sum, the average, the minimum or the maximum of the values lying inside each bin respectively. histnorm Specifies the type of normalization used for this histogram trace. If "", the span of each bar corresponds to the number of occurrences (i.e. the number of data points lying inside the bins). If "percent" / "probability", the span of each bar corresponds to the percentage / fraction of occurrences with respect to the total number of sample points (here, the sum of all bin HEIGHTS equals 100% / 1). If "density", the span of each bar corresponds to the number of occurrences in a bin divided by the size of the bin interval (here, the sum of all bin AREAS equals the total number of sample points). If *probability density*, the area of each bar corresponds to the probability that an event will fall into the corresponding bin (here, the sum of all bin AREAS equals 1). 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.histogram.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variable `binNumber` 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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`. 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.histogram.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.histogram.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. nbinsx Specifies the maximum number of desired bins. This value will be used in an algorithm that will decide the optimal bin size such that the histogram best visualizes the distribution of the data. Ignored if `xbins.size` is provided. nbinsy Specifies the maximum number of desired bins. This value will be used in an algorithm that will decide the optimal bin size such that the histogram best visualizes the distribution of the data. Ignored if `ybins.size` is provided. 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 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. selected :class:`plotly.graph_objects.histogram.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. stream :class:`plotly.graph_objects.histogram.Stream` instance or dict with compatible properties text Sets hover text elements associated with each bar. If a single string, the same string appears over all bars. If an array of string, the items are mapped in order to the this trace's coordinates. 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 text font. 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. textsrc Sets the source reference on Chart Studio Cloud for `text`. texttemplate Template string used for rendering the information text that appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `label` and `value`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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.histogram.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). x Sets the sample data to be binned on the x axis. 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. xbins :class:`plotly.graph_objects.histogram.XBins` instance or dict with compatible properties xcalendar Sets the calendar system to use with `x` date data. 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 sample data to be binned on the y axis. 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. ybins :class:`plotly.graph_objects.histogram.YBins` instance or dict with compatible properties ycalendar Sets the calendar system to use with `y` date data. 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`. 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. Returns ------- Figure """ from plotly.graph_objs import Histogram new_trace = Histogram( alignmentgroup=alignmentgroup, autobinx=autobinx, autobiny=autobiny, bingroup=bingroup, cliponaxis=cliponaxis, constraintext=constraintext, cumulative=cumulative, customdata=customdata, customdatasrc=customdatasrc, error_x=error_x, error_y=error_y, histfunc=histfunc, histnorm=histnorm, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, insidetextanchor=insidetextanchor, insidetextfont=insidetextfont, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, marker=marker, meta=meta, metasrc=metasrc, name=name, nbinsx=nbinsx, nbinsy=nbinsy, offsetgroup=offsetgroup, opacity=opacity, orientation=orientation, outsidetextfont=outsidetextfont, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, text=text, textangle=textangle, textfont=textfont, textposition=textposition, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, x=x, xaxis=xaxis, xbins=xbins, xcalendar=xcalendar, xhoverformat=xhoverformat, xsrc=xsrc, y=y, yaxis=yaxis, ybins=ybins, ycalendar=ycalendar, yhoverformat=yhoverformat, ysrc=ysrc, zorder=zorder, **kwargs, ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_histogram2d( self, autobinx=None, autobiny=None, autocolorscale=None, bingroup=None, coloraxis=None, colorbar=None, colorscale=None, customdata=None, customdatasrc=None, histfunc=None, histnorm=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, ids=None, idssrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, marker=None, meta=None, metasrc=None, name=None, nbinsx=None, nbinsy=None, opacity=None, reversescale=None, showlegend=None, showscale=None, stream=None, textfont=None, texttemplate=None, texttemplatefallback=None, uid=None, uirevision=None, visible=None, x=None, xaxis=None, xbingroup=None, xbins=None, xcalendar=None, xgap=None, xhoverformat=None, xsrc=None, y=None, yaxis=None, ybingroup=None, ybins=None, ycalendar=None, ygap=None, yhoverformat=None, ysrc=None, z=None, zauto=None, zhoverformat=None, zmax=None, zmid=None, zmin=None, zsmooth=None, zsrc=None, row=None, col=None, secondary_y=None, **kwargs, ) -> "Figure": """ Add a new Histogram2d trace The sample data from which statistics are computed is set in `x` and `y` (where `x` and `y` represent marginal distributions, binning is set in `xbins` and `ybins` in this case) or `z` (where `z` represent the 2D distribution and binning set, binning is set by `x` and `y` in this case). The resulting distribution is visualized as a heatmap. Parameters ---------- autobinx Obsolete: since v1.42 each bin attribute is auto- determined separately and `autobinx` is not needed. However, we accept `autobinx: true` or `false` and will update `xbins` accordingly before deleting `autobinx` from the trace. autobiny Obsolete: since v1.42 each bin attribute is auto- determined separately and `autobiny` is not needed. However, we accept `autobiny: true` or `false` and will update `ybins` accordingly before deleting `autobiny` from the trace. 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. bingroup Set the `xbingroup` and `ybingroup` default prefix For example, setting a `bingroup` of 1 on two histogram2d traces will make them their x-bins and y-bins match separately. 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.histogram2d.ColorBar` 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 `zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,C ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd. 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`. histfunc Specifies the binning function used for this histogram trace. If "count", the histogram values are computed by counting the number of values lying inside each bin. If "sum", "avg", "min", "max", the histogram values are computed using the sum, the average, the minimum or the maximum of the values lying inside each bin respectively. histnorm Specifies the type of normalization used for this histogram trace. If "", the span of each bar corresponds to the number of occurrences (i.e. the number of data points lying inside the bins). If "percent" / "probability", the span of each bar corresponds to the percentage / fraction of occurrences with respect to the total number of sample points (here, the sum of all bin HEIGHTS equals 100% / 1). If "density", the span of each bar corresponds to the number of occurrences in a bin divided by the size of the bin interval (here, the sum of all bin AREAS equals the total number of sample points). If *probability density*, the area of each bar corresponds to the probability that an event will fall into the corresponding bin (here, the sum of all bin AREAS equals 1). 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.histogram2d.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variable `z` 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. hovertemplatesrc Sets the source reference on Chart Studio Cloud for `hovertemplate`. 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.histogram2d.Legendgrouptit le` 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.histogram2d.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. nbinsx Specifies the maximum number of desired bins. This value will be used in an algorithm that will decide the optimal bin size such that the histogram best visualizes the distribution of the data. Ignored if `xbins.size` is provided. nbinsy Specifies the maximum number of desired bins. This value will be used in an algorithm that will decide the optimal bin size such that the histogram best visualizes the distribution of the data. Ignored if `ybins.size` is provided. opacity Sets the opacity of the trace. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.histogram2d.Stream` instance or dict with compatible properties textfont Sets the text font. texttemplate Template string used for rendering the information text that appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variable `z` texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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). x Sets the sample data to be binned on the x axis. 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. xbingroup Set a group of histogram traces which will have compatible x-bin settings. Using `xbingroup`, histogram2d and histogram2dcontour traces (on axes of the same axis type) can have compatible x-bin settings. Note that the same `xbingroup` value can be used to set (1D) histogram `bingroup` xbins :class:`plotly.graph_objects.histogram2d.XBins` instance or dict with compatible properties xcalendar Sets the calendar system to use with `x` date data. xgap Sets the horizontal gap (in pixels) between bricks. 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 sample data to be binned on the y axis. 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. ybingroup Set a group of histogram traces which will have compatible y-bin settings. Using `ybingroup`, histogram2d and histogram2dcontour traces (on axes of the same axis type) can have compatible y-bin settings. Note that the same `ybingroup` value can be used to set (1D) histogram `bingroup` ybins :class:`plotly.graph_objects.histogram2d.YBins` instance or dict with compatible properties ycalendar Sets the calendar system to use with `y` date data. ygap Sets the vertical gap (in pixels) between bricks. 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`. z Sets the aggregation data. zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zhoverformat Sets the hover text formatting rulefor `z` using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d 3/d3-format/tree/v1.4.5#d3-format.By default the values are formatted using generic number format. zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. zsmooth Picks a smoothing algorithm use to smooth `z` data. zsrc Sets the source reference on Chart Studio Cloud for `z`. 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. Returns ------- Figure """ from plotly.graph_objs import Histogram2d new_trace = Histogram2d( autobinx=autobinx, autobiny=autobiny, autocolorscale=autocolorscale, bingroup=bingroup, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, customdata=customdata, customdatasrc=customdatasrc, histfunc=histfunc, histnorm=histnorm, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, ids=ids, idssrc=idssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, marker=marker, meta=meta, metasrc=metasrc, name=name, nbinsx=nbinsx, nbinsy=nbinsy, opacity=opacity, reversescale=reversescale, showlegend=showlegend, showscale=showscale, stream=stream, textfont=textfont, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, uid=uid, uirevision=uirevision, visible=visible, x=x, xaxis=xaxis, xbingroup=xbingroup, xbins=xbins, xcalendar=xcalendar, xgap=xgap, xhoverformat=xhoverformat, xsrc=xsrc, y=y, yaxis=yaxis, ybingroup=ybingroup, ybins=ybins, ycalendar=ycalendar, ygap=ygap, yhoverformat=yhoverformat, ysrc=ysrc, z=z, zauto=zauto, zhoverformat=zhoverformat, zmax=zmax, zmid=zmid, zmin=zmin, zsmooth=zsmooth, zsrc=zsrc, **kwargs, ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_histogram2dcontour( self, autobinx=None, autobiny=None, autocolorscale=None, autocontour=None, bingroup=None, coloraxis=None, colorbar=None, colorscale=None, contours=None, customdata=None, customdatasrc=None, histfunc=None, histnorm=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, ids=None, idssrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, line=None, marker=None, meta=None, metasrc=None, name=None, nbinsx=None, nbinsy=None, ncontours=None, opacity=None, reversescale=None, showlegend=None, showscale=None, stream=None, textfont=None, texttemplate=None, texttemplatefallback=None, uid=None, uirevision=None, visible=None, x=None, xaxis=None, xbingroup=None, xbins=None, xcalendar=None, xhoverformat=None, xsrc=None, y=None, yaxis=None, ybingroup=None, ybins=None, ycalendar=None, yhoverformat=None, ysrc=None, z=None, zauto=None, zhoverformat=None, zmax=None, zmid=None, zmin=None, zsrc=None, row=None, col=None, secondary_y=None, **kwargs, ) -> "Figure": """ Add a new Histogram2dContour trace The sample data from which statistics are computed is set in `x` and `y` (where `x` and `y` represent marginal distributions, binning is set in `xbins` and `ybins` in this case) or `z` (where `z` represent the 2D distribution and binning set, binning is set by `x` and `y` in this case). The resulting distribution is visualized as a contour plot. Parameters ---------- autobinx Obsolete: since v1.42 each bin attribute is auto- determined separately and `autobinx` is not needed. However, we accept `autobinx: true` or `false` and will update `xbins` accordingly before deleting `autobinx` from the trace. autobiny Obsolete: since v1.42 each bin attribute is auto- determined separately and `autobiny` is not needed. However, we accept `autobiny: true` or `false` and will update `ybins` accordingly before deleting `autobiny` from the trace. 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. autocontour Determines whether or not the contour level attributes are picked by an algorithm. If True, the number of contour levels can be set in `ncontours`. If False, set the contour level attributes in `contours`. bingroup Set the `xbingroup` and `ybingroup` default prefix For example, setting a `bingroup` of 1 on two histogram2d traces will make them their x-bins and y-bins match separately. 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.histogram2dcontour.ColorBa r` 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 `zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,C ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd. contours :class:`plotly.graph_objects.histogram2dcontour.Contour s` 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`. histfunc Specifies the binning function used for this histogram trace. If "count", the histogram values are computed by counting the number of values lying inside each bin. If "sum", "avg", "min", "max", the histogram values are computed using the sum, the average, the minimum or the maximum of the values lying inside each bin respectively. histnorm Specifies the type of normalization used for this histogram trace. If "", the span of each bar corresponds to the number of occurrences (i.e. the number of data points lying inside the bins). If "percent" / "probability", the span of each bar corresponds to the percentage / fraction of occurrences with respect to the total number of sample points (here, the sum of all bin HEIGHTS equals 100% / 1). If "density", the span of each bar corresponds to the number of occurrences in a bin divided by the size of the bin interval (here, the sum of all bin AREAS equals the total number of sample points). If *probability density*, the area of each bar corresponds to the probability that an event will fall into the corresponding bin (here, the sum of all bin AREAS equals 1). 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.histogram2dcontour.Hoverla bel` 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variable `z` 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. hovertemplatesrc Sets the source reference on Chart Studio Cloud for `hovertemplate`. 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.histogram2dcontour.Legendg rouptitle` 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.histogram2dcontour.Line` instance or dict with compatible properties marker :class:`plotly.graph_objects.histogram2dcontour.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. nbinsx Specifies the maximum number of desired bins. This value will be used in an algorithm that will decide the optimal bin size such that the histogram best visualizes the distribution of the data. Ignored if `xbins.size` is provided. nbinsy Specifies the maximum number of desired bins. This value will be used in an algorithm that will decide the optimal bin size such that the histogram best visualizes the distribution of the data. Ignored if `ybins.size` is provided. ncontours Sets the maximum number of contour levels. The actual number of contours will be chosen automatically to be less than or equal to the value of `ncontours`. Has an effect only if `autocontour` is True or if `contours.size` is missing. opacity Sets the opacity of the trace. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.histogram2dcontour.Stream` instance or dict with compatible properties textfont For this trace it only has an effect if `coloring` is set to "heatmap". Sets the text font. texttemplate For this trace it only has an effect if `coloring` is set to "heatmap". Template string used for rendering the information text that appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `x`, `y`, `z` and `text`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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). x Sets the sample data to be binned on the x axis. 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. xbingroup Set a group of histogram traces which will have compatible x-bin settings. Using `xbingroup`, histogram2d and histogram2dcontour traces (on axes of the same axis type) can have compatible x-bin settings. Note that the same `xbingroup` value can be used to set (1D) histogram `bingroup` xbins :class:`plotly.graph_objects.histogram2dcontour.XBins` instance or dict with compatible properties xcalendar Sets the calendar system to use with `x` date data. 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 sample data to be binned on the y axis. 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. ybingroup Set a group of histogram traces which will have compatible y-bin settings. Using `ybingroup`, histogram2d and histogram2dcontour traces (on axes of the same axis type) can have compatible y-bin settings. Note that the same `ybingroup` value can be used to set (1D) histogram `bingroup` ybins :class:`plotly.graph_objects.histogram2dcontour.YBins` instance or dict with compatible properties ycalendar Sets the calendar system to use with `y` date data. 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`. z Sets the aggregation data. zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zhoverformat Sets the hover text formatting rulefor `z` using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d 3/d3-format/tree/v1.4.5#d3-format.By default the values are formatted using generic number format. zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. zsrc Sets the source reference on Chart Studio Cloud for `z`. 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. Returns ------- Figure """ from plotly.graph_objs import Histogram2dContour new_trace = Histogram2dContour( autobinx=autobinx, autobiny=autobiny, autocolorscale=autocolorscale, autocontour=autocontour, bingroup=bingroup, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, contours=contours, customdata=customdata, customdatasrc=customdatasrc, histfunc=histfunc, histnorm=histnorm, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, ids=ids, idssrc=idssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, line=line, marker=marker, meta=meta, metasrc=metasrc, name=name, nbinsx=nbinsx, nbinsy=nbinsy, ncontours=ncontours, opacity=opacity, reversescale=reversescale, showlegend=showlegend, showscale=showscale, stream=stream, textfont=textfont, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, uid=uid, uirevision=uirevision, visible=visible, x=x, xaxis=xaxis, xbingroup=xbingroup, xbins=xbins, xcalendar=xcalendar, xhoverformat=xhoverformat, xsrc=xsrc, y=y, yaxis=yaxis, ybingroup=ybingroup, ybins=ybins, ycalendar=ycalendar, yhoverformat=yhoverformat, ysrc=ysrc, z=z, zauto=zauto, zhoverformat=zhoverformat, zmax=zmax, zmid=zmid, zmin=zmin, zsrc=zsrc, **kwargs, ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_icicle( self, branchvalues=None, count=None, customdata=None, customdatasrc=None, domain=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, insidetextfont=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, pathbar=None, root=None, sort=None, stream=None, text=None, textfont=None, textinfo=None, textposition=None, textsrc=None, texttemplate=None, texttemplatefallback=None, texttemplatesrc=None, tiling=None, uid=None, uirevision=None, values=None, valuessrc=None, visible=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Icicle trace Visualize hierarchal data from leaves (and/or outer branches) towards root with rectangles. The icicle sectors are determined by the entries in "labels" or "ids" and in "parents". Parameters ---------- 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.icicle.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.icicle.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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`. leaf :class:`plotly.graph_objects.icicle.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.icicle.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.icicle.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.icicle.Pathbar` instance or dict with compatible properties root :class:`plotly.graph_objects.icicle.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.icicle.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 appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All 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`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. texttemplatesrc Sets the source reference on Chart Studio Cloud for `texttemplate`. tiling :class:`plotly.graph_objects.icicle.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). 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). Returns ------- Figure """ from plotly.graph_objs import Icicle new_trace = Icicle( branchvalues=branchvalues, count=count, customdata=customdata, customdatasrc=customdatasrc, domain=domain, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, insidetextfont=insidetextfont, labels=labels, labelssrc=labelssrc, leaf=leaf, legend=legend, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, level=level, marker=marker, maxdepth=maxdepth, meta=meta, metasrc=metasrc, name=name, opacity=opacity, outsidetextfont=outsidetextfont, parents=parents, parentssrc=parentssrc, pathbar=pathbar, root=root, sort=sort, stream=stream, text=text, textfont=textfont, textinfo=textinfo, textposition=textposition, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, texttemplatesrc=texttemplatesrc, tiling=tiling, uid=uid, uirevision=uirevision, values=values, valuessrc=valuessrc, visible=visible, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_image( self, colormodel=None, customdata=None, customdatasrc=None, dx=None, dy=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legend=None, legendgrouptitle=None, legendrank=None, legendwidth=None, meta=None, metasrc=None, name=None, opacity=None, source=None, stream=None, text=None, textsrc=None, uid=None, uirevision=None, visible=None, x0=None, xaxis=None, y0=None, yaxis=None, z=None, zmax=None, zmin=None, zorder=None, zsmooth=None, zsrc=None, row=None, col=None, secondary_y=None, **kwargs, ) -> "Figure": """ Add a new Image trace Display an image, i.e. data on a 2D regular raster. By default, when an image is displayed in a subplot, its y axis will be reversed (ie. `autorange: 'reversed'`), constrained to the domain (ie. `constrain: 'domain'`) and it will have the same scale as its x axis (ie. `scaleanchor: 'x,`) in order for pixels to be rendered as squares. Parameters ---------- colormodel Color model used to map the numerical color components described in `z` into colors. If `source` is specified, this attribute will be set to `rgba256` otherwise it defaults to `rgb`. 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 Set the pixel's horizontal size. dy Set the pixel's vertical size 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.image.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `z`, `color` and `colormodel`. 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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. legendgrouptitle :class:`plotly.graph_objects.image.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. 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. source Specifies the data URI of the image to be visualized. The URI consists of "data:image/[<media subtype\\>][;base64\\],<data\\>" stream :class:`plotly.graph_objects.image.Stream` instance or dict with compatible properties text Sets the text elements associated with each z value. 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. 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). x0 Set the image's x position. The left edge of the image (or the right edge if the x axis is reversed or dx is negative) will be found at xmin=x0-dx/2 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. y0 Set the image's y position. The top edge of the image (or the bottom edge if the y axis is NOT reversed or if dy is negative) will be found at ymin=y0-dy/2. By default when an image trace is included, the y axis will be reversed so that the image is right-side-up, but you can disable this by setting yaxis.autorange=true or by providing an explicit y axis range. 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. z A 2-dimensional array in which each element is an array of 3 or 4 numbers representing a color. zmax Array defining the higher bound for each color component. Note that the default value will depend on the colormodel. For the `rgb` colormodel, it is [255, 255, 255]. For the `rgba` colormodel, it is [255, 255, 255, 1]. For the `rgba256` colormodel, it is [255, 255, 255, 255]. For the `hsl` colormodel, it is [360, 100, 100]. For the `hsla` colormodel, it is [360, 100, 100, 1]. zmin Array defining the lower bound for each color component. Note that the default value will depend on the colormodel. For the `rgb` colormodel, it is [0, 0, 0]. For the `rgba` colormodel, it is [0, 0, 0, 0]. For the `rgba256` colormodel, it is [0, 0, 0, 0]. For the `hsl` colormodel, it is [0, 0, 0]. For the `hsla` colormodel, it is [0, 0, 0, 0]. 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`. zsmooth Picks a smoothing algorithm used to smooth `z` data. This only applies for image traces that use the `source` attribute. zsrc Sets the source reference on Chart Studio Cloud for `z`. 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. Returns ------- Figure """ from plotly.graph_objs import Image new_trace = Image( colormodel=colormodel, customdata=customdata, customdatasrc=customdatasrc, dx=dx, dy=dy, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legend=legend, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, meta=meta, metasrc=metasrc, name=name, opacity=opacity, source=source, stream=stream, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, visible=visible, x0=x0, xaxis=xaxis, y0=y0, yaxis=yaxis, z=z, zmax=zmax, zmin=zmin, zorder=zorder, zsmooth=zsmooth, zsrc=zsrc, **kwargs, ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_indicator( self, align=None, customdata=None, customdatasrc=None, delta=None, domain=None, gauge=None, ids=None, idssrc=None, legend=None, legendgrouptitle=None, legendrank=None, legendwidth=None, meta=None, metasrc=None, mode=None, name=None, number=None, stream=None, title=None, uid=None, uirevision=None, value=None, visible=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Indicator trace An indicator is used to visualize a single `value` along with some contextual information such as `steps` or a `threshold`, using a combination of three visual elements: a number, a delta, and/or a gauge. Deltas are taken with respect to a `reference`. Gauges can be either angular or bullet (aka linear) gauges. Parameters ---------- align Sets the horizontal alignment of the `text` within the box. Note that this attribute has no effect if an angular gauge is displayed: in this case, it is always centered 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`. delta :class:`plotly.graph_objects.indicator.Delta` instance or dict with compatible properties domain :class:`plotly.graph_objects.indicator.Domain` instance or dict with compatible properties gauge The gauge of the Indicator plot. 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.indicator.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. 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`. mode Determines how the value is displayed on the graph. `number` displays the value numerically in text. `delta` displays the difference to a reference value in text. Finally, `gauge` displays the value graphically on an axis. name Sets the trace name. The trace name appears as the legend item and on hover. number :class:`plotly.graph_objects.indicator.Number` instance or dict with compatible properties stream :class:`plotly.graph_objects.indicator.Stream` instance or dict with compatible properties title :class:`plotly.graph_objects.indicator.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. value Sets the number to be displayed. 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). 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). Returns ------- Figure """ from plotly.graph_objs import Indicator new_trace = Indicator( align=align, customdata=customdata, customdatasrc=customdatasrc, delta=delta, domain=domain, gauge=gauge, ids=ids, idssrc=idssrc, legend=legend, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, meta=meta, metasrc=metasrc, mode=mode, name=name, number=number, stream=stream, title=title, uid=uid, uirevision=uirevision, value=value, visible=visible, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_isosurface( self, autocolorscale=None, caps=None, cauto=None, cmax=None, cmid=None, cmin=None, coloraxis=None, colorbar=None, colorscale=None, contour=None, customdata=None, customdatasrc=None, flatshading=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, isomax=None, isomin=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, lighting=None, lightposition=None, meta=None, metasrc=None, name=None, opacity=None, reversescale=None, scene=None, showlegend=None, showscale=None, slices=None, spaceframe=None, stream=None, surface=None, text=None, textsrc=None, uid=None, uirevision=None, value=None, valuehoverformat=None, valuesrc=None, visible=None, x=None, xhoverformat=None, xsrc=None, y=None, yhoverformat=None, ysrc=None, z=None, zhoverformat=None, zsrc=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Isosurface trace Draws isosurfaces between iso-min and iso-max values with coordinates given by four 1-dimensional arrays containing the `value`, `x`, `y` and `z` of every vertex of a uniform or non- uniform 3-D grid. Horizontal or vertical slices, caps as well as spaceframe between iso-min and iso-max values could also be drawn using this trace. Parameters ---------- 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. caps :class:`plotly.graph_objects.isosurface.Caps` instance or dict with compatible properties cauto Determines whether or not the color domain is computed with respect to the input data (here `value`) 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 `value` 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 `value`. Has no effect when `cauto` is `false`. cmin Sets the lower bound of the color domain. Value should have the same units as `value` and if set, `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.isosurface.ColorBar` 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: Blackbody,Bluered,Blues,C ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd. contour :class:`plotly.graph_objects.isosurface.Contour` 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`. flatshading Determines whether or not normal smoothing is applied to the meshes, creating meshes with an angular, low- poly look via flat reflections. 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.isosurface.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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`. isomax Sets the maximum boundary for iso-surface plot. isomin Sets the minimum boundary for iso-surface plot. 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.isosurface.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. lighting :class:`plotly.graph_objects.isosurface.Lighting` instance or dict with compatible properties lightposition :class:`plotly.graph_objects.isosurface.Lightposition` 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 surface. Please note that in the case of using high `opacity` values for example a value greater than or equal to 0.5 on two surfaces (and 0.25 with four surfaces), an overlay of multiple transparent surfaces may not perfectly be sorted in depth by the webgl API. This behavior may be improved in the near future and is subject to change. 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. scene Sets a reference between this trace's 3D coordinate system and a 3D scene. If "scene" (the default value), the (x,y,z) coordinates refer to `layout.scene`. If "scene2", the (x,y,z) coordinates refer to `layout.scene2`, and so on. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. slices :class:`plotly.graph_objects.isosurface.Slices` instance or dict with compatible properties spaceframe :class:`plotly.graph_objects.isosurface.Spaceframe` instance or dict with compatible properties stream :class:`plotly.graph_objects.isosurface.Stream` instance or dict with compatible properties surface :class:`plotly.graph_objects.isosurface.Surface` instance or dict with compatible properties text Sets the text elements associated with the vertices. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. 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. value Sets the 4th dimension (value) of the vertices. valuehoverformat Sets the hover text formatting rulefor `value` using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d 3/d3-format/tree/v1.4.5#d3-format.By default the values are formatted using generic number format. valuesrc Sets the source reference on Chart Studio Cloud for `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). x Sets the X coordinates of the vertices on X 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`. xsrc Sets the source reference on Chart Studio Cloud for `x`. y Sets the Y coordinates of the vertices on 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`. ysrc Sets the source reference on Chart Studio Cloud for `y`. z Sets the Z coordinates of the vertices on Z axis. zhoverformat Sets the hover text formatting rulefor `z` 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 `zaxis.hoverformat`. zsrc Sets the source reference on Chart Studio Cloud for `z`. 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). Returns ------- Figure """ from plotly.graph_objs import Isosurface new_trace = Isosurface( autocolorscale=autocolorscale, caps=caps, cauto=cauto, cmax=cmax, cmid=cmid, cmin=cmin, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, contour=contour, customdata=customdata, customdatasrc=customdatasrc, flatshading=flatshading, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, isomax=isomax, isomin=isomin, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, lighting=lighting, lightposition=lightposition, meta=meta, metasrc=metasrc, name=name, opacity=opacity, reversescale=reversescale, scene=scene, showlegend=showlegend, showscale=showscale, slices=slices, spaceframe=spaceframe, stream=stream, surface=surface, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, value=value, valuehoverformat=valuehoverformat, valuesrc=valuesrc, visible=visible, x=x, xhoverformat=xhoverformat, xsrc=xsrc, y=y, yhoverformat=yhoverformat, ysrc=ysrc, z=z, zhoverformat=zhoverformat, zsrc=zsrc, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_mesh3d( self, alphahull=None, autocolorscale=None, cauto=None, cmax=None, cmid=None, cmin=None, color=None, coloraxis=None, colorbar=None, colorscale=None, contour=None, customdata=None, customdatasrc=None, delaunayaxis=None, facecolor=None, facecolorsrc=None, flatshading=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, i=None, ids=None, idssrc=None, intensity=None, intensitymode=None, intensitysrc=None, isrc=None, j=None, jsrc=None, k=None, ksrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, lighting=None, lightposition=None, meta=None, metasrc=None, name=None, opacity=None, reversescale=None, scene=None, showlegend=None, showscale=None, stream=None, text=None, textsrc=None, uid=None, uirevision=None, vertexcolor=None, vertexcolorsrc=None, visible=None, x=None, xcalendar=None, xhoverformat=None, xsrc=None, y=None, ycalendar=None, yhoverformat=None, ysrc=None, z=None, zcalendar=None, zhoverformat=None, zsrc=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Mesh3d trace Draws sets of triangles with coordinates given by three 1-dimensional arrays in `x`, `y`, `z` and (1) a sets of `i`, `j`, `k` indices (2) Delaunay triangulation or (3) the Alpha- shape algorithm or (4) the Convex-hull algorithm Parameters ---------- alphahull Determines how the mesh surface triangles are derived from the set of vertices (points) represented by the `x`, `y` and `z` arrays, if the `i`, `j`, `k` arrays are not supplied. For general use of `mesh3d` it is preferred that `i`, `j`, `k` are supplied. If "-1", Delaunay triangulation is used, which is mainly suitable if the mesh is a single, more or less layer surface that is perpendicular to `delaunayaxis`. In case the `delaunayaxis` intersects the mesh surface at more than one point it will result triangles that are very long in the dimension of `delaunayaxis`. If ">0", the alpha-shape algorithm is used. In this case, the positive `alphahull` value signals the use of the alpha-shape algorithm, _and_ its value acts as the parameter for the mesh fitting. If 0, the convex-hull algorithm is used. It is suitable for convex bodies or if the intention is to enclose the `x`, `y` and `z` point set into a convex hull. 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 `intensity`) 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 `intensity` 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 `intensity`. Has no effect when `cauto` is `false`. cmin Sets the lower bound of the color domain. Value should have the same units as `intensity` and if set, `cmax` must be set as well. color Sets the color of the whole mesh 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.mesh3d.ColorBar` 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: Blackbody,Bluered,Blues,C ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd. contour :class:`plotly.graph_objects.mesh3d.Contour` 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`. delaunayaxis Sets the Delaunay axis, which is the axis that is perpendicular to the surface of the Delaunay triangulation. It has an effect if `i`, `j`, `k` are not provided and `alphahull` is set to indicate Delaunay triangulation. facecolor Sets the color of each face Overrides "color" and "vertexcolor". facecolorsrc Sets the source reference on Chart Studio Cloud for `facecolor`. flatshading Determines whether or not normal smoothing is applied to the meshes, creating meshes with an angular, low- poly look via flat reflections. 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.mesh3d.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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`. i A vector of vertex indices, i.e. integer values between 0 and the length of the vertex vectors, representing the "first" vertex of a triangle. For example, `{i[m], j[m], k[m]}` together represent face m (triangle m) in the mesh, where `i[m] = n` points to the triplet `{x[n], y[n], z[n]}` in the vertex arrays. Therefore, each element in `i` represents a point in space, which is the first vertex of a triangle. 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`. intensity Sets the intensity values for vertices or cells as defined by `intensitymode`. It can be used for plotting fields on meshes. intensitymode Determines the source of `intensity` values. intensitysrc Sets the source reference on Chart Studio Cloud for `intensity`. isrc Sets the source reference on Chart Studio Cloud for `i`. j A vector of vertex indices, i.e. integer values between 0 and the length of the vertex vectors, representing the "second" vertex of a triangle. For example, `{i[m], j[m], k[m]}` together represent face m (triangle m) in the mesh, where `j[m] = n` points to the triplet `{x[n], y[n], z[n]}` in the vertex arrays. Therefore, each element in `j` represents a point in space, which is the second vertex of a triangle. jsrc Sets the source reference on Chart Studio Cloud for `j`. k A vector of vertex indices, i.e. integer values between 0 and the length of the vertex vectors, representing the "third" vertex of a triangle. For example, `{i[m], j[m], k[m]}` together represent face m (triangle m) in the mesh, where `k[m] = n` points to the triplet `{x[n], y[n], z[n]}` in the vertex arrays. Therefore, each element in `k` represents a point in space, which is the third vertex of a triangle. ksrc Sets the source reference on Chart Studio Cloud for `k`. 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.mesh3d.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. lighting :class:`plotly.graph_objects.mesh3d.Lighting` instance or dict with compatible properties lightposition :class:`plotly.graph_objects.mesh3d.Lightposition` 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 surface. Please note that in the case of using high `opacity` values for example a value greater than or equal to 0.5 on two surfaces (and 0.25 with four surfaces), an overlay of multiple transparent surfaces may not perfectly be sorted in depth by the webgl API. This behavior may be improved in the near future and is subject to change. 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. scene Sets a reference between this trace's 3D coordinate system and a 3D scene. If "scene" (the default value), the (x,y,z) coordinates refer to `layout.scene`. If "scene2", the (x,y,z) coordinates refer to `layout.scene2`, and so on. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.mesh3d.Stream` instance or dict with compatible properties text Sets the text elements associated with the vertices. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. 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. vertexcolor Sets the color of each vertex Overrides "color". While Red, green and blue colors are in the range of 0 and 255; in the case of having vertex color data in RGBA format, the alpha color should be normalized to be between 0 and 1. vertexcolorsrc Sets the source reference on Chart Studio Cloud for `vertexcolor`. 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). x Sets the X coordinates of the vertices. The nth element of vectors `x`, `y` and `z` jointly represent the X, Y and Z coordinates of the nth vertex. xcalendar Sets the calendar system to use with `x` date data. 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 coordinates of the vertices. The nth element of vectors `x`, `y` and `z` jointly represent the X, Y and Z coordinates of the nth vertex. ycalendar Sets the calendar system to use with `y` date data. 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`. z Sets the Z coordinates of the vertices. The nth element of vectors `x`, `y` and `z` jointly represent the X, Y and Z coordinates of the nth vertex. zcalendar Sets the calendar system to use with `z` date data. zhoverformat Sets the hover text formatting rulefor `z` 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 `zaxis.hoverformat`. zsrc Sets the source reference on Chart Studio Cloud for `z`. 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). Returns ------- Figure """ from plotly.graph_objs import Mesh3d new_trace = Mesh3d( alphahull=alphahull, autocolorscale=autocolorscale, cauto=cauto, cmax=cmax, cmid=cmid, cmin=cmin, color=color, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, contour=contour, customdata=customdata, customdatasrc=customdatasrc, delaunayaxis=delaunayaxis, facecolor=facecolor, facecolorsrc=facecolorsrc, flatshading=flatshading, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, i=i, ids=ids, idssrc=idssrc, intensity=intensity, intensitymode=intensitymode, intensitysrc=intensitysrc, isrc=isrc, j=j, jsrc=jsrc, k=k, ksrc=ksrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, lighting=lighting, lightposition=lightposition, meta=meta, metasrc=metasrc, name=name, opacity=opacity, reversescale=reversescale, scene=scene, showlegend=showlegend, showscale=showscale, stream=stream, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, vertexcolor=vertexcolor, vertexcolorsrc=vertexcolorsrc, visible=visible, x=x, xcalendar=xcalendar, xhoverformat=xhoverformat, xsrc=xsrc, y=y, ycalendar=ycalendar, yhoverformat=yhoverformat, ysrc=ysrc, z=z, zcalendar=zcalendar, zhoverformat=zhoverformat, zsrc=zsrc, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_ohlc( self, close=None, closesrc=None, customdata=None, customdatasrc=None, decreasing=None, high=None, highsrc=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, increasing=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, line=None, low=None, lowsrc=None, meta=None, metasrc=None, name=None, opacity=None, open=None, opensrc=None, selectedpoints=None, showlegend=None, stream=None, text=None, textsrc=None, tickwidth=None, uid=None, uirevision=None, visible=None, x=None, xaxis=None, xcalendar=None, xhoverformat=None, xperiod=None, xperiod0=None, xperiodalignment=None, xsrc=None, yaxis=None, yhoverformat=None, zorder=None, row=None, col=None, secondary_y=None, **kwargs, ) -> "Figure": """ Add a new Ohlc trace The ohlc (short for Open-High-Low-Close) is a style of financial chart describing open, high, low and close for a given `x` coordinate (most likely time). The tip of the lines represent the `low` and `high` values and the horizontal segments represent the `open` and `close` values. Sample points where the close value is higher (lower) then the open value are called increasing (decreasing). By default, increasing items are drawn in green whereas decreasing are drawn in red. Parameters ---------- close Sets the close values. closesrc Sets the source reference on Chart Studio Cloud for `close`. 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.ohlc.Decreasing` instance or dict with compatible properties high Sets the high values. highsrc Sets the source reference on Chart Studio Cloud for `high`. 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.ohlc.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `open`, `high`, `low` and `close`. 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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`. increasing :class:`plotly.graph_objects.ohlc.Increasing` 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. 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.ohlc.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.ohlc.Line` instance or dict with compatible properties low Sets the low values. lowsrc Sets the source reference on Chart Studio Cloud for `low`. 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. open Sets the open values. opensrc Sets the source reference on Chart Studio Cloud for `open`. 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.ohlc.Stream` instance or dict with compatible properties text Sets hover text elements associated with each sample point. 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 this trace's sample points. textsrc Sets the source reference on Chart Studio Cloud for `text`. tickwidth Sets the width of the open/close tick marks relative to the "x" minimal interval. 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). x Sets the x coordinates. If absent, linear coordinate will be generated. 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. xcalendar Sets the calendar system to use with `x` date data. 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`. 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`. 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`. 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. Returns ------- Figure """ from plotly.graph_objs import Ohlc new_trace = Ohlc( close=close, closesrc=closesrc, customdata=customdata, customdatasrc=customdatasrc, decreasing=decreasing, high=high, highsrc=highsrc, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, increasing=increasing, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, line=line, low=low, lowsrc=lowsrc, meta=meta, metasrc=metasrc, name=name, opacity=opacity, open=open, opensrc=opensrc, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, text=text, textsrc=textsrc, tickwidth=tickwidth, uid=uid, uirevision=uirevision, visible=visible, x=x, xaxis=xaxis, xcalendar=xcalendar, xhoverformat=xhoverformat, xperiod=xperiod, xperiod0=xperiod0, xperiodalignment=xperiodalignment, xsrc=xsrc, yaxis=yaxis, yhoverformat=yhoverformat, zorder=zorder, **kwargs, ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_parcats( self, arrangement=None, bundlecolors=None, counts=None, countssrc=None, dimensions=None, dimensiondefaults=None, domain=None, hoverinfo=None, hoveron=None, hovertemplate=None, hovertemplatefallback=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, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Parcats trace Parallel categories diagram for multidimensional categorical data. Parameters ---------- 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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). 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). Returns ------- Figure """ from plotly.graph_objs import Parcats new_trace = Parcats( arrangement=arrangement, bundlecolors=bundlecolors, counts=counts, countssrc=countssrc, dimensions=dimensions, dimensiondefaults=dimensiondefaults, domain=domain, hoverinfo=hoverinfo, hoveron=hoveron, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, labelfont=labelfont, legendgrouptitle=legendgrouptitle, legendwidth=legendwidth, line=line, meta=meta, metasrc=metasrc, name=name, sortpaths=sortpaths, stream=stream, tickfont=tickfont, uid=uid, uirevision=uirevision, visible=visible, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_parcoords( self, customdata=None, customdatasrc=None, dimensions=None, dimensiondefaults=None, domain=None, ids=None, idssrc=None, labelangle=None, labelfont=None, labelside=None, legend=None, legendgrouptitle=None, legendrank=None, legendwidth=None, line=None, meta=None, metasrc=None, name=None, rangefont=None, stream=None, tickfont=None, uid=None, uirevision=None, unselected=None, visible=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Parcoords trace Parallel coordinates for multidimensional exploratory data analysis. The samples are specified in `dimensions`. The colors are set in `line.color`. Parameters ---------- 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`. dimensions The dimensions (variables) of the parallel coordinates chart. 2..60 dimensions are supported. dimensiondefaults When used in a template (as layout.template.data.parcoords.dimensiondefaults), sets the default property values to use for elements of parcoords.dimensions domain :class:`plotly.graph_objects.parcoords.Domain` 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`. labelangle Sets the angle of the labels with respect to the horizontal. For example, a `tickangle` of -90 draws the labels vertically. Tilted labels with "labelangle" may be positioned better inside margins when `labelposition` is set to "bottom". labelfont Sets the font for the `dimension` labels. labelside Specifies the location of the `label`. "top" positions labels above, next to the title "bottom" positions labels below the graph Tilted labels with "labelangle" may be positioned better inside margins when `labelposition` is set to "bottom". 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.parcoords.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.parcoords.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. rangefont Sets the font for the `dimension` range values. stream :class:`plotly.graph_objects.parcoords.Stream` instance or dict with compatible properties tickfont Sets the font for the `dimension` tick values. 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.parcoords.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). 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). Returns ------- Figure """ from plotly.graph_objs import Parcoords new_trace = Parcoords( customdata=customdata, customdatasrc=customdatasrc, dimensions=dimensions, dimensiondefaults=dimensiondefaults, domain=domain, ids=ids, idssrc=idssrc, labelangle=labelangle, labelfont=labelfont, labelside=labelside, legend=legend, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, line=line, meta=meta, metasrc=metasrc, name=name, rangefont=rangefont, stream=stream, tickfont=tickfont, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_pie( self, automargin=None, customdata=None, customdatasrc=None, direction=None, dlabel=None, domain=None, hole=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, insidetextfont=None, insidetextorientation=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, outsidetextfont=None, pull=None, pullsrc=None, rotation=None, scalegroup=None, showlegend=None, sort=None, stream=None, text=None, textfont=None, textinfo=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatefallback=None, texttemplatesrc=None, title=None, uid=None, uirevision=None, values=None, valuessrc=None, visible=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Pie trace A data visualized by the sectors of the pie is set in `values`. The sector labels are set in `labels`. The sector colors are set in `marker.colors` Parameters ---------- automargin Determines whether outside text labels can push the margins. 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`. direction Specifies the direction at which succeeding sectors follow one another. dlabel Sets the label step. See `label0` for more info. domain :class:`plotly.graph_objects.pie.Domain` instance or dict with compatible properties hole Sets the fraction of the radius to cut out of the pie. Use this to make a donut chart. 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.pie.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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`, `percent` and `text`. 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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. 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.pie.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.pie.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. outsidetextfont Sets the font used for `textinfo` lying outside the sector. pull Sets the fraction of larger radius to pull the sectors out from the center. This can be a constant to pull all slices apart from each other equally or an array to highlight one or more slices. pullsrc Sets the source reference on Chart Studio Cloud for `pull`. rotation Instead of the first slice starting at 12 o'clock, rotate to some other angle. scalegroup If there are multiple pie charts 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. sort Determines whether or not the sectors are reordered from largest to smallest. stream :class:`plotly.graph_objects.pie.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 appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All 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`, `percent` and `text`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. texttemplatesrc Sets the source reference on Chart Studio Cloud for `texttemplate`. title :class:`plotly.graph_objects.pie.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). 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). Returns ------- Figure """ from plotly.graph_objs import Pie new_trace = Pie( automargin=automargin, customdata=customdata, customdatasrc=customdatasrc, direction=direction, dlabel=dlabel, domain=domain, hole=hole, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, insidetextfont=insidetextfont, insidetextorientation=insidetextorientation, label0=label0, labels=labels, labelssrc=labelssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, marker=marker, meta=meta, metasrc=metasrc, name=name, opacity=opacity, outsidetextfont=outsidetextfont, pull=pull, pullsrc=pullsrc, rotation=rotation, scalegroup=scalegroup, showlegend=showlegend, sort=sort, stream=stream, text=text, textfont=textfont, textinfo=textinfo, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, texttemplatesrc=texttemplatesrc, title=title, uid=uid, uirevision=uirevision, values=values, valuessrc=valuessrc, visible=visible, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_sankey( self, 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, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Sankey trace 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 ---------- 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). 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). Returns ------- Figure """ from plotly.graph_objs import Sankey new_trace = Sankey( arrangement=arrangement, customdata=customdata, customdatasrc=customdatasrc, domain=domain, hoverinfo=hoverinfo, hoverlabel=hoverlabel, ids=ids, idssrc=idssrc, legend=legend, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, link=link, meta=meta, metasrc=metasrc, name=name, node=node, orientation=orientation, selectedpoints=selectedpoints, stream=stream, textfont=textfont, uid=uid, uirevision=uirevision, valueformat=valueformat, valuesuffix=valuesuffix, visible=visible, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_scatter( self, alignmentgroup=None, cliponaxis=None, connectgaps=None, customdata=None, customdatasrc=None, dx=None, dy=None, error_x=None, error_y=None, fill=None, fillcolor=None, fillgradient=None, fillpattern=None, groupnorm=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hoveron=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, line=None, marker=None, meta=None, metasrc=None, mode=None, name=None, offsetgroup=None, opacity=None, orientation=None, selected=None, selectedpoints=None, showlegend=None, stackgaps=None, stackgroup=None, stream=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatefallback=None, texttemplatesrc=None, uid=None, uirevision=None, unselected=None, visible=None, x=None, x0=None, xaxis=None, xcalendar=None, xhoverformat=None, xperiod=None, xperiod0=None, xperiodalignment=None, xsrc=None, y=None, y0=None, yaxis=None, ycalendar=None, yhoverformat=None, yperiod=None, yperiod0=None, yperiodalignment=None, ysrc=None, zorder=None, row=None, col=None, secondary_y=None, **kwargs, ) -> "Figure": """ Add a new Scatter trace The scatter trace type encompasses line charts, scatter charts, text charts, and bubble charts. The data visualized as scatter point or lines is set in `x` and `y`. Text (appearing either on the chart or on hover only) is via `text`. Bubble charts are achieved by setting `marker.size` and/or `marker.color` to numerical arrays. Parameters ---------- 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 or not markers and text nodes are clipped about the subplot axes. To show markers and text nodes above axis lines and tick labels, make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*. connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. 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. error_x :class:`plotly.graph_objects.scatter.ErrorX` instance or dict with compatible properties error_y :class:`plotly.graph_objects.scatter.ErrorY` instance or dict with compatible properties fill Sets the area to fill with a solid color. Defaults to "none" unless this trace is stacked, then it gets "tonexty" ("tonextx") if `orientation` is "v" ("h") Use with `fillcolor` if not "none". "tozerox" and "tozeroy" fill to x=0 and y=0 respectively. "tonextx" and "tonexty" fill between the endpoints of this trace and the endpoints of the trace before it, connecting those endpoints with straight lines (to make a stacked area graph); if there is no trace before it, they behave like "tozerox" and "tozeroy". "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. "tonext" fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like "toself" if there is no trace before it. "tonext" should not be used if one trace does not enclose the other. Traces in a `stackgroup` will only fill to (or be filled to) other traces in the same group. With multiple `stackgroup`s or some traces stacked and some not, if fill-linked traces are not already consecutive, the later ones will be pushed down in the drawing order. fillcolor Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. If fillgradient is specified, fillcolor is ignored except for setting the background color of the hover label, if any. fillgradient Sets a fill gradient. If not specified, the fillcolor is used instead. fillpattern Sets the pattern within the marker. groupnorm Only relevant when `stackgroup` is used, and only the first `groupnorm` found in the `stackgroup` will be used - including if `visible` is "legendonly" but not if it is `false`. Sets the normalization for the sum of this `stackgroup`. With "fraction", the value of each trace at each location is divided by the sum of all trace values at that location. "percent" is the same but multiplied by 100 to show percentages. If there are multiple subplots, or multiple `stackgroup`s on one subplot, each will be normalized within its own set. 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.scatter.Hoverlabel` instance or dict with compatible properties hoveron Do the hover effects highlight individual points (markers or line points) or do they highlight filled regions? If the fill is "toself" or "tonext" and there are no markers or text, then the default is "fills", otherwise it is "points". 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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`. 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.scatter.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.scatter.Line` instance or dict with compatible properties marker :class:`plotly.graph_objects.scatter.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`. mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points and the trace is not stacked then the default is "lines+markers". Otherwise, "lines". name Sets the trace name. The trace name appears as the legend item and on hover. 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 Only relevant in the following cases: 1. when `scattermode` is set to "group". 2. when `stackgroup` is used, and only the first `orientation` found in the `stackgroup` will be used - including if `visible` is "legendonly" but not if it is `false`. Sets the stacking direction. With "v" ("h"), the y (x) values of subsequent traces are added. Also affects the default value of `fill`. selected :class:`plotly.graph_objects.scatter.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. stackgaps Only relevant when `stackgroup` is used, and only the first `stackgaps` found in the `stackgroup` will be used - including if `visible` is "legendonly" but not if it is `false`. Determines how we handle locations at which other traces in this group have data but this one does not. With *infer zero* we insert a zero at these locations. With "interpolate" we linearly interpolate between existing values, and extrapolate a constant beyond the existing values. stackgroup Set several scatter traces (on the same subplot) to the same stackgroup in order to add their y values (or their x values if `orientation` is "h"). If blank or omitted this trace will not be stacked. Stacking also turns `fill` on by default, using "tonexty" ("tonextx") if `orientation` is "h" ("v") and sets the default `mode` to "lines" irrespective of point count. You can only stack on a numeric (linear or log) axis. Traces in a `stackgroup` will only fill to (or be filled to) other traces in the same group. With multiple `stackgroup`s or some traces stacked and some not, if fill-linked traces are not already consecutive, the later ones will be pushed down in the drawing order. stream :class:`plotly.graph_objects.scatter.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. textfont Sets the text font. textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. 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 appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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. unselected :class:`plotly.graph_objects.scatter.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). 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. xcalendar Sets the calendar system to use with `x` date data. 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. ycalendar Sets the calendar system to use with `y` date data. 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`. 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. Returns ------- Figure """ from plotly.graph_objs import Scatter new_trace = Scatter( alignmentgroup=alignmentgroup, cliponaxis=cliponaxis, connectgaps=connectgaps, customdata=customdata, customdatasrc=customdatasrc, dx=dx, dy=dy, error_x=error_x, error_y=error_y, fill=fill, fillcolor=fillcolor, fillgradient=fillgradient, fillpattern=fillpattern, groupnorm=groupnorm, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hoveron=hoveron, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, line=line, marker=marker, meta=meta, metasrc=metasrc, mode=mode, name=name, offsetgroup=offsetgroup, opacity=opacity, orientation=orientation, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stackgaps=stackgaps, stackgroup=stackgroup, stream=stream, text=text, textfont=textfont, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, texttemplatesrc=texttemplatesrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, x=x, x0=x0, xaxis=xaxis, xcalendar=xcalendar, xhoverformat=xhoverformat, xperiod=xperiod, xperiod0=xperiod0, xperiodalignment=xperiodalignment, xsrc=xsrc, y=y, y0=y0, yaxis=yaxis, ycalendar=ycalendar, yhoverformat=yhoverformat, yperiod=yperiod, yperiod0=yperiod0, yperiodalignment=yperiodalignment, ysrc=ysrc, zorder=zorder, **kwargs, ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_scatter3d( self, connectgaps=None, customdata=None, customdatasrc=None, error_x=None, error_y=None, error_z=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, line=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, projection=None, scene=None, showlegend=None, stream=None, surfaceaxis=None, surfacecolor=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatefallback=None, texttemplatesrc=None, uid=None, uirevision=None, visible=None, x=None, xcalendar=None, xhoverformat=None, xsrc=None, y=None, ycalendar=None, yhoverformat=None, ysrc=None, z=None, zcalendar=None, zhoverformat=None, zsrc=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Scatter3d trace The data visualized as scatter point or lines in 3D dimension is set in `x`, `y`, `z`. Text (appearing either on the chart or on hover only) is via `text`. Bubble charts are achieved by setting `marker.size` and/or `marker.color` Projections are achieved via `projection`. Surface fills are achieved via `surfaceaxis`. Parameters ---------- connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. 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`. error_x :class:`plotly.graph_objects.scatter3d.ErrorX` instance or dict with compatible properties error_y :class:`plotly.graph_objects.scatter3d.ErrorY` instance or dict with compatible properties error_z :class:`plotly.graph_objects.scatter3d.ErrorZ` 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.scatter3d.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. hovertemplatesrc Sets the source reference on Chart Studio Cloud for `hovertemplate`. hovertext Sets text elements associated with each (x,y,z) triplet. 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,z) 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`. 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.scatter3d.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.scatter3d.Line` instance or dict with compatible properties marker :class:`plotly.graph_objects.scatter3d.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`. mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points and the trace is not stacked then the default is "lines+markers". Otherwise, "lines". name Sets the trace name. The trace name appears as the legend item and on hover. opacity Sets the opacity of the trace. projection :class:`plotly.graph_objects.scatter3d.Projection` instance or dict with compatible properties scene Sets a reference between this trace's 3D coordinate system and a 3D scene. If "scene" (the default value), the (x,y,z) coordinates refer to `layout.scene`. If "scene2", the (x,y,z) coordinates refer to `layout.scene2`, and so on. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.scatter3d.Stream` instance or dict with compatible properties surfaceaxis If "-1", the scatter points are not fill with a surface If 0, 1, 2, the scatter points are filled with a Delaunay surface about the x, y, z respectively. surfacecolor Sets the surface fill color. text Sets text elements associated with each (x,y,z) triplet. 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,z) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the text font. textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. 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 appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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). x Sets the x coordinates. xcalendar Sets the calendar system to use with `x` date data. 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 coordinates. ycalendar Sets the calendar system to use with `y` date data. 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`. z Sets the z coordinates. zcalendar Sets the calendar system to use with `z` date data. zhoverformat Sets the hover text formatting rulefor `z` 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 `zaxis.hoverformat`. zsrc Sets the source reference on Chart Studio Cloud for `z`. 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). Returns ------- Figure """ from plotly.graph_objs import Scatter3d new_trace = Scatter3d( connectgaps=connectgaps, customdata=customdata, customdatasrc=customdatasrc, error_x=error_x, error_y=error_y, error_z=error_z, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, line=line, marker=marker, meta=meta, metasrc=metasrc, mode=mode, name=name, opacity=opacity, projection=projection, scene=scene, showlegend=showlegend, stream=stream, surfaceaxis=surfaceaxis, surfacecolor=surfacecolor, text=text, textfont=textfont, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, texttemplatesrc=texttemplatesrc, uid=uid, uirevision=uirevision, visible=visible, x=x, xcalendar=xcalendar, xhoverformat=xhoverformat, xsrc=xsrc, y=y, ycalendar=ycalendar, yhoverformat=yhoverformat, ysrc=ysrc, z=z, zcalendar=zcalendar, zhoverformat=zhoverformat, zsrc=zsrc, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_scattercarpet( self, a=None, asrc=None, b=None, bsrc=None, carpet=None, connectgaps=None, customdata=None, customdatasrc=None, fill=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hoveron=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, line=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, selected=None, selectedpoints=None, showlegend=None, stream=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatefallback=None, texttemplatesrc=None, uid=None, uirevision=None, unselected=None, visible=None, xaxis=None, yaxis=None, zorder=None, row=None, col=None, secondary_y=None, **kwargs, ) -> "Figure": """ Add a new Scattercarpet trace Plots a scatter trace on either the first carpet axis or the carpet axis with a matching `carpet` attribute. Parameters ---------- a Sets the a-axis coordinates. asrc Sets the source reference on Chart Studio Cloud for `a`. b Sets the b-axis coordinates. bsrc Sets the source reference on Chart Studio Cloud for `b`. carpet An identifier for this carpet, so that `scattercarpet` and `contourcarpet` traces can specify a carpet plot on which they lie connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. 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`. fill Sets the area to fill with a solid color. Use with `fillcolor` if not "none". scatterternary has a subset of the options available to scatter. "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. "tonext" fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like "toself" if there is no trace before it. "tonext" should not be used if one trace does not enclose the other. 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.scattercarpet.Hoverlabel` instance or dict with compatible properties hoveron Do the hover effects highlight individual points (markers or line points) or do they highlight filled regions? If the fill is "toself" or "tonext" and there are no markers or text, then the default is "fills", otherwise it is "points". 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. hovertemplatesrc Sets the source reference on Chart Studio Cloud for `hovertemplate`. hovertext Sets hover text elements associated with each (a,b) point. If a single string, the same string appears over all the data points. If an array of strings, the items are mapped in order to the the data points in (a,b). 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`. 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.scattercarpet.Legendgroupt itle` 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.scattercarpet.Line` instance or dict with compatible properties marker :class:`plotly.graph_objects.scattercarpet.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`. mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points and the trace is not stacked then the default is "lines+markers". Otherwise, "lines". 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.scattercarpet.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. stream :class:`plotly.graph_objects.scattercarpet.Stream` instance or dict with compatible properties text Sets text elements associated with each (a,b) point. If a single string, the same string appears over all the data points. If an array of strings, the items are mapped in order to the the data points in (a,b). If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the text font. textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. 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 appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `a`, `b` and `text`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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. unselected :class:`plotly.graph_objects.scattercarpet.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). 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. 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. 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`. 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. Returns ------- Figure """ from plotly.graph_objs import Scattercarpet new_trace = Scattercarpet( a=a, asrc=asrc, b=b, bsrc=bsrc, carpet=carpet, connectgaps=connectgaps, customdata=customdata, customdatasrc=customdatasrc, fill=fill, fillcolor=fillcolor, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hoveron=hoveron, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, line=line, marker=marker, meta=meta, metasrc=metasrc, mode=mode, name=name, opacity=opacity, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, text=text, textfont=textfont, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, texttemplatesrc=texttemplatesrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, xaxis=xaxis, yaxis=yaxis, zorder=zorder, **kwargs, ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_scattergeo( self, connectgaps=None, customdata=None, customdatasrc=None, featureidkey=None, fill=None, fillcolor=None, geo=None, geojson=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, lat=None, latsrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, line=None, locationmode=None, locations=None, locationssrc=None, lon=None, lonsrc=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, selected=None, selectedpoints=None, showlegend=None, stream=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatefallback=None, texttemplatesrc=None, uid=None, uirevision=None, unselected=None, visible=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Scattergeo trace The data visualized as scatter point or lines on a geographic map is provided either by longitude/latitude pairs in `lon` and `lat` respectively or by geographic location IDs or names in `locations`. Parameters ---------- connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. 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`. featureidkey Sets the key in GeoJSON features which is used as id to match the items included in the `locations` array. Only has an effect when `geojson` is set. Support nested property, for example "properties.name". fill Sets the area to fill with a solid color. Use with `fillcolor` if not "none". "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. fillcolor Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. geo Sets a reference between this trace's geospatial coordinates and a geographic map. If "geo" (the default value), the geospatial coordinates refer to `layout.geo`. If "geo2", the geospatial coordinates refer to `layout.geo2`, and so on. geojson Sets optional GeoJSON data associated with this trace. If not given, the features on the base map are used when `locations` is set. It can be set as a valid GeoJSON object or as a URL string. Note that we only accept GeoJSONs of type "FeatureCollection" or "Feature" with geometries of type "Polygon" or "MultiPolygon". 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.scattergeo.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. hovertemplatesrc Sets the source reference on Chart Studio Cloud for `hovertemplate`. hovertext Sets hover text elements associated with each (lon,lat) pair or item in `locations`. 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 (lon,lat) or `locations` 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`. lat Sets the latitude coordinates (in degrees North). latsrc Sets the source reference on Chart Studio Cloud for `lat`. 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.scattergeo.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. line :class:`plotly.graph_objects.scattergeo.Line` instance or dict with compatible properties locationmode The library used by the *country names* `locationmode` option is changing in an upcoming version. Country names in existing plots may not work in the new version. Determines the set of locations used to match entries in `locations` to regions on the map. Values "ISO-3", "USA-states", *country names* correspond to features on the base map and value "geojson-id" corresponds to features from a custom GeoJSON linked to the `geojson` attribute. locations Sets the coordinates via location IDs or names. Coordinates correspond to the centroid of each location given. See `locationmode` for more info. locationssrc Sets the source reference on Chart Studio Cloud for `locations`. lon Sets the longitude coordinates (in degrees East). lonsrc Sets the source reference on Chart Studio Cloud for `lon`. marker :class:`plotly.graph_objects.scattergeo.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`. mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points and the trace is not stacked then the default is "lines+markers". Otherwise, "lines". 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.scattergeo.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. stream :class:`plotly.graph_objects.scattergeo.Stream` instance or dict with compatible properties text Sets text elements associated with each (lon,lat) pair or item in `locations`. 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 (lon,lat) or `locations` coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the text font. textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. 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 appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `lat`, `lon`, `location` and `text`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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. unselected :class:`plotly.graph_objects.scattergeo.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). 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). Returns ------- Figure """ from plotly.graph_objs import Scattergeo new_trace = Scattergeo( connectgaps=connectgaps, customdata=customdata, customdatasrc=customdatasrc, featureidkey=featureidkey, fill=fill, fillcolor=fillcolor, geo=geo, geojson=geojson, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, lat=lat, latsrc=latsrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, line=line, locationmode=locationmode, locations=locations, locationssrc=locationssrc, lon=lon, lonsrc=lonsrc, marker=marker, meta=meta, metasrc=metasrc, mode=mode, name=name, opacity=opacity, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, text=text, textfont=textfont, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, texttemplatesrc=texttemplatesrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_scattergl( self, connectgaps=None, customdata=None, customdatasrc=None, dx=None, dy=None, error_x=None, error_y=None, fill=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, line=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, selected=None, selectedpoints=None, showlegend=None, stream=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatefallback=None, texttemplatesrc=None, uid=None, uirevision=None, unselected=None, visible=None, x=None, x0=None, xaxis=None, xcalendar=None, xhoverformat=None, xperiod=None, xperiod0=None, xperiodalignment=None, xsrc=None, y=None, y0=None, yaxis=None, ycalendar=None, yhoverformat=None, yperiod=None, yperiod0=None, yperiodalignment=None, ysrc=None, row=None, col=None, secondary_y=None, **kwargs, ) -> "Figure": """ Add a new Scattergl trace The data visualized as scatter point or lines is set in `x` and `y` using the WebGL plotting engine. Bubble charts are achieved by setting `marker.size` and/or `marker.color` to a numerical arrays. Parameters ---------- connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. 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. error_x :class:`plotly.graph_objects.scattergl.ErrorX` instance or dict with compatible properties error_y :class:`plotly.graph_objects.scattergl.ErrorY` instance or dict with compatible properties fill Sets the area to fill with a solid color. Defaults to "none" unless this trace is stacked, then it gets "tonexty" ("tonextx") if `orientation` is "v" ("h") Use with `fillcolor` if not "none". "tozerox" and "tozeroy" fill to x=0 and y=0 respectively. "tonextx" and "tonexty" fill between the endpoints of this trace and the endpoints of the trace before it, connecting those endpoints with straight lines (to make a stacked area graph); if there is no trace before it, they behave like "tozerox" and "tozeroy". "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. "tonext" fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like "toself" if there is no trace before it. "tonext" should not be used if one trace does not enclose the other. Traces in a `stackgroup` will only fill to (or be filled to) other traces in the same group. With multiple `stackgroup`s or some traces stacked and some not, if fill-linked traces are not already consecutive, the later ones will be pushed down in the drawing order. 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.scattergl.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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`. 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.scattergl.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.scattergl.Line` instance or dict with compatible properties marker :class:`plotly.graph_objects.scattergl.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`. mode Determines the drawing mode for this scatter trace. 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.scattergl.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. stream :class:`plotly.graph_objects.scattergl.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. textfont Sets the text font. textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. 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 appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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. unselected :class:`plotly.graph_objects.scattergl.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). 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. xcalendar Sets the calendar system to use with `x` date data. 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. ycalendar Sets the calendar system to use with `y` date data. 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`. 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. Returns ------- Figure """ from plotly.graph_objs import Scattergl new_trace = Scattergl( connectgaps=connectgaps, customdata=customdata, customdatasrc=customdatasrc, dx=dx, dy=dy, error_x=error_x, error_y=error_y, fill=fill, fillcolor=fillcolor, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, line=line, marker=marker, meta=meta, metasrc=metasrc, mode=mode, name=name, opacity=opacity, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, text=text, textfont=textfont, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, texttemplatesrc=texttemplatesrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, x=x, x0=x0, xaxis=xaxis, xcalendar=xcalendar, xhoverformat=xhoverformat, xperiod=xperiod, xperiod0=xperiod0, xperiodalignment=xperiodalignment, xsrc=xsrc, y=y, y0=y0, yaxis=yaxis, ycalendar=ycalendar, yhoverformat=yhoverformat, yperiod=yperiod, yperiod0=yperiod0, yperiodalignment=yperiodalignment, ysrc=ysrc, **kwargs, ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_scattermap( self, below=None, cluster=None, connectgaps=None, customdata=None, customdatasrc=None, fill=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, lat=None, latsrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, line=None, lon=None, lonsrc=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, selected=None, selectedpoints=None, showlegend=None, stream=None, subplot=None, text=None, textfont=None, textposition=None, textsrc=None, texttemplate=None, texttemplatefallback=None, texttemplatesrc=None, uid=None, uirevision=None, unselected=None, visible=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Scattermap trace The data visualized as scatter point, lines or marker symbols on a MapLibre GL geographic map is provided by longitude/latitude pairs in `lon` and `lat`. Parameters ---------- below Determines if this scattermap trace's layers are to be inserted before the layer with the specified ID. By default, scattermap layers are inserted above all the base layers. To place the scattermap layers above every other layer, set `below` to "''". cluster :class:`plotly.graph_objects.scattermap.Cluster` instance or dict with compatible properties connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. 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`. fill Sets the area to fill with a solid color. Use with `fillcolor` if not "none". "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. 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.scattermap.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. hovertemplatesrc Sets the source reference on Chart Studio Cloud for `hovertemplate`. hovertext Sets hover text elements associated with each (lon,lat) 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 (lon,lat) 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`. lat Sets the latitude coordinates (in degrees North). latsrc Sets the source reference on Chart Studio Cloud for `lat`. 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.scattermap.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. line :class:`plotly.graph_objects.scattermap.Line` instance or dict with compatible properties lon Sets the longitude coordinates (in degrees East). lonsrc Sets the source reference on Chart Studio Cloud for `lon`. marker :class:`plotly.graph_objects.scattermap.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`. mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. 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.scattermap.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. stream :class:`plotly.graph_objects.scattermap.Stream` instance or dict with compatible properties subplot Sets a reference between this trace's data coordinates and a map subplot. If "map" (the default value), the data refer to `layout.map`. If "map2", the data refer to `layout.map2`, and so on. text Sets text elements associated with each (lon,lat) 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 (lon,lat) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the icon text font (color=map.layer.paint.text- color, size=map.layer.layout.text-size). Has an effect only when `type` is set to "symbol". textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. textsrc Sets the source reference on Chart Studio Cloud for `text`. texttemplate Template string used for rendering the information text that appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `lat`, `lon` and `text`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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. unselected :class:`plotly.graph_objects.scattermap.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). 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). Returns ------- Figure """ from plotly.graph_objs import Scattermap new_trace = Scattermap( below=below, cluster=cluster, connectgaps=connectgaps, customdata=customdata, customdatasrc=customdatasrc, fill=fill, fillcolor=fillcolor, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, lat=lat, latsrc=latsrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, line=line, lon=lon, lonsrc=lonsrc, marker=marker, meta=meta, metasrc=metasrc, mode=mode, name=name, opacity=opacity, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, subplot=subplot, text=text, textfont=textfont, textposition=textposition, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, texttemplatesrc=texttemplatesrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_scattermapbox( self, below=None, cluster=None, connectgaps=None, customdata=None, customdatasrc=None, fill=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, lat=None, latsrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, line=None, lon=None, lonsrc=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, selected=None, selectedpoints=None, showlegend=None, stream=None, subplot=None, text=None, textfont=None, textposition=None, textsrc=None, texttemplate=None, texttemplatefallback=None, texttemplatesrc=None, uid=None, uirevision=None, unselected=None, visible=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Scattermapbox trace "scattermapbox" trace is deprecated! Please consider switching to the "scattermap" trace type and `map` subplots. Learn more at: https://plotly.com/python/maplibre-migration/ as well as https://plotly.com/javascript/maplibre-migration/ The data visualized as scatter point, lines or marker symbols on a Mapbox GL geographic map is provided by longitude/latitude pairs in `lon` and `lat`. Parameters ---------- below Determines if this scattermapbox trace's layers are to be inserted before the layer with the specified ID. By default, scattermapbox layers are inserted above all the base layers. To place the scattermapbox layers above every other layer, set `below` to "''". cluster :class:`plotly.graph_objects.scattermapbox.Cluster` instance or dict with compatible properties connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. 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`. fill Sets the area to fill with a solid color. Use with `fillcolor` if not "none". "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. 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.scattermapbox.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. hovertemplatesrc Sets the source reference on Chart Studio Cloud for `hovertemplate`. hovertext Sets hover text elements associated with each (lon,lat) 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 (lon,lat) 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`. lat Sets the latitude coordinates (in degrees North). latsrc Sets the source reference on Chart Studio Cloud for `lat`. 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.scattermapbox.Legendgroupt itle` 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.scattermapbox.Line` instance or dict with compatible properties lon Sets the longitude coordinates (in degrees East). lonsrc Sets the source reference on Chart Studio Cloud for `lon`. marker :class:`plotly.graph_objects.scattermapbox.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`. mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. 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.scattermapbox.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. stream :class:`plotly.graph_objects.scattermapbox.Stream` instance or dict with compatible properties subplot mapbox subplots and traces are deprecated! Please consider switching to `map` subplots and traces. Learn more at: https://plotly.com/python/maplibre-migration/ as well as https://plotly.com/javascript/maplibre- migration/ Sets a reference between this trace's data coordinates and a mapbox subplot. If "mapbox" (the default value), the data refer to `layout.mapbox`. If "mapbox2", the data refer to `layout.mapbox2`, and so on. text Sets text elements associated with each (lon,lat) 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 (lon,lat) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the icon text font (color=mapbox.layer.paint.text- color, size=mapbox.layer.layout.text-size). Has an effect only when `type` is set to "symbol". textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. textsrc Sets the source reference on Chart Studio Cloud for `text`. texttemplate Template string used for rendering the information text that appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `lat`, `lon` and `text`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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. unselected :class:`plotly.graph_objects.scattermapbox.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). 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). Returns ------- Figure """ from plotly.graph_objs import Scattermapbox new_trace = Scattermapbox( below=below, cluster=cluster, connectgaps=connectgaps, customdata=customdata, customdatasrc=customdatasrc, fill=fill, fillcolor=fillcolor, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, lat=lat, latsrc=latsrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, line=line, lon=lon, lonsrc=lonsrc, marker=marker, meta=meta, metasrc=metasrc, mode=mode, name=name, opacity=opacity, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, subplot=subplot, text=text, textfont=textfont, textposition=textposition, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, texttemplatesrc=texttemplatesrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_scatterpolar( self, cliponaxis=None, connectgaps=None, customdata=None, customdatasrc=None, dr=None, dtheta=None, fill=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hoveron=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, line=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, r=None, r0=None, rsrc=None, selected=None, selectedpoints=None, showlegend=None, stream=None, subplot=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatefallback=None, texttemplatesrc=None, theta=None, theta0=None, thetasrc=None, thetaunit=None, uid=None, uirevision=None, unselected=None, visible=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Scatterpolar trace The scatterpolar trace type encompasses line charts, scatter charts, text charts, and bubble charts in polar coordinates. The data visualized as scatter point or lines is set in `r` (radial) and `theta` (angular) coordinates Text (appearing either on the chart or on hover only) is via `text`. Bubble charts are achieved by setting `marker.size` and/or `marker.color` to numerical arrays. Parameters ---------- cliponaxis Determines whether or not markers and text nodes are clipped about the subplot axes. To show markers and text nodes above axis lines and tick labels, make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*. connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. 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`. dr Sets the r coordinate step. dtheta Sets the theta coordinate step. By default, the `dtheta` step equals the subplot's period divided by the length of the `r` coordinates. fill Sets the area to fill with a solid color. Use with `fillcolor` if not "none". scatterpolar has a subset of the options available to scatter. "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. "tonext" fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like "toself" if there is no trace before it. "tonext" should not be used if one trace does not enclose the other. 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.scatterpolar.Hoverlabel` instance or dict with compatible properties hoveron Do the hover effects highlight individual points (markers or line points) or do they highlight filled regions? If the fill is "toself" or "tonext" and there are no markers or text, then the default is "fills", otherwise it is "points". 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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`. 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.scatterpolar.Legendgroupti tle` 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.scatterpolar.Line` instance or dict with compatible properties marker :class:`plotly.graph_objects.scatterpolar.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`. mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points and the trace is not stacked then the default is "lines+markers". Otherwise, "lines". name Sets the trace name. The trace name appears as the legend item and on hover. opacity Sets the opacity of the trace. r Sets the radial coordinates r0 Alternate to `r`. Builds a linear space of r coordinates. Use with `dr` where `r0` is the starting coordinate and `dr` the step. rsrc Sets the source reference on Chart Studio Cloud for `r`. selected :class:`plotly.graph_objects.scatterpolar.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. stream :class:`plotly.graph_objects.scatterpolar.Stream` instance or dict with compatible properties subplot Sets a reference between this trace's data coordinates and a polar subplot. If "polar" (the default value), the data refer to `layout.polar`. If "polar2", the data refer to `layout.polar2`, and so on. 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. textfont Sets the text font. textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. 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 appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `r`, `theta` and `text`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. texttemplatesrc Sets the source reference on Chart Studio Cloud for `texttemplate`. theta Sets the angular coordinates theta0 Alternate to `theta`. Builds a linear space of theta coordinates. Use with `dtheta` where `theta0` is the starting coordinate and `dtheta` the step. thetasrc Sets the source reference on Chart Studio Cloud for `theta`. thetaunit Sets the unit of input "theta" values. Has an effect only when on "linear" angular axes. 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.scatterpolar.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). 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). Returns ------- Figure """ from plotly.graph_objs import Scatterpolar new_trace = Scatterpolar( cliponaxis=cliponaxis, connectgaps=connectgaps, customdata=customdata, customdatasrc=customdatasrc, dr=dr, dtheta=dtheta, fill=fill, fillcolor=fillcolor, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hoveron=hoveron, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, line=line, marker=marker, meta=meta, metasrc=metasrc, mode=mode, name=name, opacity=opacity, r=r, r0=r0, rsrc=rsrc, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, subplot=subplot, text=text, textfont=textfont, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, texttemplatesrc=texttemplatesrc, theta=theta, theta0=theta0, thetasrc=thetasrc, thetaunit=thetaunit, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_scatterpolargl( self, connectgaps=None, customdata=None, customdatasrc=None, dr=None, dtheta=None, fill=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, line=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, r=None, r0=None, rsrc=None, selected=None, selectedpoints=None, showlegend=None, stream=None, subplot=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatefallback=None, texttemplatesrc=None, theta=None, theta0=None, thetasrc=None, thetaunit=None, uid=None, uirevision=None, unselected=None, visible=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Scatterpolargl trace The scatterpolargl trace type encompasses line charts, scatter charts, and bubble charts in polar coordinates using the WebGL plotting engine. The data visualized as scatter point or lines is set in `r` (radial) and `theta` (angular) coordinates Bubble charts are achieved by setting `marker.size` and/or `marker.color` to numerical arrays. Parameters ---------- connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. 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`. dr Sets the r coordinate step. dtheta Sets the theta coordinate step. By default, the `dtheta` step equals the subplot's period divided by the length of the `r` coordinates. fill Sets the area to fill with a solid color. Defaults to "none" unless this trace is stacked, then it gets "tonexty" ("tonextx") if `orientation` is "v" ("h") Use with `fillcolor` if not "none". "tozerox" and "tozeroy" fill to x=0 and y=0 respectively. "tonextx" and "tonexty" fill between the endpoints of this trace and the endpoints of the trace before it, connecting those endpoints with straight lines (to make a stacked area graph); if there is no trace before it, they behave like "tozerox" and "tozeroy". "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. "tonext" fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like "toself" if there is no trace before it. "tonext" should not be used if one trace does not enclose the other. Traces in a `stackgroup` will only fill to (or be filled to) other traces in the same group. With multiple `stackgroup`s or some traces stacked and some not, if fill-linked traces are not already consecutive, the later ones will be pushed down in the drawing order. 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.scatterpolargl.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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`. 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.scatterpolargl.Legendgroup title` 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.scatterpolargl.Line` instance or dict with compatible properties marker :class:`plotly.graph_objects.scatterpolargl.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`. mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points and the trace is not stacked then the default is "lines+markers". Otherwise, "lines". name Sets the trace name. The trace name appears as the legend item and on hover. opacity Sets the opacity of the trace. r Sets the radial coordinates r0 Alternate to `r`. Builds a linear space of r coordinates. Use with `dr` where `r0` is the starting coordinate and `dr` the step. rsrc Sets the source reference on Chart Studio Cloud for `r`. selected :class:`plotly.graph_objects.scatterpolargl.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. stream :class:`plotly.graph_objects.scatterpolargl.Stream` instance or dict with compatible properties subplot Sets a reference between this trace's data coordinates and a polar subplot. If "polar" (the default value), the data refer to `layout.polar`. If "polar2", the data refer to `layout.polar2`, and so on. 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. textfont Sets the text font. textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. 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 appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `r`, `theta` and `text`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. texttemplatesrc Sets the source reference on Chart Studio Cloud for `texttemplate`. theta Sets the angular coordinates theta0 Alternate to `theta`. Builds a linear space of theta coordinates. Use with `dtheta` where `theta0` is the starting coordinate and `dtheta` the step. thetasrc Sets the source reference on Chart Studio Cloud for `theta`. thetaunit Sets the unit of input "theta" values. Has an effect only when on "linear" angular axes. 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.scatterpolargl.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). 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). Returns ------- Figure """ from plotly.graph_objs import Scatterpolargl new_trace = Scatterpolargl( connectgaps=connectgaps, customdata=customdata, customdatasrc=customdatasrc, dr=dr, dtheta=dtheta, fill=fill, fillcolor=fillcolor, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, line=line, marker=marker, meta=meta, metasrc=metasrc, mode=mode, name=name, opacity=opacity, r=r, r0=r0, rsrc=rsrc, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, subplot=subplot, text=text, textfont=textfont, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, texttemplatesrc=texttemplatesrc, theta=theta, theta0=theta0, thetasrc=thetasrc, thetaunit=thetaunit, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_scattersmith( self, cliponaxis=None, connectgaps=None, customdata=None, customdatasrc=None, fill=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hoveron=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, imag=None, imagsrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, line=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, real=None, realsrc=None, selected=None, selectedpoints=None, showlegend=None, stream=None, subplot=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatefallback=None, texttemplatesrc=None, uid=None, uirevision=None, unselected=None, visible=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Scattersmith trace The scattersmith trace type encompasses line charts, scatter charts, text charts, and bubble charts in smith coordinates. The data visualized as scatter point or lines is set in `real` and `imag` (imaginary) coordinates Text (appearing either on the chart or on hover only) is via `text`. Bubble charts are achieved by setting `marker.size` and/or `marker.color` to numerical arrays. Parameters ---------- cliponaxis Determines whether or not markers and text nodes are clipped about the subplot axes. To show markers and text nodes above axis lines and tick labels, make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*. connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. 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`. fill Sets the area to fill with a solid color. Use with `fillcolor` if not "none". scattersmith has a subset of the options available to scatter. "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. "tonext" fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like "toself" if there is no trace before it. "tonext" should not be used if one trace does not enclose the other. 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.scattersmith.Hoverlabel` instance or dict with compatible properties hoveron Do the hover effects highlight individual points (markers or line points) or do they highlight filled regions? If the fill is "toself" or "tonext" and there are no markers or text, then the default is "fills", otherwise it is "points". 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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`. imag Sets the imaginary component of the data, in units of normalized impedance such that real=1, imag=0 is the center of the chart. imagsrc Sets the source reference on Chart Studio Cloud for `imag`. 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.scattersmith.Legendgroupti tle` 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.scattersmith.Line` instance or dict with compatible properties marker :class:`plotly.graph_objects.scattersmith.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`. mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points and the trace is not stacked then the default is "lines+markers". Otherwise, "lines". name Sets the trace name. The trace name appears as the legend item and on hover. opacity Sets the opacity of the trace. real Sets the real component of the data, in units of normalized impedance such that real=1, imag=0 is the center of the chart. realsrc Sets the source reference on Chart Studio Cloud for `real`. selected :class:`plotly.graph_objects.scattersmith.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. stream :class:`plotly.graph_objects.scattersmith.Stream` instance or dict with compatible properties subplot Sets a reference between this trace's data coordinates and a smith subplot. If "smith" (the default value), the data refer to `layout.smith`. If "smith2", the data refer to `layout.smith2`, and so on. 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. textfont Sets the text font. textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. 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 appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `real`, `imag` and `text`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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. unselected :class:`plotly.graph_objects.scattersmith.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). 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). Returns ------- Figure """ from plotly.graph_objs import Scattersmith new_trace = Scattersmith( cliponaxis=cliponaxis, connectgaps=connectgaps, customdata=customdata, customdatasrc=customdatasrc, fill=fill, fillcolor=fillcolor, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hoveron=hoveron, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, imag=imag, imagsrc=imagsrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, line=line, marker=marker, meta=meta, metasrc=metasrc, mode=mode, name=name, opacity=opacity, real=real, realsrc=realsrc, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, subplot=subplot, text=text, textfont=textfont, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, texttemplatesrc=texttemplatesrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_scatterternary( self, a=None, asrc=None, b=None, bsrc=None, c=None, cliponaxis=None, connectgaps=None, csrc=None, customdata=None, customdatasrc=None, fill=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hoveron=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, line=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, selected=None, selectedpoints=None, showlegend=None, stream=None, subplot=None, sum=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatefallback=None, texttemplatesrc=None, uid=None, uirevision=None, unselected=None, visible=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Scatterternary trace Provides similar functionality to the "scatter" type but on a ternary phase diagram. The data is provided by at least two arrays out of `a`, `b`, `c` triplets. Parameters ---------- a Sets the quantity of component `a` in each data point. If `a`, `b`, and `c` are all provided, they need not be normalized, only the relative values matter. If only two arrays are provided they must be normalized to match `ternary<i>.sum`. asrc Sets the source reference on Chart Studio Cloud for `a`. b Sets the quantity of component `a` in each data point. If `a`, `b`, and `c` are all provided, they need not be normalized, only the relative values matter. If only two arrays are provided they must be normalized to match `ternary<i>.sum`. bsrc Sets the source reference on Chart Studio Cloud for `b`. c Sets the quantity of component `a` in each data point. If `a`, `b`, and `c` are all provided, they need not be normalized, only the relative values matter. If only two arrays are provided they must be normalized to match `ternary<i>.sum`. cliponaxis Determines whether or not markers and text nodes are clipped about the subplot axes. To show markers and text nodes above axis lines and tick labels, make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*. connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. csrc Sets the source reference on Chart Studio Cloud for `c`. 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`. fill Sets the area to fill with a solid color. Use with `fillcolor` if not "none". scatterternary has a subset of the options available to scatter. "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. "tonext" fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like "toself" if there is no trace before it. "tonext" should not be used if one trace does not enclose the other. 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.scatterternary.Hoverlabel` instance or dict with compatible properties hoveron Do the hover effects highlight individual points (markers or line points) or do they highlight filled regions? If the fill is "toself" or "tonext" and there are no markers or text, then the default is "fills", otherwise it is "points". 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. hovertemplatesrc Sets the source reference on Chart Studio Cloud for `hovertemplate`. hovertext Sets hover text elements associated with each (a,b,c) point. If a single string, the same string appears over all the data points. If an array of strings, the items are mapped in order to the the data points in (a,b,c). 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`. 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.scatterternary.Legendgroup title` 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.scatterternary.Line` instance or dict with compatible properties marker :class:`plotly.graph_objects.scatterternary.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`. mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points and the trace is not stacked then the default is "lines+markers". Otherwise, "lines". 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.scatterternary.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. stream :class:`plotly.graph_objects.scatterternary.Stream` instance or dict with compatible properties subplot Sets a reference between this trace's data coordinates and a ternary subplot. If "ternary" (the default value), the data refer to `layout.ternary`. If "ternary2", the data refer to `layout.ternary2`, and so on. sum The number each triplet should sum to, if only two of `a`, `b`, and `c` are provided. This overrides `ternary<i>.sum` to normalize this specific trace, but does not affect the values displayed on the axes. 0 (or missing) means to use ternary<i>.sum text Sets text elements associated with each (a,b,c) point. If a single string, the same string appears over all the data points. If an array of strings, the items are mapped in order to the the data points in (a,b,c). If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the text font. textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. 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 appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `a`, `b`, `c` and `text`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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. unselected :class:`plotly.graph_objects.scatterternary.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). 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). Returns ------- Figure """ from plotly.graph_objs import Scatterternary new_trace = Scatterternary( a=a, asrc=asrc, b=b, bsrc=bsrc, c=c, cliponaxis=cliponaxis, connectgaps=connectgaps, csrc=csrc, customdata=customdata, customdatasrc=customdatasrc, fill=fill, fillcolor=fillcolor, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hoveron=hoveron, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, line=line, marker=marker, meta=meta, metasrc=metasrc, mode=mode, name=name, opacity=opacity, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, subplot=subplot, sum=sum, text=text, textfont=textfont, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, texttemplatesrc=texttemplatesrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_splom( self, customdata=None, customdatasrc=None, diagonal=None, dimensions=None, dimensiondefaults=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=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, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Splom trace 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 ---------- 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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`. 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). Returns ------- Figure """ from plotly.graph_objs import Splom new_trace = Splom( customdata=customdata, customdatasrc=customdatasrc, diagonal=diagonal, dimensions=dimensions, dimensiondefaults=dimensiondefaults, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, marker=marker, meta=meta, metasrc=metasrc, name=name, opacity=opacity, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, showlowerhalf=showlowerhalf, showupperhalf=showupperhalf, stream=stream, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, xaxes=xaxes, xhoverformat=xhoverformat, yaxes=yaxes, yhoverformat=yhoverformat, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_streamtube( self, autocolorscale=None, cauto=None, cmax=None, cmid=None, cmin=None, coloraxis=None, colorbar=None, colorscale=None, customdata=None, customdatasrc=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, ids=None, idssrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, lighting=None, lightposition=None, maxdisplayed=None, meta=None, metasrc=None, name=None, opacity=None, reversescale=None, scene=None, showlegend=None, showscale=None, sizeref=None, starts=None, stream=None, text=None, u=None, uhoverformat=None, uid=None, uirevision=None, usrc=None, v=None, vhoverformat=None, visible=None, vsrc=None, w=None, whoverformat=None, wsrc=None, x=None, xhoverformat=None, xsrc=None, y=None, yhoverformat=None, ysrc=None, z=None, zhoverformat=None, zsrc=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Streamtube trace Use a streamtube trace to visualize flow in a vector field. Specify a vector field using 6 1D arrays of equal length, 3 position arrays `x`, `y` and `z` and 3 vector component arrays `u`, `v`, and `w`. By default, the tubes' starting positions will be cut from the vector field's x-z plane at its minimum y value. To specify your own starting position, use attributes `starts.x`, `starts.y` and `starts.z`. The color is encoded by the norm of (u, v, w), and the local radius by the divergence of (u, v, w). Parameters ---------- 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 u/v/w norm) 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 u/v/w norm 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 u/v/w norm. Has no effect when `cauto` is `false`. cmin Sets the lower bound of the color domain. Value should have the same units as u/v/w norm and if set, `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.streamtube.ColorBar` 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: Blackbody,Bluered,Blues,C ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd. 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`. 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.streamtube.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `tubex`, `tubey`, `tubez`, `tubeu`, `tubev`, `tubew`, `norm` and `divergence`. 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. hovertemplatesrc Sets the source reference on Chart Studio Cloud for `hovertemplate`. hovertext Same as `text`. 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.streamtube.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. lighting :class:`plotly.graph_objects.streamtube.Lighting` instance or dict with compatible properties lightposition :class:`plotly.graph_objects.streamtube.Lightposition` instance or dict with compatible properties maxdisplayed The maximum number of displayed segments in a streamtube. 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 surface. Please note that in the case of using high `opacity` values for example a value greater than or equal to 0.5 on two surfaces (and 0.25 with four surfaces), an overlay of multiple transparent surfaces may not perfectly be sorted in depth by the webgl API. This behavior may be improved in the near future and is subject to change. 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. scene Sets a reference between this trace's 3D coordinate system and a 3D scene. If "scene" (the default value), the (x,y,z) coordinates refer to `layout.scene`. If "scene2", the (x,y,z) coordinates refer to `layout.scene2`, and so on. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. sizeref The scaling factor for the streamtubes. The default is 1, which avoids two max divergence tubes from touching at adjacent starting positions. starts :class:`plotly.graph_objects.streamtube.Starts` instance or dict with compatible properties stream :class:`plotly.graph_objects.streamtube.Stream` instance or dict with compatible properties text Sets a text element associated with this trace. If trace `hoverinfo` contains a "text" flag, this text element will be seen in all hover labels. Note that streamtube traces do not support array `text` values. u Sets the x components of the vector field. uhoverformat Sets the hover text formatting rulefor `u` using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d 3/d3-format/tree/v1.4.5#d3-format.By default the values are formatted using generic number format. 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. usrc Sets the source reference on Chart Studio Cloud for `u`. v Sets the y components of the vector field. vhoverformat Sets the hover text formatting rulefor `v` using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d 3/d3-format/tree/v1.4.5#d3-format.By default the values are formatted using generic number format. 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). vsrc Sets the source reference on Chart Studio Cloud for `v`. w Sets the z components of the vector field. whoverformat Sets the hover text formatting rulefor `w` using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d 3/d3-format/tree/v1.4.5#d3-format.By default the values are formatted using generic number format. wsrc Sets the source reference on Chart Studio Cloud for `w`. x Sets the x coordinates of the vector field. 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 coordinates of the vector field. 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`. z Sets the z coordinates of the vector field. zhoverformat Sets the hover text formatting rulefor `z` 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 `zaxis.hoverformat`. zsrc Sets the source reference on Chart Studio Cloud for `z`. 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). Returns ------- Figure """ from plotly.graph_objs import Streamtube new_trace = Streamtube( autocolorscale=autocolorscale, cauto=cauto, cmax=cmax, cmid=cmid, cmin=cmin, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, customdata=customdata, customdatasrc=customdatasrc, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, ids=ids, idssrc=idssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, lighting=lighting, lightposition=lightposition, maxdisplayed=maxdisplayed, meta=meta, metasrc=metasrc, name=name, opacity=opacity, reversescale=reversescale, scene=scene, showlegend=showlegend, showscale=showscale, sizeref=sizeref, starts=starts, stream=stream, text=text, u=u, uhoverformat=uhoverformat, uid=uid, uirevision=uirevision, usrc=usrc, v=v, vhoverformat=vhoverformat, visible=visible, vsrc=vsrc, w=w, whoverformat=whoverformat, wsrc=wsrc, x=x, xhoverformat=xhoverformat, xsrc=xsrc, y=y, yhoverformat=yhoverformat, ysrc=ysrc, z=z, zhoverformat=zhoverformat, zsrc=zsrc, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_sunburst( self, branchvalues=None, count=None, customdata=None, customdatasrc=None, domain=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=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, texttemplatefallback=None, texttemplatesrc=None, uid=None, uirevision=None, values=None, valuessrc=None, visible=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Sunburst trace 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 ---------- 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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 appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All 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`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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). 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). Returns ------- Figure """ from plotly.graph_objs import Sunburst new_trace = Sunburst( branchvalues=branchvalues, count=count, customdata=customdata, customdatasrc=customdatasrc, domain=domain, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, insidetextfont=insidetextfont, insidetextorientation=insidetextorientation, labels=labels, labelssrc=labelssrc, leaf=leaf, legend=legend, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, level=level, marker=marker, maxdepth=maxdepth, meta=meta, metasrc=metasrc, name=name, opacity=opacity, outsidetextfont=outsidetextfont, parents=parents, parentssrc=parentssrc, root=root, rotation=rotation, sort=sort, stream=stream, text=text, textfont=textfont, textinfo=textinfo, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, texttemplatesrc=texttemplatesrc, uid=uid, uirevision=uirevision, values=values, valuessrc=valuessrc, visible=visible, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_surface( self, autocolorscale=None, cauto=None, cmax=None, cmid=None, cmin=None, coloraxis=None, colorbar=None, colorscale=None, connectgaps=None, contours=None, customdata=None, customdatasrc=None, hidesurface=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, lighting=None, lightposition=None, meta=None, metasrc=None, name=None, opacity=None, opacityscale=None, reversescale=None, scene=None, showlegend=None, showscale=None, stream=None, surfacecolor=None, surfacecolorsrc=None, text=None, textsrc=None, uid=None, uirevision=None, visible=None, x=None, xcalendar=None, xhoverformat=None, xsrc=None, y=None, ycalendar=None, yhoverformat=None, ysrc=None, z=None, zcalendar=None, zhoverformat=None, zsrc=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Surface trace The data the describes the coordinates of the surface is set in `z`. Data in `z` should be a 2D list. Coordinates in `x` and `y` can either be 1D lists or 2D lists (e.g. to graph parametric surfaces). If not provided in `x` and `y`, the x and y coordinates are assumed to be linear starting at 0 with a unit step. The color scale corresponds to the `z` values by default. For custom color scales, use `surfacecolor` which should be a 2D list, where its bounds can be controlled using `cmin` and `cmax`. Parameters ---------- 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 z or surfacecolor) 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 z or surfacecolor 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 z or surfacecolor. Has no effect when `cauto` is `false`. cmin Sets the lower bound of the color domain. Value should have the same units as z or surfacecolor and if set, `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.surface.ColorBar` 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: Blackbody,Bluered,Blues,C ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd. connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data are filled in. contours :class:`plotly.graph_objects.surface.Contours` 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`. hidesurface Determines whether or not a surface is drawn. For example, set `hidesurface` to False `contours.x.show` to True and `contours.y.show` to True to draw a wire frame plot. 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.surface.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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.surface.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. lighting :class:`plotly.graph_objects.surface.Lighting` instance or dict with compatible properties lightposition :class:`plotly.graph_objects.surface.Lightposition` 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 surface. Please note that in the case of using high `opacity` values for example a value greater than or equal to 0.5 on two surfaces (and 0.25 with four surfaces), an overlay of multiple transparent surfaces may not perfectly be sorted in depth by the webgl API. This behavior may be improved in the near future and is subject to change. opacityscale Sets the opacityscale. The opacityscale must be an array containing arrays mapping a normalized value to an opacity value. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 1], [0.5, 0.2], [1, 1]]` means that higher/lower values would have higher opacity values and those in the middle would be more transparent Alternatively, `opacityscale` may be a palette name string of the following list: 'min', 'max', 'extremes' and 'uniform'. The default is 'uniform'. 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. scene Sets a reference between this trace's 3D coordinate system and a 3D scene. If "scene" (the default value), the (x,y,z) coordinates refer to `layout.scene`. If "scene2", the (x,y,z) coordinates refer to `layout.scene2`, and so on. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.surface.Stream` instance or dict with compatible properties surfacecolor Sets the surface color values, used for setting a color scale independent of `z`. surfacecolorsrc Sets the source reference on Chart Studio Cloud for `surfacecolor`. text Sets the text elements associated with each z value. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. 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. 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). x Sets the x coordinates. xcalendar Sets the calendar system to use with `x` date data. 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 coordinates. ycalendar Sets the calendar system to use with `y` date data. 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`. z Sets the z coordinates. zcalendar Sets the calendar system to use with `z` date data. zhoverformat Sets the hover text formatting rulefor `z` 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 `zaxis.hoverformat`. zsrc Sets the source reference on Chart Studio Cloud for `z`. 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). Returns ------- Figure """ from plotly.graph_objs import Surface new_trace = Surface( autocolorscale=autocolorscale, cauto=cauto, cmax=cmax, cmid=cmid, cmin=cmin, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, connectgaps=connectgaps, contours=contours, customdata=customdata, customdatasrc=customdatasrc, hidesurface=hidesurface, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, lighting=lighting, lightposition=lightposition, meta=meta, metasrc=metasrc, name=name, opacity=opacity, opacityscale=opacityscale, reversescale=reversescale, scene=scene, showlegend=showlegend, showscale=showscale, stream=stream, surfacecolor=surfacecolor, surfacecolorsrc=surfacecolorsrc, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, visible=visible, x=x, xcalendar=xcalendar, xhoverformat=xhoverformat, xsrc=xsrc, y=y, ycalendar=ycalendar, yhoverformat=yhoverformat, ysrc=ysrc, z=z, zcalendar=zcalendar, zhoverformat=zhoverformat, zsrc=zsrc, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_table( self, cells=None, columnorder=None, columnordersrc=None, columnwidth=None, columnwidthsrc=None, customdata=None, customdatasrc=None, domain=None, header=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, ids=None, idssrc=None, legend=None, legendgrouptitle=None, legendrank=None, legendwidth=None, meta=None, metasrc=None, name=None, stream=None, uid=None, uirevision=None, visible=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Table trace Table view for detailed data viewing. The data are arranged in a grid of rows and columns. Most styling can be specified for columns, rows or individual cells. Table is using a column- major order, ie. the grid is represented as a vector of column vectors. Parameters ---------- cells :class:`plotly.graph_objects.table.Cells` instance or dict with compatible properties columnorder Specifies the rendered order of the data columns; for example, a value `2` at position `0` means that column index `0` in the data will be rendered as the third column, as columns have an index base of zero. columnordersrc Sets the source reference on Chart Studio Cloud for `columnorder`. columnwidth The width of columns expressed as a ratio. Columns fill the available width in proportion of their specified column widths. columnwidthsrc Sets the source reference on Chart Studio Cloud for `columnwidth`. 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.table.Domain` instance or dict with compatible properties header :class:`plotly.graph_objects.table.Header` 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.table.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.table.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. 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. stream :class:`plotly.graph_objects.table.Stream` 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). 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). Returns ------- Figure """ from plotly.graph_objs import Table new_trace = Table( cells=cells, columnorder=columnorder, columnordersrc=columnordersrc, columnwidth=columnwidth, columnwidthsrc=columnwidthsrc, customdata=customdata, customdatasrc=customdatasrc, domain=domain, header=header, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, ids=ids, idssrc=idssrc, legend=legend, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, meta=meta, metasrc=metasrc, name=name, stream=stream, uid=uid, uirevision=uirevision, visible=visible, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_treemap( self, branchvalues=None, count=None, customdata=None, customdatasrc=None, domain=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=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, texttemplatefallback=None, texttemplatesrc=None, tiling=None, uid=None, uirevision=None, values=None, valuessrc=None, visible=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Treemap trace 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 ---------- 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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 appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All 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`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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). 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). Returns ------- Figure """ from plotly.graph_objs import Treemap new_trace = Treemap( branchvalues=branchvalues, count=count, customdata=customdata, customdatasrc=customdatasrc, domain=domain, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, insidetextfont=insidetextfont, labels=labels, labelssrc=labelssrc, legend=legend, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, level=level, marker=marker, maxdepth=maxdepth, meta=meta, metasrc=metasrc, name=name, opacity=opacity, outsidetextfont=outsidetextfont, parents=parents, parentssrc=parentssrc, pathbar=pathbar, root=root, sort=sort, stream=stream, text=text, textfont=textfont, textinfo=textinfo, textposition=textposition, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, texttemplatesrc=texttemplatesrc, tiling=tiling, uid=uid, uirevision=uirevision, values=values, valuessrc=valuessrc, visible=visible, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_violin( self, alignmentgroup=None, bandwidth=None, box=None, customdata=None, customdatasrc=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hoveron=None, hovertemplate=None, hovertemplatefallback=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, row=None, col=None, secondary_y=None, **kwargs, ) -> "Figure": """ Add a new Violin trace 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 ---------- 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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`. 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. Returns ------- Figure """ from plotly.graph_objs import Violin new_trace = Violin( alignmentgroup=alignmentgroup, bandwidth=bandwidth, box=box, customdata=customdata, customdatasrc=customdatasrc, fillcolor=fillcolor, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hoveron=hoveron, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, jitter=jitter, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, line=line, marker=marker, meanline=meanline, meta=meta, metasrc=metasrc, name=name, offsetgroup=offsetgroup, opacity=opacity, orientation=orientation, pointpos=pointpos, points=points, quartilemethod=quartilemethod, scalegroup=scalegroup, scalemode=scalemode, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, side=side, span=span, spanmode=spanmode, stream=stream, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, width=width, x=x, x0=x0, xaxis=xaxis, xhoverformat=xhoverformat, xsrc=xsrc, y=y, y0=y0, yaxis=yaxis, yhoverformat=yhoverformat, ysrc=ysrc, zorder=zorder, **kwargs, ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_volume( self, autocolorscale=None, caps=None, cauto=None, cmax=None, cmid=None, cmin=None, coloraxis=None, colorbar=None, colorscale=None, contour=None, customdata=None, customdatasrc=None, flatshading=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, isomax=None, isomin=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, lighting=None, lightposition=None, meta=None, metasrc=None, name=None, opacity=None, opacityscale=None, reversescale=None, scene=None, showlegend=None, showscale=None, slices=None, spaceframe=None, stream=None, surface=None, text=None, textsrc=None, uid=None, uirevision=None, value=None, valuehoverformat=None, valuesrc=None, visible=None, x=None, xhoverformat=None, xsrc=None, y=None, yhoverformat=None, ysrc=None, z=None, zhoverformat=None, zsrc=None, row=None, col=None, **kwargs, ) -> "Figure": """ Add a new Volume trace Draws volume trace between iso-min and iso-max values with coordinates given by four 1-dimensional arrays containing the `value`, `x`, `y` and `z` of every vertex of a uniform or non- uniform 3-D grid. Horizontal or vertical slices, caps as well as spaceframe between iso-min and iso-max values could also be drawn using this trace. Parameters ---------- 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. caps :class:`plotly.graph_objects.volume.Caps` instance or dict with compatible properties cauto Determines whether or not the color domain is computed with respect to the input data (here `value`) 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 `value` 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 `value`. Has no effect when `cauto` is `false`. cmin Sets the lower bound of the color domain. Value should have the same units as `value` and if set, `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.volume.ColorBar` 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: Blackbody,Bluered,Blues,C ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd. contour :class:`plotly.graph_objects.volume.Contour` 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`. flatshading Determines whether or not normal smoothing is applied to the meshes, creating meshes with an angular, low- poly look via flat reflections. 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.volume.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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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`. isomax Sets the maximum boundary for iso-surface plot. isomin Sets the minimum boundary for iso-surface plot. 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.volume.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. lighting :class:`plotly.graph_objects.volume.Lighting` instance or dict with compatible properties lightposition :class:`plotly.graph_objects.volume.Lightposition` 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 surface. Please note that in the case of using high `opacity` values for example a value greater than or equal to 0.5 on two surfaces (and 0.25 with four surfaces), an overlay of multiple transparent surfaces may not perfectly be sorted in depth by the webgl API. This behavior may be improved in the near future and is subject to change. opacityscale Sets the opacityscale. The opacityscale must be an array containing arrays mapping a normalized value to an opacity value. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 1], [0.5, 0.2], [1, 1]]` means that higher/lower values would have higher opacity values and those in the middle would be more transparent Alternatively, `opacityscale` may be a palette name string of the following list: 'min', 'max', 'extremes' and 'uniform'. The default is 'uniform'. 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. scene Sets a reference between this trace's 3D coordinate system and a 3D scene. If "scene" (the default value), the (x,y,z) coordinates refer to `layout.scene`. If "scene2", the (x,y,z) coordinates refer to `layout.scene2`, and so on. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. slices :class:`plotly.graph_objects.volume.Slices` instance or dict with compatible properties spaceframe :class:`plotly.graph_objects.volume.Spaceframe` instance or dict with compatible properties stream :class:`plotly.graph_objects.volume.Stream` instance or dict with compatible properties surface :class:`plotly.graph_objects.volume.Surface` instance or dict with compatible properties text Sets the text elements associated with the vertices. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. 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. value Sets the 4th dimension (value) of the vertices. valuehoverformat Sets the hover text formatting rulefor `value` using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d 3/d3-format/tree/v1.4.5#d3-format.By default the values are formatted using generic number format. valuesrc Sets the source reference on Chart Studio Cloud for `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). x Sets the X coordinates of the vertices on X 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`. xsrc Sets the source reference on Chart Studio Cloud for `x`. y Sets the Y coordinates of the vertices on 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`. ysrc Sets the source reference on Chart Studio Cloud for `y`. z Sets the Z coordinates of the vertices on Z axis. zhoverformat Sets the hover text formatting rulefor `z` 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 `zaxis.hoverformat`. zsrc Sets the source reference on Chart Studio Cloud for `z`. 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). Returns ------- Figure """ from plotly.graph_objs import Volume new_trace = Volume( autocolorscale=autocolorscale, caps=caps, cauto=cauto, cmax=cmax, cmid=cmid, cmin=cmin, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, contour=contour, customdata=customdata, customdatasrc=customdatasrc, flatshading=flatshading, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, isomax=isomax, isomin=isomin, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, lighting=lighting, lightposition=lightposition, meta=meta, metasrc=metasrc, name=name, opacity=opacity, opacityscale=opacityscale, reversescale=reversescale, scene=scene, showlegend=showlegend, showscale=showscale, slices=slices, spaceframe=spaceframe, stream=stream, surface=surface, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, value=value, valuehoverformat=valuehoverformat, valuesrc=valuesrc, visible=visible, x=x, xhoverformat=xhoverformat, xsrc=xsrc, y=y, yhoverformat=yhoverformat, ysrc=ysrc, z=z, zhoverformat=zhoverformat, zsrc=zsrc, **kwargs, ) return self.add_trace(new_trace, row=row, col=col) def add_waterfall( self, 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, hovertemplatefallback=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, texttemplatefallback=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, row=None, col=None, secondary_y=None, **kwargs, ) -> "Figure": """ Add a new Waterfall trace 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 ---------- 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. 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, all 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>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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 appears 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. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All 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`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. 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`. 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. Returns ------- Figure """ from plotly.graph_objs import Waterfall new_trace = Waterfall( alignmentgroup=alignmentgroup, base=base, cliponaxis=cliponaxis, connector=connector, constraintext=constraintext, customdata=customdata, customdatasrc=customdatasrc, decreasing=decreasing, dx=dx, dy=dy, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatefallback=hovertemplatefallback, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, increasing=increasing, insidetextanchor=insidetextanchor, insidetextfont=insidetextfont, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, measure=measure, measuresrc=measuresrc, meta=meta, metasrc=metasrc, name=name, offset=offset, offsetgroup=offsetgroup, offsetsrc=offsetsrc, opacity=opacity, orientation=orientation, outsidetextfont=outsidetextfont, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, text=text, textangle=textangle, textfont=textfont, textinfo=textinfo, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatefallback=texttemplatefallback, texttemplatesrc=texttemplatesrc, totals=totals, uid=uid, uirevision=uirevision, visible=visible, width=width, widthsrc=widthsrc, x=x, x0=x0, xaxis=xaxis, xhoverformat=xhoverformat, xperiod=xperiod, xperiod0=xperiod0, xperiodalignment=xperiodalignment, xsrc=xsrc, y=y, y0=y0, yaxis=yaxis, yhoverformat=yhoverformat, yperiod=yperiod, yperiod0=yperiod0, yperiodalignment=yperiodalignment, ysrc=ysrc, zorder=zorder, **kwargs, ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def select_coloraxes(self, selector=None, row=None, col=None): """ Select coloraxis subplot objects from a particular subplot cell and/or coloraxis subplot objects that satisfy custom selection criteria. Parameters ---------- selector: dict, function, or None (default None) Dict to use as selection criteria. coloraxis objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all coloraxis objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each coloraxis and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of coloraxis objects to select. To select coloraxis objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all coloraxis objects are selected. Returns ------- generator Generator that iterates through all of the coloraxis objects that satisfy all of the specified selection criteria """ return self._select_layout_subplots_by_prefix("coloraxis", selector, row, col) def for_each_coloraxis(self, fn, selector=None, row=None, col=None) -> "Figure": """ Apply a function to all coloraxis objects that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single coloraxis object. selector: dict, function, or None (default None) Dict to use as selection criteria. coloraxis objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all coloraxis objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each coloraxis and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of coloraxis objects to select. To select coloraxis objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all coloraxis objects are selected. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_coloraxes(selector=selector, row=row, col=col): fn(obj) return self def update_coloraxes( self, patch=None, selector=None, overwrite=False, row=None, col=None, **kwargs ) -> "Figure": """ Perform a property update operation on all coloraxis objects that satisfy the specified selection criteria Parameters ---------- patch: dict Dictionary of property updates to be applied to all coloraxis objects that satisfy the selection criteria. selector: dict, function, or None (default None) Dict to use as selection criteria. coloraxis objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all coloraxis objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each coloraxis and those for which the function returned True will be in the selection. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. row, col: int or None (default None) Subplot row and column index of coloraxis objects to select. To select coloraxis objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all coloraxis objects are selected. **kwargs Additional property updates to apply to each selected coloraxis object. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_coloraxes(selector=selector, row=row, col=col): obj.update(patch, overwrite=overwrite, **kwargs) return self def select_geos(self, selector=None, row=None, col=None): """ Select geo subplot objects from a particular subplot cell and/or geo subplot objects that satisfy custom selection criteria. Parameters ---------- selector: dict, function, or None (default None) Dict to use as selection criteria. geo objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all geo objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each geo and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of geo objects to select. To select geo objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all geo objects are selected. Returns ------- generator Generator that iterates through all of the geo objects that satisfy all of the specified selection criteria """ return self._select_layout_subplots_by_prefix("geo", selector, row, col) def for_each_geo(self, fn, selector=None, row=None, col=None) -> "Figure": """ Apply a function to all geo objects that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single geo object. selector: dict, function, or None (default None) Dict to use as selection criteria. geo objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all geo objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each geo and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of geo objects to select. To select geo objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all geo objects are selected. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_geos(selector=selector, row=row, col=col): fn(obj) return self def update_geos( self, patch=None, selector=None, overwrite=False, row=None, col=None, **kwargs ) -> "Figure": """ Perform a property update operation on all geo objects that satisfy the specified selection criteria Parameters ---------- patch: dict Dictionary of property updates to be applied to all geo objects that satisfy the selection criteria. selector: dict, function, or None (default None) Dict to use as selection criteria. geo objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all geo objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each geo and those for which the function returned True will be in the selection. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. row, col: int or None (default None) Subplot row and column index of geo objects to select. To select geo objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all geo objects are selected. **kwargs Additional property updates to apply to each selected geo object. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_geos(selector=selector, row=row, col=col): obj.update(patch, overwrite=overwrite, **kwargs) return self def select_legends(self, selector=None, row=None, col=None): """ Select legend subplot objects from a particular subplot cell and/or legend subplot objects that satisfy custom selection criteria. Parameters ---------- selector: dict, function, or None (default None) Dict to use as selection criteria. legend objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all legend objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each legend and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of legend objects to select. To select legend objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all legend objects are selected. Returns ------- generator Generator that iterates through all of the legend objects that satisfy all of the specified selection criteria """ return self._select_layout_subplots_by_prefix("legend", selector, row, col) def for_each_legend(self, fn, selector=None, row=None, col=None) -> "Figure": """ Apply a function to all legend objects that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single legend object. selector: dict, function, or None (default None) Dict to use as selection criteria. legend objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all legend objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each legend and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of legend objects to select. To select legend objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all legend objects are selected. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_legends(selector=selector, row=row, col=col): fn(obj) return self def update_legends( self, patch=None, selector=None, overwrite=False, row=None, col=None, **kwargs ) -> "Figure": """ Perform a property update operation on all legend objects that satisfy the specified selection criteria Parameters ---------- patch: dict Dictionary of property updates to be applied to all legend objects that satisfy the selection criteria. selector: dict, function, or None (default None) Dict to use as selection criteria. legend objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all legend objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each legend and those for which the function returned True will be in the selection. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. row, col: int or None (default None) Subplot row and column index of legend objects to select. To select legend objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all legend objects are selected. **kwargs Additional property updates to apply to each selected legend object. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_legends(selector=selector, row=row, col=col): obj.update(patch, overwrite=overwrite, **kwargs) return self def select_maps(self, selector=None, row=None, col=None): """ Select map subplot objects from a particular subplot cell and/or map subplot objects that satisfy custom selection criteria. Parameters ---------- selector: dict, function, or None (default None) Dict to use as selection criteria. map objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all map objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each map and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of map objects to select. To select map objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all map objects are selected. Returns ------- generator Generator that iterates through all of the map objects that satisfy all of the specified selection criteria """ return self._select_layout_subplots_by_prefix("map", selector, row, col) def for_each_map(self, fn, selector=None, row=None, col=None) -> "Figure": """ Apply a function to all map objects that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single map object. selector: dict, function, or None (default None) Dict to use as selection criteria. map objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all map objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each map and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of map objects to select. To select map objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all map objects are selected. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_maps(selector=selector, row=row, col=col): fn(obj) return self def update_maps( self, patch=None, selector=None, overwrite=False, row=None, col=None, **kwargs ) -> "Figure": """ Perform a property update operation on all map objects that satisfy the specified selection criteria Parameters ---------- patch: dict Dictionary of property updates to be applied to all map objects that satisfy the selection criteria. selector: dict, function, or None (default None) Dict to use as selection criteria. map objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all map objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each map and those for which the function returned True will be in the selection. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. row, col: int or None (default None) Subplot row and column index of map objects to select. To select map objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all map objects are selected. **kwargs Additional property updates to apply to each selected map object. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_maps(selector=selector, row=row, col=col): obj.update(patch, overwrite=overwrite, **kwargs) return self def select_mapboxes(self, selector=None, row=None, col=None): """ Select mapbox subplot objects from a particular subplot cell and/or mapbox subplot objects that satisfy custom selection criteria. Parameters ---------- selector: dict, function, or None (default None) Dict to use as selection criteria. mapbox objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all mapbox objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each mapbox and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of mapbox objects to select. To select mapbox objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all mapbox objects are selected. Returns ------- generator Generator that iterates through all of the mapbox objects that satisfy all of the specified selection criteria """ return self._select_layout_subplots_by_prefix("mapbox", selector, row, col) def for_each_mapbox(self, fn, selector=None, row=None, col=None) -> "Figure": """ Apply a function to all mapbox objects that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single mapbox object. selector: dict, function, or None (default None) Dict to use as selection criteria. mapbox objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all mapbox objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each mapbox and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of mapbox objects to select. To select mapbox objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all mapbox objects are selected. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_mapboxes(selector=selector, row=row, col=col): fn(obj) return self def update_mapboxes( self, patch=None, selector=None, overwrite=False, row=None, col=None, **kwargs ) -> "Figure": """ Perform a property update operation on all mapbox objects that satisfy the specified selection criteria Parameters ---------- patch: dict Dictionary of property updates to be applied to all mapbox objects that satisfy the selection criteria. selector: dict, function, or None (default None) Dict to use as selection criteria. mapbox objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all mapbox objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each mapbox and those for which the function returned True will be in the selection. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. row, col: int or None (default None) Subplot row and column index of mapbox objects to select. To select mapbox objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all mapbox objects are selected. **kwargs Additional property updates to apply to each selected mapbox object. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_mapboxes(selector=selector, row=row, col=col): obj.update(patch, overwrite=overwrite, **kwargs) return self def select_polars(self, selector=None, row=None, col=None): """ Select polar subplot objects from a particular subplot cell and/or polar subplot objects that satisfy custom selection criteria. Parameters ---------- selector: dict, function, or None (default None) Dict to use as selection criteria. polar objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all polar objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each polar and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of polar objects to select. To select polar objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all polar objects are selected. Returns ------- generator Generator that iterates through all of the polar objects that satisfy all of the specified selection criteria """ return self._select_layout_subplots_by_prefix("polar", selector, row, col) def for_each_polar(self, fn, selector=None, row=None, col=None) -> "Figure": """ Apply a function to all polar objects that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single polar object. selector: dict, function, or None (default None) Dict to use as selection criteria. polar objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all polar objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each polar and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of polar objects to select. To select polar objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all polar objects are selected. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_polars(selector=selector, row=row, col=col): fn(obj) return self def update_polars( self, patch=None, selector=None, overwrite=False, row=None, col=None, **kwargs ) -> "Figure": """ Perform a property update operation on all polar objects that satisfy the specified selection criteria Parameters ---------- patch: dict Dictionary of property updates to be applied to all polar objects that satisfy the selection criteria. selector: dict, function, or None (default None) Dict to use as selection criteria. polar objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all polar objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each polar and those for which the function returned True will be in the selection. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. row, col: int or None (default None) Subplot row and column index of polar objects to select. To select polar objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all polar objects are selected. **kwargs Additional property updates to apply to each selected polar object. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_polars(selector=selector, row=row, col=col): obj.update(patch, overwrite=overwrite, **kwargs) return self def select_scenes(self, selector=None, row=None, col=None): """ Select scene subplot objects from a particular subplot cell and/or scene subplot objects that satisfy custom selection criteria. Parameters ---------- selector: dict, function, or None (default None) Dict to use as selection criteria. scene objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all scene objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each scene and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of scene objects to select. To select scene objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all scene objects are selected. Returns ------- generator Generator that iterates through all of the scene objects that satisfy all of the specified selection criteria """ return self._select_layout_subplots_by_prefix("scene", selector, row, col) def for_each_scene(self, fn, selector=None, row=None, col=None) -> "Figure": """ Apply a function to all scene objects that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single scene object. selector: dict, function, or None (default None) Dict to use as selection criteria. scene objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all scene objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each scene and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of scene objects to select. To select scene objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all scene objects are selected. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_scenes(selector=selector, row=row, col=col): fn(obj) return self def update_scenes( self, patch=None, selector=None, overwrite=False, row=None, col=None, **kwargs ) -> "Figure": """ Perform a property update operation on all scene objects that satisfy the specified selection criteria Parameters ---------- patch: dict Dictionary of property updates to be applied to all scene objects that satisfy the selection criteria. selector: dict, function, or None (default None) Dict to use as selection criteria. scene objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all scene objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each scene and those for which the function returned True will be in the selection. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. row, col: int or None (default None) Subplot row and column index of scene objects to select. To select scene objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all scene objects are selected. **kwargs Additional property updates to apply to each selected scene object. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_scenes(selector=selector, row=row, col=col): obj.update(patch, overwrite=overwrite, **kwargs) return self def select_smiths(self, selector=None, row=None, col=None): """ Select smith subplot objects from a particular subplot cell and/or smith subplot objects that satisfy custom selection criteria. Parameters ---------- selector: dict, function, or None (default None) Dict to use as selection criteria. smith objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all smith objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each smith and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of smith objects to select. To select smith objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all smith objects are selected. Returns ------- generator Generator that iterates through all of the smith objects that satisfy all of the specified selection criteria """ return self._select_layout_subplots_by_prefix("smith", selector, row, col) def for_each_smith(self, fn, selector=None, row=None, col=None) -> "Figure": """ Apply a function to all smith objects that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single smith object. selector: dict, function, or None (default None) Dict to use as selection criteria. smith objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all smith objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each smith and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of smith objects to select. To select smith objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all smith objects are selected. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_smiths(selector=selector, row=row, col=col): fn(obj) return self def update_smiths( self, patch=None, selector=None, overwrite=False, row=None, col=None, **kwargs ) -> "Figure": """ Perform a property update operation on all smith objects that satisfy the specified selection criteria Parameters ---------- patch: dict Dictionary of property updates to be applied to all smith objects that satisfy the selection criteria. selector: dict, function, or None (default None) Dict to use as selection criteria. smith objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all smith objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each smith and those for which the function returned True will be in the selection. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. row, col: int or None (default None) Subplot row and column index of smith objects to select. To select smith objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all smith objects are selected. **kwargs Additional property updates to apply to each selected smith object. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_smiths(selector=selector, row=row, col=col): obj.update(patch, overwrite=overwrite, **kwargs) return self def select_ternaries(self, selector=None, row=None, col=None): """ Select ternary subplot objects from a particular subplot cell and/or ternary subplot objects that satisfy custom selection criteria. Parameters ---------- selector: dict, function, or None (default None) Dict to use as selection criteria. ternary objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all ternary objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each ternary and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of ternary objects to select. To select ternary objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all ternary objects are selected. Returns ------- generator Generator that iterates through all of the ternary objects that satisfy all of the specified selection criteria """ return self._select_layout_subplots_by_prefix("ternary", selector, row, col) def for_each_ternary(self, fn, selector=None, row=None, col=None) -> "Figure": """ Apply a function to all ternary objects that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single ternary object. selector: dict, function, or None (default None) Dict to use as selection criteria. ternary objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all ternary objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each ternary and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of ternary objects to select. To select ternary objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all ternary objects are selected. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_ternaries(selector=selector, row=row, col=col): fn(obj) return self def update_ternaries( self, patch=None, selector=None, overwrite=False, row=None, col=None, **kwargs ) -> "Figure": """ Perform a property update operation on all ternary objects that satisfy the specified selection criteria Parameters ---------- patch: dict Dictionary of property updates to be applied to all ternary objects that satisfy the selection criteria. selector: dict, function, or None (default None) Dict to use as selection criteria. ternary objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all ternary objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each ternary and those for which the function returned True will be in the selection. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. row, col: int or None (default None) Subplot row and column index of ternary objects to select. To select ternary objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all ternary objects are selected. **kwargs Additional property updates to apply to each selected ternary object. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_ternaries(selector=selector, row=row, col=col): obj.update(patch, overwrite=overwrite, **kwargs) return self def select_xaxes(self, selector=None, row=None, col=None): """ Select xaxis subplot objects from a particular subplot cell and/or xaxis subplot objects that satisfy custom selection criteria. Parameters ---------- selector: dict, function, or None (default None) Dict to use as selection criteria. xaxis objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all xaxis objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each xaxis and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of xaxis objects to select. To select xaxis objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all xaxis objects are selected. Returns ------- generator Generator that iterates through all of the xaxis objects that satisfy all of the specified selection criteria """ return self._select_layout_subplots_by_prefix("xaxis", selector, row, col) def for_each_xaxis(self, fn, selector=None, row=None, col=None) -> "Figure": """ Apply a function to all xaxis objects that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single xaxis object. selector: dict, function, or None (default None) Dict to use as selection criteria. xaxis objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all xaxis objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each xaxis and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of xaxis objects to select. To select xaxis objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all xaxis objects are selected. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_xaxes(selector=selector, row=row, col=col): fn(obj) return self def update_xaxes( self, patch=None, selector=None, overwrite=False, row=None, col=None, **kwargs ) -> "Figure": """ Perform a property update operation on all xaxis objects that satisfy the specified selection criteria Parameters ---------- patch: dict Dictionary of property updates to be applied to all xaxis objects that satisfy the selection criteria. selector: dict, function, or None (default None) Dict to use as selection criteria. xaxis objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all xaxis objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each xaxis and those for which the function returned True will be in the selection. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. row, col: int or None (default None) Subplot row and column index of xaxis objects to select. To select xaxis objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all xaxis objects are selected. **kwargs Additional property updates to apply to each selected xaxis object. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_xaxes(selector=selector, row=row, col=col): obj.update(patch, overwrite=overwrite, **kwargs) return self def select_yaxes(self, selector=None, row=None, col=None, secondary_y=None): """ Select yaxis subplot objects from a particular subplot cell and/or yaxis subplot objects that satisfy custom selection criteria. Parameters ---------- selector: dict, function, or None (default None) Dict to use as selection criteria. yaxis objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all yaxis objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each yaxis and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of yaxis objects to select. To select yaxis objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all yaxis objects are selected. secondary_y: boolean or None (default None) * If True, only select yaxis objects associated with the secondary y-axis of the subplot. * If False, only select yaxis objects associated with the primary y-axis of the subplot. * If None (the default), do not filter yaxis objects based on a secondary y-axis condition. To select yaxis objects by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- generator Generator that iterates through all of the yaxis objects that satisfy all of the specified selection criteria """ return self._select_layout_subplots_by_prefix( "yaxis", selector, row, col, secondary_y=secondary_y ) def for_each_yaxis( self, fn, selector=None, row=None, col=None, secondary_y=None ) -> "Figure": """ Apply a function to all yaxis objects that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single yaxis object. selector: dict, function, or None (default None) Dict to use as selection criteria. yaxis objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all yaxis objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each yaxis and those for which the function returned True will be in the selection. row, col: int or None (default None) Subplot row and column index of yaxis objects to select. To select yaxis objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all yaxis objects are selected. secondary_y: boolean or None (default None) * If True, only select yaxis objects associated with the secondary y-axis of the subplot. * If False, only select yaxis objects associated with the primary y-axis of the subplot. * If None (the default), do not filter yaxis objects based on a secondary y-axis condition. To select yaxis objects by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_yaxes( selector=selector, row=row, col=col, secondary_y=secondary_y ): fn(obj) return self def update_yaxes( self, patch=None, selector=None, overwrite=False, row=None, col=None, secondary_y=None, **kwargs, ) -> "Figure": """ Perform a property update operation on all yaxis objects that satisfy the specified selection criteria Parameters ---------- patch: dict Dictionary of property updates to be applied to all yaxis objects that satisfy the selection criteria. selector: dict, function, or None (default None) Dict to use as selection criteria. yaxis objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all yaxis objects are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each yaxis and those for which the function returned True will be in the selection. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. row, col: int or None (default None) Subplot row and column index of yaxis objects to select. To select yaxis objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all yaxis objects are selected. secondary_y: boolean or None (default None) * If True, only select yaxis objects associated with the secondary y-axis of the subplot. * If False, only select yaxis objects associated with the primary y-axis of the subplot. * If None (the default), do not filter yaxis objects based on a secondary y-axis condition. To select yaxis objects by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. **kwargs Additional property updates to apply to each selected yaxis object. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_yaxes( selector=selector, row=row, col=col, secondary_y=secondary_y ): obj.update(patch, overwrite=overwrite, **kwargs) return self def select_annotations(self, selector=None, row=None, col=None, secondary_y=None): """ Select annotations from a particular subplot cell and/or annotations that satisfy custom selection criteria. Parameters ---------- selector: dict, function, int, str, or None (default None) Dict to use as selection criteria. Annotations will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all annotations are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each annotation and those for which the function returned True will be in the selection. If an int N, the Nth annotation matching row and col will be selected (N can be negative). If a string S, the selector is equivalent to dict(type=S). row, col: int or None (default None) Subplot row and column index of annotations to select. To select annotations by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those annotation that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all annotations are selected. secondary_y: boolean or None (default None) * If True, only select annotations associated with the secondary y-axis of the subplot. * If False, only select annotations associated with the primary y-axis of the subplot. * If None (the default), do not filter annotations based on secondary y-axis. To select annotations by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- generator Generator that iterates through all of the annotations that satisfy all of the specified selection criteria """ return self._select_annotations_like( "annotations", selector=selector, row=row, col=col, secondary_y=secondary_y ) def for_each_annotation( self, fn, selector=None, row=None, col=None, secondary_y=None ): """ Apply a function to all annotations that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single annotation object. selector: dict, function, int, str or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all annotations are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each annotation and those for which the function returned True will be in the selection. If an int N, the Nth annotation matching row and col will be selected (N can be negative). If a string S, the selector is equivalent to dict(type=S). row, col: int or None (default None) Subplot row and column index of annotations to select. To select annotations by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those annotations that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all annotations are selected. secondary_y: boolean or None (default None) * If True, only select annotations associated with the secondary y-axis of the subplot. * If False, only select annotations associated with the primary y-axis of the subplot. * If None (the default), do not filter annotations based on secondary y-axis. To select annotations by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- self Returns the Figure object that the method was called on """ for obj in self._select_annotations_like( prop="annotations", selector=selector, row=row, col=col, secondary_y=secondary_y, ): fn(obj) return self def update_annotations( self, patch=None, selector=None, row=None, col=None, secondary_y=None, **kwargs ) -> "Figure": """ Perform a property update operation on all annotations that satisfy the specified selection criteria Parameters ---------- patch: dict or None (default None) Dictionary of property updates to be applied to all annotations that satisfy the selection criteria. selector: dict, function, int, str or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all annotations are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each annotation and those for which the function returned True will be in the selection. If an int N, the Nth annotation matching row and col will be selected (N can be negative). If a string S, the selector is equivalent to dict(type=S). row, col: int or None (default None) Subplot row and column index of annotations to select. To select annotations by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those annotation that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all annotations are selected. secondary_y: boolean or None (default None) * If True, only select annotations associated with the secondary y-axis of the subplot. * If False, only select annotations associated with the primary y-axis of the subplot. * If None (the default), do not filter annotations based on secondary y-axis. To select annotations by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. **kwargs Additional property updates to apply to each selected annotation. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self._select_annotations_like( prop="annotations", selector=selector, row=row, col=col, secondary_y=secondary_y, ): obj.update(patch, **kwargs) return self def add_annotation( self, arg=None, align=None, arrowcolor=None, arrowhead=None, arrowside=None, arrowsize=None, arrowwidth=None, ax=None, axref=None, ay=None, ayref=None, bgcolor=None, bordercolor=None, borderpad=None, borderwidth=None, captureevents=None, clicktoshow=None, font=None, height=None, hoverlabel=None, hovertext=None, name=None, opacity=None, showarrow=None, standoff=None, startarrowhead=None, startarrowsize=None, startstandoff=None, templateitemname=None, text=None, textangle=None, valign=None, visible=None, width=None, x=None, xanchor=None, xclick=None, xref=None, xshift=None, y=None, yanchor=None, yclick=None, yref=None, yshift=None, row=None, col=None, secondary_y=None, exclude_empty_subplots=None, **kwargs, ) -> "Figure": """ Create and add a new annotation to the figure's layout Parameters ---------- arg instance of Annotation or dict with compatible 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.Hoverlab el` 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>`, and `<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. row Subplot row for annotation. If 'all', addresses all rows in the specified column(s). col Subplot column for annotation. If 'all', addresses all columns in the specified row(s). secondary_y Whether to add annotation to secondary y-axis exclude_empty_subplots If True, annotation will not be added to subplots without traces. Returns ------- Figure """ from plotly.graph_objs import layout as _layout new_obj = _layout.Annotation( arg, align=align, arrowcolor=arrowcolor, arrowhead=arrowhead, arrowside=arrowside, arrowsize=arrowsize, arrowwidth=arrowwidth, ax=ax, axref=axref, ay=ay, ayref=ayref, bgcolor=bgcolor, bordercolor=bordercolor, borderpad=borderpad, borderwidth=borderwidth, captureevents=captureevents, clicktoshow=clicktoshow, font=font, height=height, hoverlabel=hoverlabel, hovertext=hovertext, name=name, opacity=opacity, showarrow=showarrow, standoff=standoff, startarrowhead=startarrowhead, startarrowsize=startarrowsize, startstandoff=startstandoff, templateitemname=templateitemname, text=text, textangle=textangle, valign=valign, visible=visible, width=width, x=x, xanchor=xanchor, xclick=xclick, xref=xref, xshift=xshift, y=y, yanchor=yanchor, yclick=yclick, yref=yref, yshift=yshift, **kwargs, ) return self._add_annotation_like( "annotation", "annotations", new_obj, row=row, col=col, secondary_y=secondary_y, exclude_empty_subplots=exclude_empty_subplots, ) def select_layout_images(self, selector=None, row=None, col=None, secondary_y=None): """ Select images from a particular subplot cell and/or images that satisfy custom selection criteria. Parameters ---------- selector: dict, function, int, str, or None (default None) Dict to use as selection criteria. Annotations will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all images are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each image and those for which the function returned True will be in the selection. If an int N, the Nth image matching row and col will be selected (N can be negative). If a string S, the selector is equivalent to dict(type=S). row, col: int or None (default None) Subplot row and column index of images to select. To select images by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those image that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all images are selected. secondary_y: boolean or None (default None) * If True, only select images associated with the secondary y-axis of the subplot. * If False, only select images associated with the primary y-axis of the subplot. * If None (the default), do not filter images based on secondary y-axis. To select images by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- generator Generator that iterates through all of the images that satisfy all of the specified selection criteria """ return self._select_annotations_like( "images", selector=selector, row=row, col=col, secondary_y=secondary_y ) def for_each_layout_image( self, fn, selector=None, row=None, col=None, secondary_y=None ): """ Apply a function to all images that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single image object. selector: dict, function, int, str or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all images are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each image and those for which the function returned True will be in the selection. If an int N, the Nth image matching row and col will be selected (N can be negative). If a string S, the selector is equivalent to dict(type=S). row, col: int or None (default None) Subplot row and column index of images to select. To select images by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those images that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all images are selected. secondary_y: boolean or None (default None) * If True, only select images associated with the secondary y-axis of the subplot. * If False, only select images associated with the primary y-axis of the subplot. * If None (the default), do not filter images based on secondary y-axis. To select images by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- self Returns the Figure object that the method was called on """ for obj in self._select_annotations_like( prop="images", selector=selector, row=row, col=col, secondary_y=secondary_y, ): fn(obj) return self def update_layout_images( self, patch=None, selector=None, row=None, col=None, secondary_y=None, **kwargs ) -> "Figure": """ Perform a property update operation on all images that satisfy the specified selection criteria Parameters ---------- patch: dict or None (default None) Dictionary of property updates to be applied to all images that satisfy the selection criteria. selector: dict, function, int, str or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all images are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each image and those for which the function returned True will be in the selection. If an int N, the Nth image matching row and col will be selected (N can be negative). If a string S, the selector is equivalent to dict(type=S). row, col: int or None (default None) Subplot row and column index of images to select. To select images by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those image that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all images are selected. secondary_y: boolean or None (default None) * If True, only select images associated with the secondary y-axis of the subplot. * If False, only select images associated with the primary y-axis of the subplot. * If None (the default), do not filter images based on secondary y-axis. To select images by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. **kwargs Additional property updates to apply to each selected image. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self._select_annotations_like( prop="images", selector=selector, row=row, col=col, secondary_y=secondary_y, ): obj.update(patch, **kwargs) return self def add_layout_image( self, arg=None, layer=None, name=None, opacity=None, sizex=None, sizey=None, sizing=None, source=None, templateitemname=None, visible=None, x=None, xanchor=None, xref=None, y=None, yanchor=None, yref=None, row=None, col=None, secondary_y=None, exclude_empty_subplots=None, **kwargs, ) -> "Figure": """ Create and add a new image to the figure's layout Parameters ---------- arg instance of Image or dict with compatible 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. row Subplot row for image. If 'all', addresses all rows in the specified column(s). col Subplot column for image. If 'all', addresses all columns in the specified row(s). secondary_y Whether to add image to secondary y-axis exclude_empty_subplots If True, image will not be added to subplots without traces. Returns ------- Figure """ from plotly.graph_objs import layout as _layout new_obj = _layout.Image( arg, layer=layer, name=name, opacity=opacity, sizex=sizex, sizey=sizey, sizing=sizing, source=source, templateitemname=templateitemname, visible=visible, x=x, xanchor=xanchor, xref=xref, y=y, yanchor=yanchor, yref=yref, **kwargs, ) return self._add_annotation_like( "image", "images", new_obj, row=row, col=col, secondary_y=secondary_y, exclude_empty_subplots=exclude_empty_subplots, ) def select_selections(self, selector=None, row=None, col=None, secondary_y=None): """ Select selections from a particular subplot cell and/or selections that satisfy custom selection criteria. Parameters ---------- selector: dict, function, int, str, or None (default None) Dict to use as selection criteria. Annotations will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all selections are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each selection and those for which the function returned True will be in the selection. If an int N, the Nth selection matching row and col will be selected (N can be negative). If a string S, the selector is equivalent to dict(type=S). row, col: int or None (default None) Subplot row and column index of selections to select. To select selections by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those selection that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all selections are selected. secondary_y: boolean or None (default None) * If True, only select selections associated with the secondary y-axis of the subplot. * If False, only select selections associated with the primary y-axis of the subplot. * If None (the default), do not filter selections based on secondary y-axis. To select selections by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- generator Generator that iterates through all of the selections that satisfy all of the specified selection criteria """ return self._select_annotations_like( "selections", selector=selector, row=row, col=col, secondary_y=secondary_y ) def for_each_selection( self, fn, selector=None, row=None, col=None, secondary_y=None ): """ Apply a function to all selections that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single selection object. selector: dict, function, int, str or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all selections are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each selection and those for which the function returned True will be in the selection. If an int N, the Nth selection matching row and col will be selected (N can be negative). If a string S, the selector is equivalent to dict(type=S). row, col: int or None (default None) Subplot row and column index of selections to select. To select selections by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those selections that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all selections are selected. secondary_y: boolean or None (default None) * If True, only select selections associated with the secondary y-axis of the subplot. * If False, only select selections associated with the primary y-axis of the subplot. * If None (the default), do not filter selections based on secondary y-axis. To select selections by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- self Returns the Figure object that the method was called on """ for obj in self._select_annotations_like( prop="selections", selector=selector, row=row, col=col, secondary_y=secondary_y, ): fn(obj) return self def update_selections( self, patch=None, selector=None, row=None, col=None, secondary_y=None, **kwargs ) -> "Figure": """ Perform a property update operation on all selections that satisfy the specified selection criteria Parameters ---------- patch: dict or None (default None) Dictionary of property updates to be applied to all selections that satisfy the selection criteria. selector: dict, function, int, str or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all selections are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each selection and those for which the function returned True will be in the selection. If an int N, the Nth selection matching row and col will be selected (N can be negative). If a string S, the selector is equivalent to dict(type=S). row, col: int or None (default None) Subplot row and column index of selections to select. To select selections by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those selection that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all selections are selected. secondary_y: boolean or None (default None) * If True, only select selections associated with the secondary y-axis of the subplot. * If False, only select selections associated with the primary y-axis of the subplot. * If None (the default), do not filter selections based on secondary y-axis. To select selections by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. **kwargs Additional property updates to apply to each selected selection. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self._select_annotations_like( prop="selections", selector=selector, row=row, col=col, secondary_y=secondary_y, ): obj.update(patch, **kwargs) return self def add_selection( 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, row=None, col=None, secondary_y=None, exclude_empty_subplots=None, **kwargs, ) -> "Figure": """ Create and add a new selection to the figure's layout Parameters ---------- arg instance of Selection or dict with compatible properties 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. row Subplot row for selection. If 'all', addresses all rows in the specified column(s). col Subplot column for selection. If 'all', addresses all columns in the specified row(s). secondary_y Whether to add selection to secondary y-axis exclude_empty_subplots If True, selection will not be added to subplots without traces. Returns ------- Figure """ from plotly.graph_objs import layout as _layout new_obj = _layout.Selection( arg, line=line, name=name, opacity=opacity, path=path, templateitemname=templateitemname, type=type, x0=x0, x1=x1, xref=xref, y0=y0, y1=y1, yref=yref, **kwargs, ) return self._add_annotation_like( "selection", "selections", new_obj, row=row, col=col, secondary_y=secondary_y, exclude_empty_subplots=exclude_empty_subplots, ) def select_shapes(self, selector=None, row=None, col=None, secondary_y=None): """ Select shapes from a particular subplot cell and/or shapes that satisfy custom selection criteria. Parameters ---------- selector: dict, function, int, str, or None (default None) Dict to use as selection criteria. Annotations will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all shapes are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each shape and those for which the function returned True will be in the selection. If an int N, the Nth shape matching row and col will be selected (N can be negative). If a string S, the selector is equivalent to dict(type=S). row, col: int or None (default None) Subplot row and column index of shapes to select. To select shapes by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those shape that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all shapes are selected. secondary_y: boolean or None (default None) * If True, only select shapes associated with the secondary y-axis of the subplot. * If False, only select shapes associated with the primary y-axis of the subplot. * If None (the default), do not filter shapes based on secondary y-axis. To select shapes by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- generator Generator that iterates through all of the shapes that satisfy all of the specified selection criteria """ return self._select_annotations_like( "shapes", selector=selector, row=row, col=col, secondary_y=secondary_y ) def for_each_shape(self, fn, selector=None, row=None, col=None, secondary_y=None): """ Apply a function to all shapes that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single shape object. selector: dict, function, int, str or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all shapes are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each shape and those for which the function returned True will be in the selection. If an int N, the Nth shape matching row and col will be selected (N can be negative). If a string S, the selector is equivalent to dict(type=S). row, col: int or None (default None) Subplot row and column index of shapes to select. To select shapes by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those shapes that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all shapes are selected. secondary_y: boolean or None (default None) * If True, only select shapes associated with the secondary y-axis of the subplot. * If False, only select shapes associated with the primary y-axis of the subplot. * If None (the default), do not filter shapes based on secondary y-axis. To select shapes by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- self Returns the Figure object that the method was called on """ for obj in self._select_annotations_like( prop="shapes", selector=selector, row=row, col=col, secondary_y=secondary_y, ): fn(obj) return self def update_shapes( self, patch=None, selector=None, row=None, col=None, secondary_y=None, **kwargs ) -> "Figure": """ Perform a property update operation on all shapes that satisfy the specified selection criteria Parameters ---------- patch: dict or None (default None) Dictionary of property updates to be applied to all shapes that satisfy the selection criteria. selector: dict, function, int, str or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all shapes are selected. If a function, it must be a function accepting a single argument and returning a boolean. The function will be called on each shape and those for which the function returned True will be in the selection. If an int N, the Nth shape matching row and col will be selected (N can be negative). If a string S, the selector is equivalent to dict(type=S). row, col: int or None (default None) Subplot row and column index of shapes to select. To select shapes by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those shape that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all shapes are selected. secondary_y: boolean or None (default None) * If True, only select shapes associated with the secondary y-axis of the subplot. * If False, only select shapes associated with the primary y-axis of the subplot. * If None (the default), do not filter shapes based on secondary y-axis. To select shapes by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. **kwargs Additional property updates to apply to each selected shape. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self._select_annotations_like( prop="shapes", selector=selector, row=row, col=col, secondary_y=secondary_y, ): obj.update(patch, **kwargs) return self def add_shape( self, arg=None, editable=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, path=None, showlegend=None, templateitemname=None, type=None, visible=None, x0=None, x0shift=None, x1=None, x1shift=None, xanchor=None, xref=None, xsizemode=None, y0=None, y0shift=None, y1=None, y1shift=None, yanchor=None, yref=None, ysizemode=None, row=None, col=None, secondary_y=None, exclude_empty_subplots=None, **kwargs, ) -> "Figure": """ Create and add a new shape to the figure's layout Parameters ---------- arg instance of Shape or dict with compatible 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.Legendgroupti tle` 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. row Subplot row for shape. If 'all', addresses all rows in the specified column(s). col Subplot column for shape. If 'all', addresses all columns in the specified row(s). secondary_y Whether to add shape to secondary y-axis exclude_empty_subplots If True, shape will not be added to subplots without traces. Returns ------- Figure """ from plotly.graph_objs import layout as _layout new_obj = _layout.Shape( arg, editable=editable, fillcolor=fillcolor, fillrule=fillrule, label=label, layer=layer, legend=legend, legendgroup=legendgroup, legendgrouptitle=legendgrouptitle, legendrank=legendrank, legendwidth=legendwidth, line=line, name=name, opacity=opacity, path=path, showlegend=showlegend, templateitemname=templateitemname, type=type, visible=visible, x0=x0, x0shift=x0shift, x1=x1, x1shift=x1shift, xanchor=xanchor, xref=xref, xsizemode=xsizemode, y0=y0, y0shift=y0shift, y1=y1, y1shift=y1shift, yanchor=yanchor, yref=yref, ysizemode=ysizemode, **kwargs, ) return self._add_annotation_like( "shape", "shapes", new_obj, row=row, col=col, secondary_y=secondary_y, exclude_empty_subplots=exclude_empty_subplots, )
Figure
python
jamielennox__requests-mock
tests/test_mocker.py
{ "start": 11904, "end": 22269 }
class ____(base.TestCase): URL = 'http://test.com/path' TEXT = 'resp' def assertResponse(self, resp): self.assertEqual(self.TEXT, resp.text) @requests_mock.Mocker() def test_mocker_request(self, m): method = 'XXX' mock_obj = m.request(method, self.URL, text=self.TEXT) resp = requests.request(method, self.URL) self.assertResponse(resp) self.assertTrue(mock_obj.called) self.assertTrue(mock_obj.called_once) self.assertTrue(m.called) self.assertTrue(m.called_once) @requests_mock.Mocker() def test_mocker_get(self, m): mock_obj = m.get(self.URL, text=self.TEXT) self.assertResponse(requests.get(self.URL)) self.assertTrue(mock_obj.called) self.assertTrue(mock_obj.called_once) self.assertTrue(m.called) self.assertTrue(m.called_once) @requests_mock.Mocker() def test_mocker_options(self, m): mock_obj = m.options(self.URL, text=self.TEXT) self.assertResponse(requests.options(self.URL)) self.assertTrue(mock_obj.called) self.assertTrue(mock_obj.called_once) self.assertTrue(m.called) self.assertTrue(m.called_once) @requests_mock.Mocker() def test_mocker_head(self, m): mock_obj = m.head(self.URL, text=self.TEXT) self.assertResponse(requests.head(self.URL)) self.assertTrue(mock_obj.called) self.assertTrue(mock_obj.called_once) self.assertTrue(m.called) self.assertTrue(m.called_once) @requests_mock.Mocker() def test_mocker_post(self, m): mock_obj = m.post(self.URL, text=self.TEXT) self.assertResponse(requests.post(self.URL)) self.assertTrue(mock_obj.called) self.assertTrue(mock_obj.called_once) self.assertTrue(m.called) self.assertTrue(m.called_once) @requests_mock.Mocker() def test_mocker_put(self, m): mock_obj = m.put(self.URL, text=self.TEXT) self.assertResponse(requests.put(self.URL)) self.assertTrue(mock_obj.called) self.assertTrue(mock_obj.called_once) self.assertTrue(m.called) self.assertTrue(m.called_once) @requests_mock.Mocker() def test_mocker_patch(self, m): mock_obj = m.patch(self.URL, text=self.TEXT) self.assertResponse(requests.patch(self.URL)) self.assertTrue(mock_obj.called) self.assertTrue(mock_obj.called_once) self.assertTrue(m.called) self.assertTrue(m.called_once) @requests_mock.Mocker() def test_mocker_delete(self, m): mock_obj = m.delete(self.URL, text=self.TEXT) self.assertResponse(requests.delete(self.URL)) self.assertTrue(mock_obj.called) self.assertTrue(mock_obj.called_once) self.assertTrue(m.called) self.assertTrue(m.called_once) @requests_mock.Mocker() def test_mocker_real_http_and_responses(self, m): self.assertRaises(RuntimeError, m.get, self.URL, text='abcd', real_http=True) @requests_mock.Mocker() def test_mocker_real_http(self, m): data = 'testdata' uri1 = 'fake://example.com/foo' uri2 = 'fake://example.com/bar' uri3 = 'fake://example.com/baz' m.get(uri1, text=data) m.get(uri2, real_http=True) self.assertEqual(data, requests.get(uri1).text) # This should fail because requests can't get an adapter for mock:// # but it shows that it has tried and would have made a request. self.assertRaises(requests.exceptions.InvalidSchema, requests.get, uri2) # This fails because real_http is not set on the mocker self.assertRaises(exceptions.NoMockAddress, requests.get, uri3) # do it again to make sure the mock is still in place self.assertEqual(data, requests.get(uri1).text) @requests_mock.Mocker(case_sensitive=True) def test_case_sensitive_query(self, m): data = 'testdata' query = {'aBcDe': 'FgHiJ'} m.get(self.URL, text=data) resp = requests.get(self.URL, params=query) self.assertEqual('GET', m.last_request.method) self.assertEqual(200, resp.status_code) self.assertEqual(data, resp.text) for k, v in query.items(): self.assertEqual([v], m.last_request.qs[k]) @mock.patch.object(requests_mock.Mocker, 'case_sensitive', True) def test_global_case_sensitive(self): with requests_mock.mock() as m: data = 'testdata' query = {'aBcDe': 'FgHiJ'} m.get(self.URL, text=data) resp = requests.get(self.URL, params=query) self.assertEqual('GET', m.last_request.method) self.assertEqual(200, resp.status_code) self.assertEqual(data, resp.text) for k, v in query.items(): self.assertEqual([v], m.last_request.qs[k]) def test_nested_mocking(self): url1 = 'http://url1.com/path1' url2 = 'http://url2.com/path2' url3 = 'http://url3.com/path3' data1 = 'data1' data2 = 'data2' data3 = 'data3' with requests_mock.mock() as m1: r1 = m1.get(url1, text=data1) resp1a = requests.get(url1) self.assertRaises(exceptions.NoMockAddress, requests.get, url2) self.assertRaises(exceptions.NoMockAddress, requests.get, url3) self.assertEqual(data1, resp1a.text) # call count = 3 because there are 3 calls above, url 1-3 self.assertEqual(3, m1.call_count) self.assertEqual(1, r1.call_count) with requests_mock.mock() as m2: r2 = m2.get(url2, text=data2) self.assertRaises(exceptions.NoMockAddress, requests.get, url1) resp2a = requests.get(url2) self.assertRaises(exceptions.NoMockAddress, requests.get, url3) self.assertEqual(data2, resp2a.text) with requests_mock.mock() as m3: r3 = m3.get(url3, text=data3) self.assertRaises(exceptions.NoMockAddress, requests.get, url1) self.assertRaises(exceptions.NoMockAddress, requests.get, url2) resp3 = requests.get(url3) self.assertEqual(data3, resp3.text) self.assertEqual(3, m3.call_count) self.assertEqual(1, r3.call_count) resp2b = requests.get(url2) self.assertRaises(exceptions.NoMockAddress, requests.get, url1) self.assertEqual(data2, resp2b.text) self.assertRaises(exceptions.NoMockAddress, requests.get, url3) self.assertEqual(3, m1.call_count) self.assertEqual(1, r1.call_count) self.assertEqual(6, m2.call_count) self.assertEqual(2, r2.call_count) self.assertEqual(3, m3.call_count) self.assertEqual(1, r3.call_count) resp1b = requests.get(url1) self.assertEqual(data1, resp1b.text) self.assertRaises(exceptions.NoMockAddress, requests.get, url2) self.assertRaises(exceptions.NoMockAddress, requests.get, url3) self.assertEqual(6, m1.call_count) self.assertEqual(2, r1.call_count) @requests_mock.mock() def test_mocker_additional(self, m): url = 'http://www.example.com' good_text = 'success' def additional_cb(req): return 'hello' in req.text m.post(url, additional_matcher=additional_cb, text=good_text) self.assertEqual(good_text, requests.post(url, data='hello world').text) self.assertRaises(exceptions.NoMockAddress, requests.post, url, data='goodbye world') @requests_mock.mock() def test_mocker_pickle(self, m): url = 'http://www.example.com' text = 'hello world' m.get(url, text=text) orig_resp = requests.get(url) self.assertEqual(text, orig_resp.text) d = pickle.dumps(orig_resp) new_resp = pickle.loads(d) self.assertEqual(text, new_resp.text) self.assertIsInstance(orig_resp.request.matcher, adapter._Matcher) self.assertIsNone(new_resp.request.matcher) @requests_mock.mock() def test_stream_zero_bytes(self, m): content = b'blah' m.get("http://test", content=content) res = requests.get("http://test", stream=True) zero_val = res.raw.read(0) self.assertEqual(b'', zero_val) self.assertFalse(res.raw.closed) full_val = res.raw.read() self.assertEqual(content, full_val) def test_with_json_encoder_on_mocker(self): test_val = 'hello world' class MyJsonEncoder(json.JSONEncoder): def encode(s, o): return test_val with requests_mock.Mocker(json_encoder=MyJsonEncoder) as m: m.get("http://test", json={"a": "b"}) res = requests.get("http://test") self.assertEqual(test_val, res.text) @requests_mock.mock() def test_with_json_encoder_on_endpoint(self, m): test_val = 'hello world' class MyJsonEncoder(json.JSONEncoder): def encode(s, o): return test_val m.get("http://test", json={"a": "b"}, json_encoder=MyJsonEncoder) res = requests.get("http://test") self.assertEqual(test_val, res.text) @requests_mock.mock() def test_mismatch_content_length_streaming(self, m): url = "https://test/package.tar.gz" def f(request, context): context.headers["Content-Length"] = "300810" return None m.head( url=url, status_code=200, text=f, ) requests.head(url)
MockerHttpMethodsTests