ZTWHHH commited on
Commit
cb41ed4
·
verified ·
1 Parent(s): 90878cc

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. videochat2/lib/python3.10/site-packages/pandas/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  2. videochat2/lib/python3.10/site-packages/pandas/tests/__pycache__/test_common.cpython-310.pyc +0 -0
  3. videochat2/lib/python3.10/site-packages/pandas/tests/__pycache__/test_optional_dependency.cpython-310.pyc +0 -0
  4. videochat2/lib/python3.10/site-packages/pandas/tests/__pycache__/test_register_accessor.cpython-310.pyc +0 -0
  5. videochat2/lib/python3.10/site-packages/pandas/tests/__pycache__/test_take.cpython-310.pyc +0 -0
  6. videochat2/lib/python3.10/site-packages/pandas/tests/api/__init__.py +0 -0
  7. videochat2/lib/python3.10/site-packages/pandas/tests/api/test_types.py +62 -0
  8. videochat2/lib/python3.10/site-packages/pandas/tests/base/__pycache__/__init__.cpython-310.pyc +0 -0
  9. videochat2/lib/python3.10/site-packages/pandas/tests/base/__pycache__/common.cpython-310.pyc +0 -0
  10. videochat2/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_constructors.cpython-310.pyc +0 -0
  11. videochat2/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_conversion.cpython-310.pyc +0 -0
  12. videochat2/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_fillna.cpython-310.pyc +0 -0
  13. videochat2/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_misc.cpython-310.pyc +0 -0
  14. videochat2/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_transpose.cpython-310.pyc +0 -0
  15. videochat2/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_unique.cpython-310.pyc +0 -0
  16. videochat2/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_value_counts.cpython-310.pyc +0 -0
  17. videochat2/lib/python3.10/site-packages/pandas/tests/base/common.py +10 -0
  18. videochat2/lib/python3.10/site-packages/pandas/tests/base/test_fillna.py +60 -0
  19. videochat2/lib/python3.10/site-packages/pandas/tests/base/test_misc.py +187 -0
  20. videochat2/lib/python3.10/site-packages/pandas/tests/internals/__pycache__/__init__.cpython-310.pyc +0 -0
  21. videochat2/lib/python3.10/site-packages/pandas/tests/internals/__pycache__/test_api.cpython-310.pyc +0 -0
  22. videochat2/lib/python3.10/site-packages/pandas/tests/internals/__pycache__/test_internals.cpython-310.pyc +0 -0
  23. videochat2/lib/python3.10/site-packages/pandas/tests/internals/__pycache__/test_managers.cpython-310.pyc +0 -0
  24. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__init__.py +0 -0
  25. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/__init__.cpython-310.pyc +0 -0
  26. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/common.cpython-310.pyc +0 -0
  27. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/conftest.cpython-310.pyc +0 -0
  28. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/test_backend.cpython-310.pyc +0 -0
  29. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/test_boxplot_method.cpython-310.pyc +0 -0
  30. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/test_common.cpython-310.pyc +0 -0
  31. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/test_converter.cpython-310.pyc +0 -0
  32. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/test_datetimelike.cpython-310.pyc +0 -0
  33. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/test_groupby.cpython-310.pyc +0 -0
  34. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/test_hist_method.cpython-310.pyc +0 -0
  35. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/test_misc.cpython-310.pyc +0 -0
  36. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/test_series.cpython-310.pyc +0 -0
  37. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/test_style.cpython-310.pyc +0 -0
  38. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/common.py +585 -0
  39. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/conftest.py +34 -0
  40. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/__init__.py +0 -0
  41. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/__pycache__/__init__.cpython-310.pyc +0 -0
  42. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/__pycache__/test_frame.cpython-310.pyc +0 -0
  43. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/__pycache__/test_frame_color.cpython-310.pyc +0 -0
  44. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/__pycache__/test_frame_groupby.cpython-310.pyc +0 -0
  45. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/__pycache__/test_frame_legend.cpython-310.pyc +0 -0
  46. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/__pycache__/test_frame_subplots.cpython-310.pyc +0 -0
  47. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/__pycache__/test_hist_box_by.cpython-310.pyc +0 -0
  48. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/test_frame.py +2223 -0
  49. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/test_frame_color.py +661 -0
  50. videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/test_frame_groupby.py +73 -0
videochat2/lib/python3.10/site-packages/pandas/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (168 Bytes). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/__pycache__/test_common.cpython-310.pyc ADDED
Binary file (6.95 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/__pycache__/test_optional_dependency.cpython-310.pyc ADDED
Binary file (2.47 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/__pycache__/test_register_accessor.cpython-310.pyc ADDED
Binary file (4.18 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/__pycache__/test_take.cpython-310.pyc ADDED
Binary file (9.39 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/api/__init__.py ADDED
File without changes
videochat2/lib/python3.10/site-packages/pandas/tests/api/test_types.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import pandas._testing as tm
4
+ from pandas.api import types
5
+ from pandas.tests.api.test_api import Base
6
+
7
+
8
+ class TestTypes(Base):
9
+ allowed = [
10
+ "is_any_real_numeric_dtype",
11
+ "is_bool",
12
+ "is_bool_dtype",
13
+ "is_categorical_dtype",
14
+ "is_complex",
15
+ "is_complex_dtype",
16
+ "is_datetime64_any_dtype",
17
+ "is_datetime64_dtype",
18
+ "is_datetime64_ns_dtype",
19
+ "is_datetime64tz_dtype",
20
+ "is_dtype_equal",
21
+ "is_float",
22
+ "is_float_dtype",
23
+ "is_int64_dtype",
24
+ "is_integer",
25
+ "is_integer_dtype",
26
+ "is_number",
27
+ "is_numeric_dtype",
28
+ "is_object_dtype",
29
+ "is_scalar",
30
+ "is_sparse",
31
+ "is_string_dtype",
32
+ "is_signed_integer_dtype",
33
+ "is_timedelta64_dtype",
34
+ "is_timedelta64_ns_dtype",
35
+ "is_unsigned_integer_dtype",
36
+ "is_period_dtype",
37
+ "is_interval",
38
+ "is_interval_dtype",
39
+ "is_re",
40
+ "is_re_compilable",
41
+ "is_dict_like",
42
+ "is_iterator",
43
+ "is_file_like",
44
+ "is_list_like",
45
+ "is_hashable",
46
+ "is_array_like",
47
+ "is_named_tuple",
48
+ "pandas_dtype",
49
+ "union_categoricals",
50
+ "infer_dtype",
51
+ "is_extension_array_dtype",
52
+ ]
53
+ deprecated: list[str] = []
54
+ dtypes = ["CategoricalDtype", "DatetimeTZDtype", "PeriodDtype", "IntervalDtype"]
55
+
56
+ def test_types(self):
57
+ self.check(types, self.allowed + self.dtypes + self.deprecated)
58
+
59
+ def test_deprecated_from_api_types(self):
60
+ for t in self.deprecated:
61
+ with tm.assert_produces_warning(FutureWarning):
62
+ getattr(types, t)(1)
videochat2/lib/python3.10/site-packages/pandas/tests/base/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (173 Bytes). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/base/__pycache__/common.cpython-310.pyc ADDED
Binary file (550 Bytes). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_constructors.cpython-310.pyc ADDED
Binary file (5.5 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_conversion.cpython-310.pyc ADDED
Binary file (13.5 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_fillna.cpython-310.pyc ADDED
Binary file (1.55 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_misc.cpython-310.pyc ADDED
Binary file (4.69 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_transpose.cpython-310.pyc ADDED
Binary file (1.81 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_unique.cpython-310.pyc ADDED
Binary file (3.5 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/base/__pycache__/test_value_counts.cpython-310.pyc ADDED
Binary file (7.05 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/base/common.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ from pandas import Index
4
+ from pandas.api.types import is_bool_dtype
5
+
6
+
7
+ def allow_na_ops(obj: Any) -> bool:
8
+ """Whether to skip test cases including NaN"""
9
+ is_bool_index = isinstance(obj, Index) and is_bool_dtype(obj)
10
+ return not is_bool_index and obj._can_hold_na
videochat2/lib/python3.10/site-packages/pandas/tests/base/test_fillna.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Though Index.fillna and Series.fillna has separate impl,
3
+ test here to confirm these works as the same
4
+ """
5
+
6
+ import numpy as np
7
+ import pytest
8
+
9
+ from pandas import MultiIndex
10
+ import pandas._testing as tm
11
+ from pandas.tests.base.common import allow_na_ops
12
+
13
+
14
+ def test_fillna(index_or_series_obj):
15
+ # GH 11343
16
+ obj = index_or_series_obj
17
+
18
+ if isinstance(obj, MultiIndex):
19
+ msg = "isna is not defined for MultiIndex"
20
+ with pytest.raises(NotImplementedError, match=msg):
21
+ obj.fillna(0)
22
+ return
23
+
24
+ # values will not be changed
25
+ fill_value = obj.values[0] if len(obj) > 0 else 0
26
+ result = obj.fillna(fill_value)
27
+
28
+ tm.assert_equal(obj, result)
29
+
30
+ # check shallow_copied
31
+ assert obj is not result
32
+
33
+
34
+ @pytest.mark.parametrize("null_obj", [np.nan, None])
35
+ def test_fillna_null(null_obj, index_or_series_obj):
36
+ # GH 11343
37
+ obj = index_or_series_obj
38
+ klass = type(obj)
39
+
40
+ if not allow_na_ops(obj):
41
+ pytest.skip(f"{klass} doesn't allow for NA operations")
42
+ elif len(obj) < 1:
43
+ pytest.skip("Test doesn't make sense on empty data")
44
+ elif isinstance(obj, MultiIndex):
45
+ pytest.skip(f"MultiIndex can't hold '{null_obj}'")
46
+
47
+ values = obj._values
48
+ fill_value = values[0]
49
+ expected = values.copy()
50
+ values[0:2] = null_obj
51
+ expected[0:2] = fill_value
52
+
53
+ expected = klass(expected)
54
+ obj = klass(values)
55
+
56
+ result = obj.fillna(fill_value)
57
+ tm.assert_equal(result, expected)
58
+
59
+ # check shallow_copied
60
+ assert obj is not result
videochat2/lib/python3.10/site-packages/pandas/tests/base/test_misc.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import numpy as np
4
+ import pytest
5
+
6
+ from pandas.compat import (
7
+ IS64,
8
+ PYPY,
9
+ )
10
+
11
+ from pandas.core.dtypes.common import (
12
+ is_categorical_dtype,
13
+ is_dtype_equal,
14
+ is_object_dtype,
15
+ )
16
+
17
+ import pandas as pd
18
+ from pandas import (
19
+ Index,
20
+ Series,
21
+ )
22
+ import pandas._testing as tm
23
+
24
+
25
+ def test_isnull_notnull_docstrings():
26
+ # GH#41855 make sure its clear these are aliases
27
+ doc = pd.DataFrame.notnull.__doc__
28
+ assert doc.startswith("\nDataFrame.notnull is an alias for DataFrame.notna.\n")
29
+ doc = pd.DataFrame.isnull.__doc__
30
+ assert doc.startswith("\nDataFrame.isnull is an alias for DataFrame.isna.\n")
31
+
32
+ doc = Series.notnull.__doc__
33
+ assert doc.startswith("\nSeries.notnull is an alias for Series.notna.\n")
34
+ doc = Series.isnull.__doc__
35
+ assert doc.startswith("\nSeries.isnull is an alias for Series.isna.\n")
36
+
37
+
38
+ @pytest.mark.parametrize(
39
+ "op_name, op",
40
+ [
41
+ ("add", "+"),
42
+ ("sub", "-"),
43
+ ("mul", "*"),
44
+ ("mod", "%"),
45
+ ("pow", "**"),
46
+ ("truediv", "/"),
47
+ ("floordiv", "//"),
48
+ ],
49
+ )
50
+ def test_binary_ops_docstring(frame_or_series, op_name, op):
51
+ # not using the all_arithmetic_functions fixture with _get_opstr
52
+ # as _get_opstr is used internally in the dynamic implementation of the docstring
53
+ klass = frame_or_series
54
+
55
+ operand1 = klass.__name__.lower()
56
+ operand2 = "other"
57
+ expected_str = " ".join([operand1, op, operand2])
58
+ assert expected_str in getattr(klass, op_name).__doc__
59
+
60
+ # reverse version of the binary ops
61
+ expected_str = " ".join([operand2, op, operand1])
62
+ assert expected_str in getattr(klass, "r" + op_name).__doc__
63
+
64
+
65
+ def test_ndarray_compat_properties(index_or_series_obj):
66
+ obj = index_or_series_obj
67
+
68
+ # Check that we work.
69
+ for p in ["shape", "dtype", "T", "nbytes"]:
70
+ assert getattr(obj, p, None) is not None
71
+
72
+ # deprecated properties
73
+ for p in ["strides", "itemsize", "base", "data"]:
74
+ assert not hasattr(obj, p)
75
+
76
+ msg = "can only convert an array of size 1 to a Python scalar"
77
+ with pytest.raises(ValueError, match=msg):
78
+ obj.item() # len > 1
79
+
80
+ assert obj.ndim == 1
81
+ assert obj.size == len(obj)
82
+
83
+ assert Index([1]).item() == 1
84
+ assert Series([1]).item() == 1
85
+
86
+
87
+ @pytest.mark.skipif(PYPY, reason="not relevant for PyPy")
88
+ def test_memory_usage(index_or_series_obj):
89
+ obj = index_or_series_obj
90
+
91
+ res = obj.memory_usage()
92
+ res_deep = obj.memory_usage(deep=True)
93
+
94
+ is_ser = isinstance(obj, Series)
95
+ is_object = is_object_dtype(obj) or (
96
+ isinstance(obj, Series) and is_object_dtype(obj.index)
97
+ )
98
+ is_categorical = is_categorical_dtype(obj.dtype) or (
99
+ isinstance(obj, Series) and is_categorical_dtype(obj.index.dtype)
100
+ )
101
+ is_object_string = is_dtype_equal(obj, "string[python]") or (
102
+ is_ser and is_dtype_equal(obj.index.dtype, "string[python]")
103
+ )
104
+
105
+ if len(obj) == 0:
106
+ if isinstance(obj, Index):
107
+ expected = 0
108
+ else:
109
+ expected = 108 if IS64 else 64
110
+ assert res_deep == res == expected
111
+ elif is_object or is_categorical or is_object_string:
112
+ # only deep will pick them up
113
+ assert res_deep > res
114
+ else:
115
+ assert res == res_deep
116
+
117
+ # sys.getsizeof will call the .memory_usage with
118
+ # deep=True, and add on some GC overhead
119
+ diff = res_deep - sys.getsizeof(obj)
120
+ assert abs(diff) < 100
121
+
122
+
123
+ def test_memory_usage_components_series(series_with_simple_index):
124
+ series = series_with_simple_index
125
+ total_usage = series.memory_usage(index=True)
126
+ non_index_usage = series.memory_usage(index=False)
127
+ index_usage = series.index.memory_usage()
128
+ assert total_usage == non_index_usage + index_usage
129
+
130
+
131
+ @pytest.mark.parametrize("dtype", tm.NARROW_NP_DTYPES)
132
+ def test_memory_usage_components_narrow_series(dtype):
133
+ series = tm.make_rand_series(name="a", dtype=dtype)
134
+ total_usage = series.memory_usage(index=True)
135
+ non_index_usage = series.memory_usage(index=False)
136
+ index_usage = series.index.memory_usage()
137
+ assert total_usage == non_index_usage + index_usage
138
+
139
+
140
+ def test_searchsorted(request, index_or_series_obj):
141
+ # numpy.searchsorted calls obj.searchsorted under the hood.
142
+ # See gh-12238
143
+ obj = index_or_series_obj
144
+
145
+ if isinstance(obj, pd.MultiIndex):
146
+ # See gh-14833
147
+ request.node.add_marker(
148
+ pytest.mark.xfail(
149
+ reason="np.searchsorted doesn't work on pd.MultiIndex: GH 14833"
150
+ )
151
+ )
152
+ elif obj.dtype.kind == "c" and isinstance(obj, Index):
153
+ # TODO: Should Series cases also raise? Looks like they use numpy
154
+ # comparison semantics https://github.com/numpy/numpy/issues/15981
155
+ mark = pytest.mark.xfail(reason="complex objects are not comparable")
156
+ request.node.add_marker(mark)
157
+
158
+ max_obj = max(obj, default=0)
159
+ index = np.searchsorted(obj, max_obj)
160
+ assert 0 <= index <= len(obj)
161
+
162
+ index = np.searchsorted(obj, max_obj, sorter=range(len(obj)))
163
+ assert 0 <= index <= len(obj)
164
+
165
+
166
+ def test_access_by_position(index_flat):
167
+ index = index_flat
168
+
169
+ if len(index) == 0:
170
+ pytest.skip("Test doesn't make sense on empty data")
171
+
172
+ series = Series(index)
173
+ assert index[0] == series.iloc[0]
174
+ assert index[5] == series.iloc[5]
175
+ assert index[-1] == series.iloc[-1]
176
+
177
+ size = len(index)
178
+ assert index[-1] == index[size - 1]
179
+
180
+ msg = f"index {size} is out of bounds for axis 0 with size {size}"
181
+ if is_dtype_equal(index.dtype, "string[pyarrow]"):
182
+ msg = "index out of bounds"
183
+ with pytest.raises(IndexError, match=msg):
184
+ index[size]
185
+ msg = "single positional indexer is out-of-bounds"
186
+ with pytest.raises(IndexError, match=msg):
187
+ series.iloc[size]
videochat2/lib/python3.10/site-packages/pandas/tests/internals/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (178 Bytes). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/internals/__pycache__/test_api.cpython-310.pyc ADDED
Binary file (1.52 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/internals/__pycache__/test_internals.cpython-310.pyc ADDED
Binary file (40.2 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/internals/__pycache__/test_managers.cpython-310.pyc ADDED
Binary file (2.12 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__init__.py ADDED
File without changes
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (177 Bytes). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/common.cpython-310.pyc ADDED
Binary file (17.3 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/conftest.cpython-310.pyc ADDED
Binary file (824 Bytes). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/test_backend.cpython-310.pyc ADDED
Binary file (3.36 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/test_boxplot_method.cpython-310.pyc ADDED
Binary file (19.5 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/test_common.cpython-310.pyc ADDED
Binary file (2.43 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/test_converter.cpython-310.pyc ADDED
Binary file (13.2 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/test_datetimelike.cpython-310.pyc ADDED
Binary file (46.7 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/test_groupby.cpython-310.pyc ADDED
Binary file (5.33 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/test_hist_method.cpython-310.pyc ADDED
Binary file (23.4 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/test_misc.cpython-310.pyc ADDED
Binary file (19.1 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/test_series.cpython-310.pyc ADDED
Binary file (28.4 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/__pycache__/test_style.cpython-310.pyc ADDED
Binary file (4.64 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/common.py ADDED
@@ -0,0 +1,585 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module consolidating common testing functions for checking plotting.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import (
8
+ TYPE_CHECKING,
9
+ Sequence,
10
+ )
11
+
12
+ import numpy as np
13
+
14
+ from pandas.util._decorators import cache_readonly
15
+ import pandas.util._test_decorators as td
16
+
17
+ from pandas.core.dtypes.api import is_list_like
18
+
19
+ import pandas as pd
20
+ from pandas import Series
21
+ import pandas._testing as tm
22
+
23
+ if TYPE_CHECKING:
24
+ from matplotlib.axes import Axes
25
+
26
+
27
+ @td.skip_if_no_mpl
28
+ class TestPlotBase:
29
+ """
30
+ This is a common base class used for various plotting tests
31
+ """
32
+
33
+ def setup_method(self):
34
+ import matplotlib as mpl
35
+
36
+ mpl.rcdefaults()
37
+
38
+ def teardown_method(self):
39
+ tm.close()
40
+
41
+ @cache_readonly
42
+ def plt(self):
43
+ import matplotlib.pyplot as plt
44
+
45
+ return plt
46
+
47
+ @cache_readonly
48
+ def colorconverter(self):
49
+ from matplotlib import colors
50
+
51
+ return colors.colorConverter
52
+
53
+ def _check_legend_labels(self, axes, labels=None, visible=True):
54
+ """
55
+ Check each axes has expected legend labels
56
+
57
+ Parameters
58
+ ----------
59
+ axes : matplotlib Axes object, or its list-like
60
+ labels : list-like
61
+ expected legend labels
62
+ visible : bool
63
+ expected legend visibility. labels are checked only when visible is
64
+ True
65
+ """
66
+ if visible and (labels is None):
67
+ raise ValueError("labels must be specified when visible is True")
68
+ axes = self._flatten_visible(axes)
69
+ for ax in axes:
70
+ if visible:
71
+ assert ax.get_legend() is not None
72
+ self._check_text_labels(ax.get_legend().get_texts(), labels)
73
+ else:
74
+ assert ax.get_legend() is None
75
+
76
+ def _check_legend_marker(self, ax, expected_markers=None, visible=True):
77
+ """
78
+ Check ax has expected legend markers
79
+
80
+ Parameters
81
+ ----------
82
+ ax : matplotlib Axes object
83
+ expected_markers : list-like
84
+ expected legend markers
85
+ visible : bool
86
+ expected legend visibility. labels are checked only when visible is
87
+ True
88
+ """
89
+ if visible and (expected_markers is None):
90
+ raise ValueError("Markers must be specified when visible is True")
91
+ if visible:
92
+ handles, _ = ax.get_legend_handles_labels()
93
+ markers = [handle.get_marker() for handle in handles]
94
+ assert markers == expected_markers
95
+ else:
96
+ assert ax.get_legend() is None
97
+
98
+ def _check_data(self, xp, rs):
99
+ """
100
+ Check each axes has identical lines
101
+
102
+ Parameters
103
+ ----------
104
+ xp : matplotlib Axes object
105
+ rs : matplotlib Axes object
106
+ """
107
+ xp_lines = xp.get_lines()
108
+ rs_lines = rs.get_lines()
109
+
110
+ assert len(xp_lines) == len(rs_lines)
111
+ for xpl, rsl in zip(xp_lines, rs_lines):
112
+ xpdata = xpl.get_xydata()
113
+ rsdata = rsl.get_xydata()
114
+ tm.assert_almost_equal(xpdata, rsdata)
115
+
116
+ tm.close()
117
+
118
+ def _check_visible(self, collections, visible=True):
119
+ """
120
+ Check each artist is visible or not
121
+
122
+ Parameters
123
+ ----------
124
+ collections : matplotlib Artist or its list-like
125
+ target Artist or its list or collection
126
+ visible : bool
127
+ expected visibility
128
+ """
129
+ from matplotlib.collections import Collection
130
+
131
+ if not isinstance(collections, Collection) and not is_list_like(collections):
132
+ collections = [collections]
133
+
134
+ for patch in collections:
135
+ assert patch.get_visible() == visible
136
+
137
+ def _check_patches_all_filled(
138
+ self, axes: Axes | Sequence[Axes], filled: bool = True
139
+ ) -> None:
140
+ """
141
+ Check for each artist whether it is filled or not
142
+
143
+ Parameters
144
+ ----------
145
+ axes : matplotlib Axes object, or its list-like
146
+ filled : bool
147
+ expected filling
148
+ """
149
+
150
+ axes = self._flatten_visible(axes)
151
+ for ax in axes:
152
+ for patch in ax.patches:
153
+ assert patch.fill == filled
154
+
155
+ def _get_colors_mapped(self, series, colors):
156
+ unique = series.unique()
157
+ # unique and colors length can be differed
158
+ # depending on slice value
159
+ mapped = dict(zip(unique, colors))
160
+ return [mapped[v] for v in series.values]
161
+
162
+ def _check_colors(
163
+ self, collections, linecolors=None, facecolors=None, mapping=None
164
+ ):
165
+ """
166
+ Check each artist has expected line colors and face colors
167
+
168
+ Parameters
169
+ ----------
170
+ collections : list-like
171
+ list or collection of target artist
172
+ linecolors : list-like which has the same length as collections
173
+ list of expected line colors
174
+ facecolors : list-like which has the same length as collections
175
+ list of expected face colors
176
+ mapping : Series
177
+ Series used for color grouping key
178
+ used for andrew_curves, parallel_coordinates, radviz test
179
+ """
180
+ from matplotlib.collections import (
181
+ Collection,
182
+ LineCollection,
183
+ PolyCollection,
184
+ )
185
+ from matplotlib.lines import Line2D
186
+
187
+ conv = self.colorconverter
188
+ if linecolors is not None:
189
+ if mapping is not None:
190
+ linecolors = self._get_colors_mapped(mapping, linecolors)
191
+ linecolors = linecolors[: len(collections)]
192
+
193
+ assert len(collections) == len(linecolors)
194
+ for patch, color in zip(collections, linecolors):
195
+ if isinstance(patch, Line2D):
196
+ result = patch.get_color()
197
+ # Line2D may contains string color expression
198
+ result = conv.to_rgba(result)
199
+ elif isinstance(patch, (PolyCollection, LineCollection)):
200
+ result = tuple(patch.get_edgecolor()[0])
201
+ else:
202
+ result = patch.get_edgecolor()
203
+
204
+ expected = conv.to_rgba(color)
205
+ assert result == expected
206
+
207
+ if facecolors is not None:
208
+ if mapping is not None:
209
+ facecolors = self._get_colors_mapped(mapping, facecolors)
210
+ facecolors = facecolors[: len(collections)]
211
+
212
+ assert len(collections) == len(facecolors)
213
+ for patch, color in zip(collections, facecolors):
214
+ if isinstance(patch, Collection):
215
+ # returned as list of np.array
216
+ result = patch.get_facecolor()[0]
217
+ else:
218
+ result = patch.get_facecolor()
219
+
220
+ if isinstance(result, np.ndarray):
221
+ result = tuple(result)
222
+
223
+ expected = conv.to_rgba(color)
224
+ assert result == expected
225
+
226
+ def _check_text_labels(self, texts, expected):
227
+ """
228
+ Check each text has expected labels
229
+
230
+ Parameters
231
+ ----------
232
+ texts : matplotlib Text object, or its list-like
233
+ target text, or its list
234
+ expected : str or list-like which has the same length as texts
235
+ expected text label, or its list
236
+ """
237
+ if not is_list_like(texts):
238
+ assert texts.get_text() == expected
239
+ else:
240
+ labels = [t.get_text() for t in texts]
241
+ assert len(labels) == len(expected)
242
+ for label, e in zip(labels, expected):
243
+ assert label == e
244
+
245
+ def _check_ticks_props(
246
+ self, axes, xlabelsize=None, xrot=None, ylabelsize=None, yrot=None
247
+ ):
248
+ """
249
+ Check each axes has expected tick properties
250
+
251
+ Parameters
252
+ ----------
253
+ axes : matplotlib Axes object, or its list-like
254
+ xlabelsize : number
255
+ expected xticks font size
256
+ xrot : number
257
+ expected xticks rotation
258
+ ylabelsize : number
259
+ expected yticks font size
260
+ yrot : number
261
+ expected yticks rotation
262
+ """
263
+ from matplotlib.ticker import NullFormatter
264
+
265
+ axes = self._flatten_visible(axes)
266
+ for ax in axes:
267
+ if xlabelsize is not None or xrot is not None:
268
+ if isinstance(ax.xaxis.get_minor_formatter(), NullFormatter):
269
+ # If minor ticks has NullFormatter, rot / fontsize are not
270
+ # retained
271
+ labels = ax.get_xticklabels()
272
+ else:
273
+ labels = ax.get_xticklabels() + ax.get_xticklabels(minor=True)
274
+
275
+ for label in labels:
276
+ if xlabelsize is not None:
277
+ tm.assert_almost_equal(label.get_fontsize(), xlabelsize)
278
+ if xrot is not None:
279
+ tm.assert_almost_equal(label.get_rotation(), xrot)
280
+
281
+ if ylabelsize is not None or yrot is not None:
282
+ if isinstance(ax.yaxis.get_minor_formatter(), NullFormatter):
283
+ labels = ax.get_yticklabels()
284
+ else:
285
+ labels = ax.get_yticklabels() + ax.get_yticklabels(minor=True)
286
+
287
+ for label in labels:
288
+ if ylabelsize is not None:
289
+ tm.assert_almost_equal(label.get_fontsize(), ylabelsize)
290
+ if yrot is not None:
291
+ tm.assert_almost_equal(label.get_rotation(), yrot)
292
+
293
+ def _check_ax_scales(self, axes, xaxis="linear", yaxis="linear"):
294
+ """
295
+ Check each axes has expected scales
296
+
297
+ Parameters
298
+ ----------
299
+ axes : matplotlib Axes object, or its list-like
300
+ xaxis : {'linear', 'log'}
301
+ expected xaxis scale
302
+ yaxis : {'linear', 'log'}
303
+ expected yaxis scale
304
+ """
305
+ axes = self._flatten_visible(axes)
306
+ for ax in axes:
307
+ assert ax.xaxis.get_scale() == xaxis
308
+ assert ax.yaxis.get_scale() == yaxis
309
+
310
+ def _check_axes_shape(self, axes, axes_num=None, layout=None, figsize=None):
311
+ """
312
+ Check expected number of axes is drawn in expected layout
313
+
314
+ Parameters
315
+ ----------
316
+ axes : matplotlib Axes object, or its list-like
317
+ axes_num : number
318
+ expected number of axes. Unnecessary axes should be set to
319
+ invisible.
320
+ layout : tuple
321
+ expected layout, (expected number of rows , columns)
322
+ figsize : tuple
323
+ expected figsize. default is matplotlib default
324
+ """
325
+ from pandas.plotting._matplotlib.tools import flatten_axes
326
+
327
+ if figsize is None:
328
+ figsize = (6.4, 4.8)
329
+ visible_axes = self._flatten_visible(axes)
330
+
331
+ if axes_num is not None:
332
+ assert len(visible_axes) == axes_num
333
+ for ax in visible_axes:
334
+ # check something drawn on visible axes
335
+ assert len(ax.get_children()) > 0
336
+
337
+ if layout is not None:
338
+ result = self._get_axes_layout(flatten_axes(axes))
339
+ assert result == layout
340
+
341
+ tm.assert_numpy_array_equal(
342
+ visible_axes[0].figure.get_size_inches(),
343
+ np.array(figsize, dtype=np.float64),
344
+ )
345
+
346
+ def _get_axes_layout(self, axes):
347
+ x_set = set()
348
+ y_set = set()
349
+ for ax in axes:
350
+ # check axes coordinates to estimate layout
351
+ points = ax.get_position().get_points()
352
+ x_set.add(points[0][0])
353
+ y_set.add(points[0][1])
354
+ return (len(y_set), len(x_set))
355
+
356
+ def _flatten_visible(self, axes):
357
+ """
358
+ Flatten axes, and filter only visible
359
+
360
+ Parameters
361
+ ----------
362
+ axes : matplotlib Axes object, or its list-like
363
+
364
+ """
365
+ from pandas.plotting._matplotlib.tools import flatten_axes
366
+
367
+ axes = flatten_axes(axes)
368
+ axes = [ax for ax in axes if ax.get_visible()]
369
+ return axes
370
+
371
+ def _check_has_errorbars(self, axes, xerr=0, yerr=0):
372
+ """
373
+ Check axes has expected number of errorbars
374
+
375
+ Parameters
376
+ ----------
377
+ axes : matplotlib Axes object, or its list-like
378
+ xerr : number
379
+ expected number of x errorbar
380
+ yerr : number
381
+ expected number of y errorbar
382
+ """
383
+ axes = self._flatten_visible(axes)
384
+ for ax in axes:
385
+ containers = ax.containers
386
+ xerr_count = 0
387
+ yerr_count = 0
388
+ for c in containers:
389
+ has_xerr = getattr(c, "has_xerr", False)
390
+ has_yerr = getattr(c, "has_yerr", False)
391
+ if has_xerr:
392
+ xerr_count += 1
393
+ if has_yerr:
394
+ yerr_count += 1
395
+ assert xerr == xerr_count
396
+ assert yerr == yerr_count
397
+
398
+ def _check_box_return_type(
399
+ self, returned, return_type, expected_keys=None, check_ax_title=True
400
+ ):
401
+ """
402
+ Check box returned type is correct
403
+
404
+ Parameters
405
+ ----------
406
+ returned : object to be tested, returned from boxplot
407
+ return_type : str
408
+ return_type passed to boxplot
409
+ expected_keys : list-like, optional
410
+ group labels in subplot case. If not passed,
411
+ the function checks assuming boxplot uses single ax
412
+ check_ax_title : bool
413
+ Whether to check the ax.title is the same as expected_key
414
+ Intended to be checked by calling from ``boxplot``.
415
+ Normal ``plot`` doesn't attach ``ax.title``, it must be disabled.
416
+ """
417
+ from matplotlib.axes import Axes
418
+
419
+ types = {"dict": dict, "axes": Axes, "both": tuple}
420
+ if expected_keys is None:
421
+ # should be fixed when the returning default is changed
422
+ if return_type is None:
423
+ return_type = "dict"
424
+
425
+ assert isinstance(returned, types[return_type])
426
+ if return_type == "both":
427
+ assert isinstance(returned.ax, Axes)
428
+ assert isinstance(returned.lines, dict)
429
+ else:
430
+ # should be fixed when the returning default is changed
431
+ if return_type is None:
432
+ for r in self._flatten_visible(returned):
433
+ assert isinstance(r, Axes)
434
+ return
435
+
436
+ assert isinstance(returned, Series)
437
+
438
+ assert sorted(returned.keys()) == sorted(expected_keys)
439
+ for key, value in returned.items():
440
+ assert isinstance(value, types[return_type])
441
+ # check returned dict has correct mapping
442
+ if return_type == "axes":
443
+ if check_ax_title:
444
+ assert value.get_title() == key
445
+ elif return_type == "both":
446
+ if check_ax_title:
447
+ assert value.ax.get_title() == key
448
+ assert isinstance(value.ax, Axes)
449
+ assert isinstance(value.lines, dict)
450
+ elif return_type == "dict":
451
+ line = value["medians"][0]
452
+ axes = line.axes
453
+ if check_ax_title:
454
+ assert axes.get_title() == key
455
+ else:
456
+ raise AssertionError
457
+
458
+ def _check_grid_settings(self, obj, kinds, kws={}):
459
+ # Make sure plot defaults to rcParams['axes.grid'] setting, GH 9792
460
+
461
+ import matplotlib as mpl
462
+
463
+ def is_grid_on():
464
+ xticks = self.plt.gca().xaxis.get_major_ticks()
465
+ yticks = self.plt.gca().yaxis.get_major_ticks()
466
+ xoff = all(not g.gridline.get_visible() for g in xticks)
467
+ yoff = all(not g.gridline.get_visible() for g in yticks)
468
+
469
+ return not (xoff and yoff)
470
+
471
+ spndx = 1
472
+ for kind in kinds:
473
+ self.plt.subplot(1, 4 * len(kinds), spndx)
474
+ spndx += 1
475
+ mpl.rc("axes", grid=False)
476
+ obj.plot(kind=kind, **kws)
477
+ assert not is_grid_on()
478
+ self.plt.clf()
479
+
480
+ self.plt.subplot(1, 4 * len(kinds), spndx)
481
+ spndx += 1
482
+ mpl.rc("axes", grid=True)
483
+ obj.plot(kind=kind, grid=False, **kws)
484
+ assert not is_grid_on()
485
+ self.plt.clf()
486
+
487
+ if kind not in ["pie", "hexbin", "scatter"]:
488
+ self.plt.subplot(1, 4 * len(kinds), spndx)
489
+ spndx += 1
490
+ mpl.rc("axes", grid=True)
491
+ obj.plot(kind=kind, **kws)
492
+ assert is_grid_on()
493
+ self.plt.clf()
494
+
495
+ self.plt.subplot(1, 4 * len(kinds), spndx)
496
+ spndx += 1
497
+ mpl.rc("axes", grid=False)
498
+ obj.plot(kind=kind, grid=True, **kws)
499
+ assert is_grid_on()
500
+ self.plt.clf()
501
+
502
+ def _unpack_cycler(self, rcParams, field="color"):
503
+ """
504
+ Auxiliary function for correctly unpacking cycler after MPL >= 1.5
505
+ """
506
+ return [v[field] for v in rcParams["axes.prop_cycle"]]
507
+
508
+ def get_x_axis(self, ax):
509
+ return ax._shared_axes["x"]
510
+
511
+ def get_y_axis(self, ax):
512
+ return ax._shared_axes["y"]
513
+
514
+
515
+ def _check_plot_works(f, default_axes=False, **kwargs):
516
+ """
517
+ Create plot and ensure that plot return object is valid.
518
+
519
+ Parameters
520
+ ----------
521
+ f : func
522
+ Plotting function.
523
+ default_axes : bool, optional
524
+ If False (default):
525
+ - If `ax` not in `kwargs`, then create subplot(211) and plot there
526
+ - Create new subplot(212) and plot there as well
527
+ - Mind special corner case for bootstrap_plot (see `_gen_two_subplots`)
528
+ If True:
529
+ - Simply run plotting function with kwargs provided
530
+ - All required axes instances will be created automatically
531
+ - It is recommended to use it when the plotting function
532
+ creates multiple axes itself. It helps avoid warnings like
533
+ 'UserWarning: To output multiple subplots,
534
+ the figure containing the passed axes is being cleared'
535
+ **kwargs
536
+ Keyword arguments passed to the plotting function.
537
+
538
+ Returns
539
+ -------
540
+ Plot object returned by the last plotting.
541
+ """
542
+ import matplotlib.pyplot as plt
543
+
544
+ if default_axes:
545
+ gen_plots = _gen_default_plot
546
+ else:
547
+ gen_plots = _gen_two_subplots
548
+
549
+ ret = None
550
+ try:
551
+ fig = kwargs.get("figure", plt.gcf())
552
+ plt.clf()
553
+
554
+ for ret in gen_plots(f, fig, **kwargs):
555
+ tm.assert_is_valid_plot_return_object(ret)
556
+
557
+ with tm.ensure_clean(return_filelike=True) as path:
558
+ plt.savefig(path)
559
+
560
+ finally:
561
+ tm.close(fig)
562
+
563
+ return ret
564
+
565
+
566
+ def _gen_default_plot(f, fig, **kwargs):
567
+ """
568
+ Create plot in a default way.
569
+ """
570
+ yield f(**kwargs)
571
+
572
+
573
+ def _gen_two_subplots(f, fig, **kwargs):
574
+ """
575
+ Create plot on two subplots forcefully created.
576
+ """
577
+ if "ax" not in kwargs:
578
+ fig.add_subplot(211)
579
+ yield f(**kwargs)
580
+
581
+ if f is pd.plotting.bootstrap_plot:
582
+ assert "ax" not in kwargs
583
+ else:
584
+ kwargs["ax"] = fig.add_subplot(212)
585
+ yield f(**kwargs)
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/conftest.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from pandas import (
5
+ DataFrame,
6
+ to_datetime,
7
+ )
8
+
9
+
10
+ @pytest.fixture
11
+ def hist_df():
12
+ n = 100
13
+ np_random = np.random.RandomState(42)
14
+ gender = np_random.choice(["Male", "Female"], size=n)
15
+ classroom = np_random.choice(["A", "B", "C"], size=n)
16
+
17
+ hist_df = DataFrame(
18
+ {
19
+ "gender": gender,
20
+ "classroom": classroom,
21
+ "height": np.random.normal(66, 4, size=n),
22
+ "weight": np.random.normal(161, 32, size=n),
23
+ "category": np.random.randint(4, size=n),
24
+ "datetime": to_datetime(
25
+ np.random.randint(
26
+ 812419200000000000,
27
+ 819331200000000000,
28
+ size=n,
29
+ dtype=np.int64,
30
+ )
31
+ ),
32
+ }
33
+ )
34
+ return hist_df
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/__init__.py ADDED
File without changes
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (183 Bytes). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/__pycache__/test_frame.cpython-310.pyc ADDED
Binary file (67.2 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/__pycache__/test_frame_color.cpython-310.pyc ADDED
Binary file (22.7 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/__pycache__/test_frame_groupby.cpython-310.pyc ADDED
Binary file (2.03 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/__pycache__/test_frame_legend.cpython-310.pyc ADDED
Binary file (7.01 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/__pycache__/test_frame_subplots.cpython-310.pyc ADDED
Binary file (20 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/__pycache__/test_hist_box_by.cpython-310.pyc ADDED
Binary file (8.9 kB). View file
 
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/test_frame.py ADDED
@@ -0,0 +1,2223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Test cases for DataFrame.plot """
2
+ from datetime import (
3
+ date,
4
+ datetime,
5
+ )
6
+ import gc
7
+ import itertools
8
+ import re
9
+ import string
10
+ import warnings
11
+ import weakref
12
+
13
+ import numpy as np
14
+ import pytest
15
+
16
+ import pandas.util._test_decorators as td
17
+
18
+ from pandas.core.dtypes.api import is_list_like
19
+
20
+ import pandas as pd
21
+ from pandas import (
22
+ DataFrame,
23
+ MultiIndex,
24
+ PeriodIndex,
25
+ Series,
26
+ bdate_range,
27
+ date_range,
28
+ plotting,
29
+ )
30
+ import pandas._testing as tm
31
+ from pandas.tests.plotting.common import (
32
+ TestPlotBase,
33
+ _check_plot_works,
34
+ )
35
+
36
+ from pandas.io.formats.printing import pprint_thing
37
+
38
+
39
+ @td.skip_if_no_mpl
40
+ class TestDataFramePlots(TestPlotBase):
41
+ @pytest.mark.xfail(reason="Api changed in 3.6.0")
42
+ @pytest.mark.slow
43
+ def test_plot(self):
44
+ df = tm.makeTimeDataFrame()
45
+ _check_plot_works(df.plot, grid=False)
46
+
47
+ # _check_plot_works adds an ax so use default_axes=True to avoid warning
48
+ axes = _check_plot_works(df.plot, default_axes=True, subplots=True)
49
+ self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
50
+
51
+ axes = _check_plot_works(
52
+ df.plot,
53
+ default_axes=True,
54
+ subplots=True,
55
+ layout=(-1, 2),
56
+ )
57
+ self._check_axes_shape(axes, axes_num=4, layout=(2, 2))
58
+
59
+ axes = _check_plot_works(
60
+ df.plot,
61
+ default_axes=True,
62
+ subplots=True,
63
+ use_index=False,
64
+ )
65
+ self._check_ticks_props(axes, xrot=0)
66
+ self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
67
+
68
+ df = DataFrame({"x": [1, 2], "y": [3, 4]})
69
+ msg = "'Line2D' object has no property 'blarg'"
70
+ with pytest.raises(AttributeError, match=msg):
71
+ df.plot.line(blarg=True)
72
+
73
+ df = DataFrame(np.random.rand(10, 3), index=list(string.ascii_letters[:10]))
74
+
75
+ ax = _check_plot_works(df.plot, use_index=True)
76
+ self._check_ticks_props(ax, xrot=0)
77
+ _check_plot_works(df.plot, yticks=[1, 5, 10])
78
+ _check_plot_works(df.plot, xticks=[1, 5, 10])
79
+ _check_plot_works(df.plot, ylim=(-100, 100), xlim=(-100, 100))
80
+
81
+ _check_plot_works(df.plot, default_axes=True, subplots=True, title="blah")
82
+
83
+ # We have to redo it here because _check_plot_works does two plots,
84
+ # once without an ax kwarg and once with an ax kwarg and the new sharex
85
+ # behaviour does not remove the visibility of the latter axis (as ax is
86
+ # present). see: https://github.com/pandas-dev/pandas/issues/9737
87
+
88
+ axes = df.plot(subplots=True, title="blah")
89
+ self._check_axes_shape(axes, axes_num=3, layout=(3, 1))
90
+ # axes[0].figure.savefig("test.png")
91
+ for ax in axes[:2]:
92
+ self._check_visible(ax.xaxis) # xaxis must be visible for grid
93
+ self._check_visible(ax.get_xticklabels(), visible=False)
94
+ self._check_visible(ax.get_xticklabels(minor=True), visible=False)
95
+ self._check_visible([ax.xaxis.get_label()], visible=False)
96
+ for ax in [axes[2]]:
97
+ self._check_visible(ax.xaxis)
98
+ self._check_visible(ax.get_xticklabels())
99
+ self._check_visible([ax.xaxis.get_label()])
100
+ self._check_ticks_props(ax, xrot=0)
101
+
102
+ _check_plot_works(df.plot, title="blah")
103
+
104
+ tuples = zip(string.ascii_letters[:10], range(10))
105
+ df = DataFrame(np.random.rand(10, 3), index=MultiIndex.from_tuples(tuples))
106
+ ax = _check_plot_works(df.plot, use_index=True)
107
+ self._check_ticks_props(ax, xrot=0)
108
+
109
+ # unicode
110
+ index = MultiIndex.from_tuples(
111
+ [
112
+ ("\u03b1", 0),
113
+ ("\u03b1", 1),
114
+ ("\u03b2", 2),
115
+ ("\u03b2", 3),
116
+ ("\u03b3", 4),
117
+ ("\u03b3", 5),
118
+ ("\u03b4", 6),
119
+ ("\u03b4", 7),
120
+ ],
121
+ names=["i0", "i1"],
122
+ )
123
+ columns = MultiIndex.from_tuples(
124
+ [("bar", "\u0394"), ("bar", "\u0395")], names=["c0", "c1"]
125
+ )
126
+ df = DataFrame(np.random.randint(0, 10, (8, 2)), columns=columns, index=index)
127
+ _check_plot_works(df.plot, title="\u03A3")
128
+
129
+ # GH 6951
130
+ # Test with single column
131
+ df = DataFrame({"x": np.random.rand(10)})
132
+ axes = _check_plot_works(df.plot.bar, subplots=True)
133
+ self._check_axes_shape(axes, axes_num=1, layout=(1, 1))
134
+
135
+ axes = _check_plot_works(df.plot.bar, subplots=True, layout=(-1, 1))
136
+ self._check_axes_shape(axes, axes_num=1, layout=(1, 1))
137
+ # When ax is supplied and required number of axes is 1,
138
+ # passed ax should be used:
139
+ fig, ax = self.plt.subplots()
140
+ axes = df.plot.bar(subplots=True, ax=ax)
141
+ assert len(axes) == 1
142
+ result = ax.axes
143
+ assert result is axes[0]
144
+
145
+ def test_nullable_int_plot(self):
146
+ # GH 32073
147
+ dates = ["2008", "2009", None, "2011", "2012"]
148
+ df = DataFrame(
149
+ {
150
+ "A": [1, 2, 3, 4, 5],
151
+ "B": [1, 2, 3, 4, 5],
152
+ "C": np.array([7, 5, np.nan, 3, 2], dtype=object),
153
+ "D": pd.to_datetime(dates, format="%Y").view("i8"),
154
+ "E": pd.to_datetime(dates, format="%Y", utc=True).view("i8"),
155
+ }
156
+ )
157
+
158
+ _check_plot_works(df.plot, x="A", y="B")
159
+ _check_plot_works(df[["A", "B"]].plot, x="A", y="B")
160
+ _check_plot_works(df[["C", "A"]].plot, x="C", y="A") # nullable value on x-axis
161
+ _check_plot_works(df[["A", "C"]].plot, x="A", y="C")
162
+ _check_plot_works(df[["B", "C"]].plot, x="B", y="C")
163
+ _check_plot_works(df[["A", "D"]].plot, x="A", y="D")
164
+ _check_plot_works(df[["A", "E"]].plot, x="A", y="E")
165
+
166
+ @pytest.mark.slow
167
+ def test_integer_array_plot(self):
168
+ # GH 25587
169
+ arr = pd.array([1, 2, 3, 4], dtype="UInt32")
170
+
171
+ s = Series(arr)
172
+ _check_plot_works(s.plot.line)
173
+ _check_plot_works(s.plot.bar)
174
+ _check_plot_works(s.plot.hist)
175
+ _check_plot_works(s.plot.pie)
176
+
177
+ df = DataFrame({"x": arr, "y": arr})
178
+ _check_plot_works(df.plot.line)
179
+ _check_plot_works(df.plot.bar)
180
+ _check_plot_works(df.plot.hist)
181
+ _check_plot_works(df.plot.pie, y="y")
182
+ _check_plot_works(df.plot.scatter, x="x", y="y")
183
+ _check_plot_works(df.plot.hexbin, x="x", y="y")
184
+
185
+ def test_nonnumeric_exclude(self):
186
+ df = DataFrame({"A": ["x", "y", "z"], "B": [1, 2, 3]})
187
+ ax = df.plot()
188
+ assert len(ax.get_lines()) == 1 # B was plotted
189
+
190
+ def test_implicit_label(self):
191
+ df = DataFrame(np.random.randn(10, 3), columns=["a", "b", "c"])
192
+ ax = df.plot(x="a", y="b")
193
+ self._check_text_labels(ax.xaxis.get_label(), "a")
194
+
195
+ def test_donot_overwrite_index_name(self):
196
+ # GH 8494
197
+ df = DataFrame(np.random.randn(2, 2), columns=["a", "b"])
198
+ df.index.name = "NAME"
199
+ df.plot(y="b", label="LABEL")
200
+ assert df.index.name == "NAME"
201
+
202
+ def test_plot_xy(self):
203
+ # columns.inferred_type == 'string'
204
+ df = tm.makeTimeDataFrame()
205
+ self._check_data(df.plot(x=0, y=1), df.set_index("A")["B"].plot())
206
+ self._check_data(df.plot(x=0), df.set_index("A").plot())
207
+ self._check_data(df.plot(y=0), df.B.plot())
208
+ self._check_data(df.plot(x="A", y="B"), df.set_index("A").B.plot())
209
+ self._check_data(df.plot(x="A"), df.set_index("A").plot())
210
+ self._check_data(df.plot(y="B"), df.B.plot())
211
+
212
+ # columns.inferred_type == 'integer'
213
+ df.columns = np.arange(1, len(df.columns) + 1)
214
+ self._check_data(df.plot(x=1, y=2), df.set_index(1)[2].plot())
215
+ self._check_data(df.plot(x=1), df.set_index(1).plot())
216
+ self._check_data(df.plot(y=1), df[1].plot())
217
+
218
+ # figsize and title
219
+ ax = df.plot(x=1, y=2, title="Test", figsize=(16, 8))
220
+ self._check_text_labels(ax.title, "Test")
221
+ self._check_axes_shape(ax, axes_num=1, layout=(1, 1), figsize=(16.0, 8.0))
222
+
223
+ # columns.inferred_type == 'mixed'
224
+ # TODO add MultiIndex test
225
+
226
+ @pytest.mark.parametrize(
227
+ "input_log, expected_log", [(True, "log"), ("sym", "symlog")]
228
+ )
229
+ def test_logscales(self, input_log, expected_log):
230
+ df = DataFrame({"a": np.arange(100)}, index=np.arange(100))
231
+
232
+ ax = df.plot(logy=input_log)
233
+ self._check_ax_scales(ax, yaxis=expected_log)
234
+ assert ax.get_yscale() == expected_log
235
+
236
+ ax = df.plot(logx=input_log)
237
+ self._check_ax_scales(ax, xaxis=expected_log)
238
+ assert ax.get_xscale() == expected_log
239
+
240
+ ax = df.plot(loglog=input_log)
241
+ self._check_ax_scales(ax, xaxis=expected_log, yaxis=expected_log)
242
+ assert ax.get_xscale() == expected_log
243
+ assert ax.get_yscale() == expected_log
244
+
245
+ @pytest.mark.parametrize("input_param", ["logx", "logy", "loglog"])
246
+ def test_invalid_logscale(self, input_param):
247
+ # GH: 24867
248
+ df = DataFrame({"a": np.arange(100)}, index=np.arange(100))
249
+
250
+ msg = "Boolean, None and 'sym' are valid options, 'sm' is given."
251
+ with pytest.raises(ValueError, match=msg):
252
+ df.plot(**{input_param: "sm"})
253
+
254
+ def test_xcompat(self):
255
+ df = tm.makeTimeDataFrame()
256
+ ax = df.plot(x_compat=True)
257
+ lines = ax.get_lines()
258
+ assert not isinstance(lines[0].get_xdata(), PeriodIndex)
259
+ self._check_ticks_props(ax, xrot=30)
260
+
261
+ tm.close()
262
+ plotting.plot_params["xaxis.compat"] = True
263
+ ax = df.plot()
264
+ lines = ax.get_lines()
265
+ assert not isinstance(lines[0].get_xdata(), PeriodIndex)
266
+ self._check_ticks_props(ax, xrot=30)
267
+
268
+ tm.close()
269
+ plotting.plot_params["x_compat"] = False
270
+
271
+ ax = df.plot()
272
+ lines = ax.get_lines()
273
+ assert not isinstance(lines[0].get_xdata(), PeriodIndex)
274
+ assert isinstance(PeriodIndex(lines[0].get_xdata()), PeriodIndex)
275
+
276
+ tm.close()
277
+ # useful if you're plotting a bunch together
278
+ with plotting.plot_params.use("x_compat", True):
279
+ ax = df.plot()
280
+ lines = ax.get_lines()
281
+ assert not isinstance(lines[0].get_xdata(), PeriodIndex)
282
+ self._check_ticks_props(ax, xrot=30)
283
+
284
+ tm.close()
285
+ ax = df.plot()
286
+ lines = ax.get_lines()
287
+ assert not isinstance(lines[0].get_xdata(), PeriodIndex)
288
+ assert isinstance(PeriodIndex(lines[0].get_xdata()), PeriodIndex)
289
+ self._check_ticks_props(ax, xrot=0)
290
+
291
+ def test_period_compat(self):
292
+ # GH 9012
293
+ # period-array conversions
294
+ df = DataFrame(
295
+ np.random.rand(21, 2),
296
+ index=bdate_range(datetime(2000, 1, 1), datetime(2000, 1, 31)),
297
+ columns=["a", "b"],
298
+ )
299
+
300
+ df.plot()
301
+ self.plt.axhline(y=0)
302
+ tm.close()
303
+
304
+ def test_unsorted_index(self):
305
+ df = DataFrame(
306
+ {"y": np.arange(100)}, index=np.arange(99, -1, -1), dtype=np.int64
307
+ )
308
+ ax = df.plot()
309
+ lines = ax.get_lines()[0]
310
+ rs = lines.get_xydata()
311
+ rs = Series(rs[:, 1], rs[:, 0], dtype=np.int64, name="y")
312
+ tm.assert_series_equal(rs, df.y, check_index_type=False)
313
+ tm.close()
314
+
315
+ df.index = pd.Index(np.arange(99, -1, -1), dtype=np.float64)
316
+ ax = df.plot()
317
+ lines = ax.get_lines()[0]
318
+ rs = lines.get_xydata()
319
+ rs = Series(rs[:, 1], rs[:, 0], dtype=np.int64, name="y")
320
+ tm.assert_series_equal(rs, df.y)
321
+
322
+ def test_unsorted_index_lims(self):
323
+ df = DataFrame({"y": [0.0, 1.0, 2.0, 3.0]}, index=[1.0, 0.0, 3.0, 2.0])
324
+ ax = df.plot()
325
+ xmin, xmax = ax.get_xlim()
326
+ lines = ax.get_lines()
327
+ assert xmin <= np.nanmin(lines[0].get_data()[0])
328
+ assert xmax >= np.nanmax(lines[0].get_data()[0])
329
+
330
+ df = DataFrame(
331
+ {"y": [0.0, 1.0, np.nan, 3.0, 4.0, 5.0, 6.0]},
332
+ index=[1.0, 0.0, 3.0, 2.0, np.nan, 3.0, 2.0],
333
+ )
334
+ ax = df.plot()
335
+ xmin, xmax = ax.get_xlim()
336
+ lines = ax.get_lines()
337
+ assert xmin <= np.nanmin(lines[0].get_data()[0])
338
+ assert xmax >= np.nanmax(lines[0].get_data()[0])
339
+
340
+ df = DataFrame({"y": [0.0, 1.0, 2.0, 3.0], "z": [91.0, 90.0, 93.0, 92.0]})
341
+ ax = df.plot(x="z", y="y")
342
+ xmin, xmax = ax.get_xlim()
343
+ lines = ax.get_lines()
344
+ assert xmin <= np.nanmin(lines[0].get_data()[0])
345
+ assert xmax >= np.nanmax(lines[0].get_data()[0])
346
+
347
+ def test_negative_log(self):
348
+ df = -DataFrame(
349
+ np.random.rand(6, 4),
350
+ index=list(string.ascii_letters[:6]),
351
+ columns=["x", "y", "z", "four"],
352
+ )
353
+ msg = "Log-y scales are not supported in area plot"
354
+ with pytest.raises(ValueError, match=msg):
355
+ df.plot.area(logy=True)
356
+ with pytest.raises(ValueError, match=msg):
357
+ df.plot.area(loglog=True)
358
+
359
+ def _compare_stacked_y_cood(self, normal_lines, stacked_lines):
360
+ base = np.zeros(len(normal_lines[0].get_data()[1]))
361
+ for nl, sl in zip(normal_lines, stacked_lines):
362
+ base += nl.get_data()[1] # get y coordinates
363
+ sy = sl.get_data()[1]
364
+ tm.assert_numpy_array_equal(base, sy)
365
+
366
+ @pytest.mark.parametrize("kind", ["line", "area"])
367
+ def test_line_area_stacked(self, kind):
368
+ np_random = np.random.RandomState(42)
369
+ df = DataFrame(np_random.rand(6, 4), columns=["w", "x", "y", "z"])
370
+ neg_df = -df
371
+ # each column has either positive or negative value
372
+ sep_df = DataFrame(
373
+ {
374
+ "w": np_random.rand(6),
375
+ "x": np_random.rand(6),
376
+ "y": -np_random.rand(6),
377
+ "z": -np_random.rand(6),
378
+ }
379
+ )
380
+ # each column has positive-negative mixed value
381
+ mixed_df = DataFrame(
382
+ np_random.randn(6, 4),
383
+ index=list(string.ascii_letters[:6]),
384
+ columns=["w", "x", "y", "z"],
385
+ )
386
+
387
+ ax1 = _check_plot_works(df.plot, kind=kind, stacked=False)
388
+ ax2 = _check_plot_works(df.plot, kind=kind, stacked=True)
389
+ self._compare_stacked_y_cood(ax1.lines, ax2.lines)
390
+
391
+ ax1 = _check_plot_works(neg_df.plot, kind=kind, stacked=False)
392
+ ax2 = _check_plot_works(neg_df.plot, kind=kind, stacked=True)
393
+ self._compare_stacked_y_cood(ax1.lines, ax2.lines)
394
+
395
+ ax1 = _check_plot_works(sep_df.plot, kind=kind, stacked=False)
396
+ ax2 = _check_plot_works(sep_df.plot, kind=kind, stacked=True)
397
+ self._compare_stacked_y_cood(ax1.lines[:2], ax2.lines[:2])
398
+ self._compare_stacked_y_cood(ax1.lines[2:], ax2.lines[2:])
399
+
400
+ _check_plot_works(mixed_df.plot, stacked=False)
401
+ msg = (
402
+ "When stacked is True, each column must be either all positive or "
403
+ "all negative. Column 'w' contains both positive and negative "
404
+ "values"
405
+ )
406
+ with pytest.raises(ValueError, match=msg):
407
+ mixed_df.plot(stacked=True)
408
+
409
+ # Use an index with strictly positive values, preventing
410
+ # matplotlib from warning about ignoring xlim
411
+ df2 = df.set_index(df.index + 1)
412
+ _check_plot_works(df2.plot, kind=kind, logx=True, stacked=True)
413
+
414
+ def test_line_area_nan_df(self):
415
+ values1 = [1, 2, np.nan, 3]
416
+ values2 = [3, np.nan, 2, 1]
417
+ df = DataFrame({"a": values1, "b": values2})
418
+ tdf = DataFrame({"a": values1, "b": values2}, index=tm.makeDateIndex(k=4))
419
+
420
+ for d in [df, tdf]:
421
+ ax = _check_plot_works(d.plot)
422
+ masked1 = ax.lines[0].get_ydata()
423
+ masked2 = ax.lines[1].get_ydata()
424
+ # remove nan for comparison purpose
425
+
426
+ exp = np.array([1, 2, 3], dtype=np.float64)
427
+ tm.assert_numpy_array_equal(np.delete(masked1.data, 2), exp)
428
+
429
+ exp = np.array([3, 2, 1], dtype=np.float64)
430
+ tm.assert_numpy_array_equal(np.delete(masked2.data, 1), exp)
431
+ tm.assert_numpy_array_equal(
432
+ masked1.mask, np.array([False, False, True, False])
433
+ )
434
+ tm.assert_numpy_array_equal(
435
+ masked2.mask, np.array([False, True, False, False])
436
+ )
437
+
438
+ expected1 = np.array([1, 2, 0, 3], dtype=np.float64)
439
+ expected2 = np.array([3, 0, 2, 1], dtype=np.float64)
440
+
441
+ ax = _check_plot_works(d.plot, stacked=True)
442
+ tm.assert_numpy_array_equal(ax.lines[0].get_ydata(), expected1)
443
+ tm.assert_numpy_array_equal(ax.lines[1].get_ydata(), expected1 + expected2)
444
+
445
+ ax = _check_plot_works(d.plot.area)
446
+ tm.assert_numpy_array_equal(ax.lines[0].get_ydata(), expected1)
447
+ tm.assert_numpy_array_equal(ax.lines[1].get_ydata(), expected1 + expected2)
448
+
449
+ ax = _check_plot_works(d.plot.area, stacked=False)
450
+ tm.assert_numpy_array_equal(ax.lines[0].get_ydata(), expected1)
451
+ tm.assert_numpy_array_equal(ax.lines[1].get_ydata(), expected2)
452
+
453
+ def test_line_lim(self):
454
+ df = DataFrame(np.random.rand(6, 3), columns=["x", "y", "z"])
455
+ ax = df.plot()
456
+ xmin, xmax = ax.get_xlim()
457
+ lines = ax.get_lines()
458
+ assert xmin <= lines[0].get_data()[0][0]
459
+ assert xmax >= lines[0].get_data()[0][-1]
460
+
461
+ ax = df.plot(secondary_y=True)
462
+ xmin, xmax = ax.get_xlim()
463
+ lines = ax.get_lines()
464
+ assert xmin <= lines[0].get_data()[0][0]
465
+ assert xmax >= lines[0].get_data()[0][-1]
466
+
467
+ axes = df.plot(secondary_y=True, subplots=True)
468
+ self._check_axes_shape(axes, axes_num=3, layout=(3, 1))
469
+ for ax in axes:
470
+ assert hasattr(ax, "left_ax")
471
+ assert not hasattr(ax, "right_ax")
472
+ xmin, xmax = ax.get_xlim()
473
+ lines = ax.get_lines()
474
+ assert xmin <= lines[0].get_data()[0][0]
475
+ assert xmax >= lines[0].get_data()[0][-1]
476
+
477
+ @pytest.mark.xfail(
478
+ strict=False,
479
+ reason="2020-12-01 this has been failing periodically on the "
480
+ "ymin==0 assertion for a week or so.",
481
+ )
482
+ @pytest.mark.parametrize("stacked", [True, False])
483
+ def test_area_lim(self, stacked):
484
+ df = DataFrame(np.random.rand(6, 4), columns=["x", "y", "z", "four"])
485
+
486
+ neg_df = -df
487
+
488
+ ax = _check_plot_works(df.plot.area, stacked=stacked)
489
+ xmin, xmax = ax.get_xlim()
490
+ ymin, ymax = ax.get_ylim()
491
+ lines = ax.get_lines()
492
+ assert xmin <= lines[0].get_data()[0][0]
493
+ assert xmax >= lines[0].get_data()[0][-1]
494
+ assert ymin == 0
495
+
496
+ ax = _check_plot_works(neg_df.plot.area, stacked=stacked)
497
+ ymin, ymax = ax.get_ylim()
498
+ assert ymax == 0
499
+
500
+ def test_area_sharey_dont_overwrite(self):
501
+ # GH37942
502
+ df = DataFrame(np.random.rand(4, 2), columns=["x", "y"])
503
+ fig, (ax1, ax2) = self.plt.subplots(1, 2, sharey=True)
504
+
505
+ df.plot(ax=ax1, kind="area")
506
+ df.plot(ax=ax2, kind="area")
507
+
508
+ assert self.get_y_axis(ax1).joined(ax1, ax2)
509
+ assert self.get_y_axis(ax2).joined(ax1, ax2)
510
+
511
+ def test_bar_linewidth(self):
512
+ df = DataFrame(np.random.randn(5, 5))
513
+
514
+ # regular
515
+ ax = df.plot.bar(linewidth=2)
516
+ for r in ax.patches:
517
+ assert r.get_linewidth() == 2
518
+
519
+ # stacked
520
+ ax = df.plot.bar(stacked=True, linewidth=2)
521
+ for r in ax.patches:
522
+ assert r.get_linewidth() == 2
523
+
524
+ # subplots
525
+ axes = df.plot.bar(linewidth=2, subplots=True)
526
+ self._check_axes_shape(axes, axes_num=5, layout=(5, 1))
527
+ for ax in axes:
528
+ for r in ax.patches:
529
+ assert r.get_linewidth() == 2
530
+
531
+ def test_bar_barwidth(self):
532
+ df = DataFrame(np.random.randn(5, 5))
533
+
534
+ width = 0.9
535
+
536
+ # regular
537
+ ax = df.plot.bar(width=width)
538
+ for r in ax.patches:
539
+ assert r.get_width() == width / len(df.columns)
540
+
541
+ # stacked
542
+ ax = df.plot.bar(stacked=True, width=width)
543
+ for r in ax.patches:
544
+ assert r.get_width() == width
545
+
546
+ # horizontal regular
547
+ ax = df.plot.barh(width=width)
548
+ for r in ax.patches:
549
+ assert r.get_height() == width / len(df.columns)
550
+
551
+ # horizontal stacked
552
+ ax = df.plot.barh(stacked=True, width=width)
553
+ for r in ax.patches:
554
+ assert r.get_height() == width
555
+
556
+ # subplots
557
+ axes = df.plot.bar(width=width, subplots=True)
558
+ for ax in axes:
559
+ for r in ax.patches:
560
+ assert r.get_width() == width
561
+
562
+ # horizontal subplots
563
+ axes = df.plot.barh(width=width, subplots=True)
564
+ for ax in axes:
565
+ for r in ax.patches:
566
+ assert r.get_height() == width
567
+
568
+ def test_bar_bottom_left(self):
569
+ df = DataFrame(np.random.rand(5, 5))
570
+ ax = df.plot.bar(stacked=False, bottom=1)
571
+ result = [p.get_y() for p in ax.patches]
572
+ assert result == [1] * 25
573
+
574
+ ax = df.plot.bar(stacked=True, bottom=[-1, -2, -3, -4, -5])
575
+ result = [p.get_y() for p in ax.patches[:5]]
576
+ assert result == [-1, -2, -3, -4, -5]
577
+
578
+ ax = df.plot.barh(stacked=False, left=np.array([1, 1, 1, 1, 1]))
579
+ result = [p.get_x() for p in ax.patches]
580
+ assert result == [1] * 25
581
+
582
+ ax = df.plot.barh(stacked=True, left=[1, 2, 3, 4, 5])
583
+ result = [p.get_x() for p in ax.patches[:5]]
584
+ assert result == [1, 2, 3, 4, 5]
585
+
586
+ axes = df.plot.bar(subplots=True, bottom=-1)
587
+ for ax in axes:
588
+ result = [p.get_y() for p in ax.patches]
589
+ assert result == [-1] * 5
590
+
591
+ axes = df.plot.barh(subplots=True, left=np.array([1, 1, 1, 1, 1]))
592
+ for ax in axes:
593
+ result = [p.get_x() for p in ax.patches]
594
+ assert result == [1] * 5
595
+
596
+ def test_bar_nan(self):
597
+ df = DataFrame({"A": [10, np.nan, 20], "B": [5, 10, 20], "C": [1, 2, 3]})
598
+ ax = df.plot.bar()
599
+ expected = [10, 0, 20, 5, 10, 20, 1, 2, 3]
600
+ result = [p.get_height() for p in ax.patches]
601
+ assert result == expected
602
+
603
+ ax = df.plot.bar(stacked=True)
604
+ result = [p.get_height() for p in ax.patches]
605
+ assert result == expected
606
+
607
+ result = [p.get_y() for p in ax.patches]
608
+ expected = [0.0, 0.0, 0.0, 10.0, 0.0, 20.0, 15.0, 10.0, 40.0]
609
+ assert result == expected
610
+
611
+ def test_bar_categorical(self):
612
+ # GH 13019
613
+ df1 = DataFrame(
614
+ np.random.randn(6, 5),
615
+ index=pd.Index(list("ABCDEF")),
616
+ columns=pd.Index(list("abcde")),
617
+ )
618
+ # categorical index must behave the same
619
+ df2 = DataFrame(
620
+ np.random.randn(6, 5),
621
+ index=pd.CategoricalIndex(list("ABCDEF")),
622
+ columns=pd.CategoricalIndex(list("abcde")),
623
+ )
624
+
625
+ for df in [df1, df2]:
626
+ ax = df.plot.bar()
627
+ ticks = ax.xaxis.get_ticklocs()
628
+ tm.assert_numpy_array_equal(ticks, np.array([0, 1, 2, 3, 4, 5]))
629
+ assert ax.get_xlim() == (-0.5, 5.5)
630
+ # check left-edge of bars
631
+ assert ax.patches[0].get_x() == -0.25
632
+ assert ax.patches[-1].get_x() == 5.15
633
+
634
+ ax = df.plot.bar(stacked=True)
635
+ tm.assert_numpy_array_equal(ticks, np.array([0, 1, 2, 3, 4, 5]))
636
+ assert ax.get_xlim() == (-0.5, 5.5)
637
+ assert ax.patches[0].get_x() == -0.25
638
+ assert ax.patches[-1].get_x() == 4.75
639
+
640
+ def test_plot_scatter(self):
641
+ df = DataFrame(
642
+ np.random.randn(6, 4),
643
+ index=list(string.ascii_letters[:6]),
644
+ columns=["x", "y", "z", "four"],
645
+ )
646
+
647
+ _check_plot_works(df.plot.scatter, x="x", y="y")
648
+ _check_plot_works(df.plot.scatter, x=1, y=2)
649
+
650
+ msg = re.escape("scatter() missing 1 required positional argument: 'y'")
651
+ with pytest.raises(TypeError, match=msg):
652
+ df.plot.scatter(x="x")
653
+ msg = re.escape("scatter() missing 1 required positional argument: 'x'")
654
+ with pytest.raises(TypeError, match=msg):
655
+ df.plot.scatter(y="y")
656
+
657
+ # GH 6951
658
+ axes = df.plot(x="x", y="y", kind="scatter", subplots=True)
659
+ self._check_axes_shape(axes, axes_num=1, layout=(1, 1))
660
+
661
+ def test_raise_error_on_datetime_time_data(self):
662
+ # GH 8113, datetime.time type is not supported by matplotlib in scatter
663
+ df = DataFrame(np.random.randn(10), columns=["a"])
664
+ df["dtime"] = date_range(start="2014-01-01", freq="h", periods=10).time
665
+ msg = "must be a string or a (real )?number, not 'datetime.time'"
666
+
667
+ with pytest.raises(TypeError, match=msg):
668
+ df.plot(kind="scatter", x="dtime", y="a")
669
+
670
+ def test_scatterplot_datetime_data(self):
671
+ # GH 30391
672
+ dates = date_range(start=date(2019, 1, 1), periods=12, freq="W")
673
+ vals = np.random.normal(0, 1, len(dates))
674
+ df = DataFrame({"dates": dates, "vals": vals})
675
+
676
+ _check_plot_works(df.plot.scatter, x="dates", y="vals")
677
+ _check_plot_works(df.plot.scatter, x=0, y=1)
678
+
679
+ def test_scatterplot_object_data(self):
680
+ # GH 18755
681
+ df = DataFrame({"a": ["A", "B", "C"], "b": [2, 3, 4]})
682
+
683
+ _check_plot_works(df.plot.scatter, x="a", y="b")
684
+ _check_plot_works(df.plot.scatter, x=0, y=1)
685
+
686
+ df = DataFrame({"a": ["A", "B", "C"], "b": ["a", "b", "c"]})
687
+
688
+ _check_plot_works(df.plot.scatter, x="a", y="b")
689
+ _check_plot_works(df.plot.scatter, x=0, y=1)
690
+
691
+ @pytest.mark.parametrize("ordered", [True, False])
692
+ @pytest.mark.parametrize(
693
+ "categories",
694
+ (["setosa", "versicolor", "virginica"], ["versicolor", "virginica", "setosa"]),
695
+ )
696
+ def test_scatterplot_color_by_categorical(self, ordered, categories):
697
+ df = DataFrame(
698
+ [[5.1, 3.5], [4.9, 3.0], [7.0, 3.2], [6.4, 3.2], [5.9, 3.0]],
699
+ columns=["length", "width"],
700
+ )
701
+ df["species"] = pd.Categorical(
702
+ ["setosa", "setosa", "virginica", "virginica", "versicolor"],
703
+ ordered=ordered,
704
+ categories=categories,
705
+ )
706
+ ax = df.plot.scatter(x=0, y=1, c="species")
707
+ (colorbar_collection,) = ax.collections
708
+ colorbar = colorbar_collection.colorbar
709
+
710
+ expected_ticks = np.array([0.5, 1.5, 2.5])
711
+ result_ticks = colorbar.get_ticks()
712
+ tm.assert_numpy_array_equal(result_ticks, expected_ticks)
713
+
714
+ expected_boundaries = np.array([0.0, 1.0, 2.0, 3.0])
715
+ result_boundaries = colorbar._boundaries
716
+ tm.assert_numpy_array_equal(result_boundaries, expected_boundaries)
717
+
718
+ expected_yticklabels = categories
719
+ result_yticklabels = [i.get_text() for i in colorbar.ax.get_ymajorticklabels()]
720
+ assert all(i == j for i, j in zip(result_yticklabels, expected_yticklabels))
721
+
722
+ @pytest.mark.parametrize("x, y", [("x", "y"), ("y", "x"), ("y", "y")])
723
+ def test_plot_scatter_with_categorical_data(self, x, y):
724
+ # after fixing GH 18755, should be able to plot categorical data
725
+ df = DataFrame({"x": [1, 2, 3, 4], "y": pd.Categorical(["a", "b", "a", "c"])})
726
+
727
+ _check_plot_works(df.plot.scatter, x=x, y=y)
728
+
729
+ def test_plot_scatter_with_c(self):
730
+ df = DataFrame(
731
+ np.random.randint(low=0, high=100, size=(6, 4)),
732
+ index=list(string.ascii_letters[:6]),
733
+ columns=["x", "y", "z", "four"],
734
+ )
735
+
736
+ axes = [df.plot.scatter(x="x", y="y", c="z"), df.plot.scatter(x=0, y=1, c=2)]
737
+ for ax in axes:
738
+ # default to Greys
739
+ assert ax.collections[0].cmap.name == "Greys"
740
+
741
+ assert ax.collections[0].colorbar.ax.get_ylabel() == "z"
742
+
743
+ cm = "cubehelix"
744
+ ax = df.plot.scatter(x="x", y="y", c="z", colormap=cm)
745
+ assert ax.collections[0].cmap.name == cm
746
+
747
+ # verify turning off colorbar works
748
+ ax = df.plot.scatter(x="x", y="y", c="z", colorbar=False)
749
+ assert ax.collections[0].colorbar is None
750
+
751
+ # verify that we can still plot a solid color
752
+ ax = df.plot.scatter(x=0, y=1, c="red")
753
+ assert ax.collections[0].colorbar is None
754
+ self._check_colors(ax.collections, facecolors=["r"])
755
+
756
+ # Ensure that we can pass an np.array straight through to matplotlib,
757
+ # this functionality was accidentally removed previously.
758
+ # See https://github.com/pandas-dev/pandas/issues/8852 for bug report
759
+ #
760
+ # Exercise colormap path and non-colormap path as they are independent
761
+ #
762
+ df = DataFrame({"A": [1, 2], "B": [3, 4]})
763
+ red_rgba = [1.0, 0.0, 0.0, 1.0]
764
+ green_rgba = [0.0, 1.0, 0.0, 1.0]
765
+ rgba_array = np.array([red_rgba, green_rgba])
766
+ ax = df.plot.scatter(x="A", y="B", c=rgba_array)
767
+ # expect the face colors of the points in the non-colormap path to be
768
+ # identical to the values we supplied, normally we'd be on shaky ground
769
+ # comparing floats for equality but here we expect them to be
770
+ # identical.
771
+ tm.assert_numpy_array_equal(ax.collections[0].get_facecolor(), rgba_array)
772
+ # we don't test the colors of the faces in this next plot because they
773
+ # are dependent on the spring colormap, which may change its colors
774
+ # later.
775
+ float_array = np.array([0.0, 1.0])
776
+ df.plot.scatter(x="A", y="B", c=float_array, cmap="spring")
777
+
778
+ def test_plot_scatter_with_s(self):
779
+ # this refers to GH 32904
780
+ df = DataFrame(np.random.random((10, 3)) * 100, columns=["a", "b", "c"])
781
+
782
+ ax = df.plot.scatter(x="a", y="b", s="c")
783
+ tm.assert_numpy_array_equal(df["c"].values, right=ax.collections[0].get_sizes())
784
+
785
+ def test_plot_scatter_with_norm(self):
786
+ # added while fixing GH 45809
787
+ import matplotlib as mpl
788
+
789
+ df = DataFrame(np.random.random((10, 3)) * 100, columns=["a", "b", "c"])
790
+ norm = mpl.colors.LogNorm()
791
+ ax = df.plot.scatter(x="a", y="b", c="c", norm=norm)
792
+ assert ax.collections[0].norm is norm
793
+
794
+ def test_plot_scatter_without_norm(self):
795
+ # added while fixing GH 45809
796
+ import matplotlib as mpl
797
+
798
+ df = DataFrame(np.random.random((10, 3)) * 100, columns=["a", "b", "c"])
799
+ ax = df.plot.scatter(x="a", y="b", c="c")
800
+ plot_norm = ax.collections[0].norm
801
+ color_min_max = (df.c.min(), df.c.max())
802
+ default_norm = mpl.colors.Normalize(*color_min_max)
803
+ for value in df.c:
804
+ assert plot_norm(value) == default_norm(value)
805
+
806
+ @pytest.mark.slow
807
+ def test_plot_bar(self):
808
+ df = DataFrame(
809
+ np.random.randn(6, 4),
810
+ index=list(string.ascii_letters[:6]),
811
+ columns=["one", "two", "three", "four"],
812
+ )
813
+
814
+ _check_plot_works(df.plot.bar)
815
+ _check_plot_works(df.plot.bar, legend=False)
816
+ _check_plot_works(df.plot.bar, default_axes=True, subplots=True)
817
+ _check_plot_works(df.plot.bar, stacked=True)
818
+
819
+ df = DataFrame(
820
+ np.random.randn(10, 15),
821
+ index=list(string.ascii_letters[:10]),
822
+ columns=range(15),
823
+ )
824
+ _check_plot_works(df.plot.bar)
825
+
826
+ df = DataFrame({"a": [0, 1], "b": [1, 0]})
827
+ ax = _check_plot_works(df.plot.bar)
828
+ self._check_ticks_props(ax, xrot=90)
829
+
830
+ ax = df.plot.bar(rot=35, fontsize=10)
831
+ self._check_ticks_props(ax, xrot=35, xlabelsize=10, ylabelsize=10)
832
+
833
+ ax = _check_plot_works(df.plot.barh)
834
+ self._check_ticks_props(ax, yrot=0)
835
+
836
+ ax = df.plot.barh(rot=55, fontsize=11)
837
+ self._check_ticks_props(ax, yrot=55, ylabelsize=11, xlabelsize=11)
838
+
839
+ def test_boxplot(self, hist_df):
840
+ df = hist_df
841
+ series = df["height"]
842
+ numeric_cols = df._get_numeric_data().columns
843
+ labels = [pprint_thing(c) for c in numeric_cols]
844
+
845
+ ax = _check_plot_works(df.plot.box)
846
+ self._check_text_labels(ax.get_xticklabels(), labels)
847
+ tm.assert_numpy_array_equal(
848
+ ax.xaxis.get_ticklocs(), np.arange(1, len(numeric_cols) + 1)
849
+ )
850
+ assert len(ax.lines) == 7 * len(numeric_cols)
851
+ tm.close()
852
+
853
+ axes = series.plot.box(rot=40)
854
+ self._check_ticks_props(axes, xrot=40, yrot=0)
855
+ tm.close()
856
+
857
+ ax = _check_plot_works(series.plot.box)
858
+
859
+ positions = np.array([1, 6, 7])
860
+ ax = df.plot.box(positions=positions)
861
+ numeric_cols = df._get_numeric_data().columns
862
+ labels = [pprint_thing(c) for c in numeric_cols]
863
+ self._check_text_labels(ax.get_xticklabels(), labels)
864
+ tm.assert_numpy_array_equal(ax.xaxis.get_ticklocs(), positions)
865
+ assert len(ax.lines) == 7 * len(numeric_cols)
866
+
867
+ def test_boxplot_vertical(self, hist_df):
868
+ df = hist_df
869
+ numeric_cols = df._get_numeric_data().columns
870
+ labels = [pprint_thing(c) for c in numeric_cols]
871
+
872
+ # if horizontal, yticklabels are rotated
873
+ ax = df.plot.box(rot=50, fontsize=8, vert=False)
874
+ self._check_ticks_props(ax, xrot=0, yrot=50, ylabelsize=8)
875
+ self._check_text_labels(ax.get_yticklabels(), labels)
876
+ assert len(ax.lines) == 7 * len(numeric_cols)
877
+
878
+ axes = _check_plot_works(
879
+ df.plot.box,
880
+ default_axes=True,
881
+ subplots=True,
882
+ vert=False,
883
+ logx=True,
884
+ )
885
+ self._check_axes_shape(axes, axes_num=3, layout=(1, 3))
886
+ self._check_ax_scales(axes, xaxis="log")
887
+ for ax, label in zip(axes, labels):
888
+ self._check_text_labels(ax.get_yticklabels(), [label])
889
+ assert len(ax.lines) == 7
890
+
891
+ positions = np.array([3, 2, 8])
892
+ ax = df.plot.box(positions=positions, vert=False)
893
+ self._check_text_labels(ax.get_yticklabels(), labels)
894
+ tm.assert_numpy_array_equal(ax.yaxis.get_ticklocs(), positions)
895
+ assert len(ax.lines) == 7 * len(numeric_cols)
896
+
897
+ def test_boxplot_return_type(self):
898
+ df = DataFrame(
899
+ np.random.randn(6, 4),
900
+ index=list(string.ascii_letters[:6]),
901
+ columns=["one", "two", "three", "four"],
902
+ )
903
+ msg = "return_type must be {None, 'axes', 'dict', 'both'}"
904
+ with pytest.raises(ValueError, match=msg):
905
+ df.plot.box(return_type="not_a_type")
906
+
907
+ result = df.plot.box(return_type="dict")
908
+ self._check_box_return_type(result, "dict")
909
+
910
+ result = df.plot.box(return_type="axes")
911
+ self._check_box_return_type(result, "axes")
912
+
913
+ result = df.plot.box() # default axes
914
+ self._check_box_return_type(result, "axes")
915
+
916
+ result = df.plot.box(return_type="both")
917
+ self._check_box_return_type(result, "both")
918
+
919
+ @td.skip_if_no_scipy
920
+ def test_kde_df(self):
921
+ df = DataFrame(np.random.randn(100, 4))
922
+ ax = _check_plot_works(df.plot, kind="kde")
923
+ expected = [pprint_thing(c) for c in df.columns]
924
+ self._check_legend_labels(ax, labels=expected)
925
+ self._check_ticks_props(ax, xrot=0)
926
+
927
+ ax = df.plot(kind="kde", rot=20, fontsize=5)
928
+ self._check_ticks_props(ax, xrot=20, xlabelsize=5, ylabelsize=5)
929
+
930
+ axes = _check_plot_works(
931
+ df.plot,
932
+ default_axes=True,
933
+ kind="kde",
934
+ subplots=True,
935
+ )
936
+ self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
937
+
938
+ axes = df.plot(kind="kde", logy=True, subplots=True)
939
+ self._check_ax_scales(axes, yaxis="log")
940
+
941
+ @td.skip_if_no_scipy
942
+ def test_kde_missing_vals(self):
943
+ df = DataFrame(np.random.uniform(size=(100, 4)))
944
+ df.loc[0, 0] = np.nan
945
+ _check_plot_works(df.plot, kind="kde")
946
+
947
+ def test_hist_df(self):
948
+ from matplotlib.patches import Rectangle
949
+
950
+ df = DataFrame(np.random.randn(100, 4))
951
+ series = df[0]
952
+
953
+ ax = _check_plot_works(df.plot.hist)
954
+ expected = [pprint_thing(c) for c in df.columns]
955
+ self._check_legend_labels(ax, labels=expected)
956
+
957
+ axes = _check_plot_works(
958
+ df.plot.hist,
959
+ default_axes=True,
960
+ subplots=True,
961
+ logy=True,
962
+ )
963
+ self._check_axes_shape(axes, axes_num=4, layout=(4, 1))
964
+ self._check_ax_scales(axes, yaxis="log")
965
+
966
+ axes = series.plot.hist(rot=40)
967
+ self._check_ticks_props(axes, xrot=40, yrot=0)
968
+ tm.close()
969
+
970
+ ax = series.plot.hist(cumulative=True, bins=4, density=True)
971
+ # height of last bin (index 5) must be 1.0
972
+ rects = [x for x in ax.get_children() if isinstance(x, Rectangle)]
973
+ tm.assert_almost_equal(rects[-1].get_height(), 1.0)
974
+ tm.close()
975
+
976
+ ax = series.plot.hist(cumulative=True, bins=4)
977
+ rects = [x for x in ax.get_children() if isinstance(x, Rectangle)]
978
+
979
+ tm.assert_almost_equal(rects[-2].get_height(), 100.0)
980
+ tm.close()
981
+
982
+ # if horizontal, yticklabels are rotated
983
+ axes = df.plot.hist(rot=50, fontsize=8, orientation="horizontal")
984
+ self._check_ticks_props(axes, xrot=0, yrot=50, ylabelsize=8)
985
+
986
+ @pytest.mark.parametrize(
987
+ "weights", [0.1 * np.ones(shape=(100,)), 0.1 * np.ones(shape=(100, 2))]
988
+ )
989
+ def test_hist_weights(self, weights):
990
+ # GH 33173
991
+ np.random.seed(0)
992
+ df = DataFrame(dict(zip(["A", "B"], np.random.randn(2, 100))))
993
+
994
+ ax1 = _check_plot_works(df.plot, kind="hist", weights=weights)
995
+ ax2 = _check_plot_works(df.plot, kind="hist")
996
+
997
+ patch_height_with_weights = [patch.get_height() for patch in ax1.patches]
998
+
999
+ # original heights with no weights, and we manually multiply with example
1000
+ # weights, so after multiplication, they should be almost same
1001
+ expected_patch_height = [0.1 * patch.get_height() for patch in ax2.patches]
1002
+
1003
+ tm.assert_almost_equal(patch_height_with_weights, expected_patch_height)
1004
+
1005
+ def _check_box_coord(
1006
+ self,
1007
+ patches,
1008
+ expected_y=None,
1009
+ expected_h=None,
1010
+ expected_x=None,
1011
+ expected_w=None,
1012
+ ):
1013
+ result_y = np.array([p.get_y() for p in patches])
1014
+ result_height = np.array([p.get_height() for p in patches])
1015
+ result_x = np.array([p.get_x() for p in patches])
1016
+ result_width = np.array([p.get_width() for p in patches])
1017
+ # dtype is depending on above values, no need to check
1018
+
1019
+ if expected_y is not None:
1020
+ tm.assert_numpy_array_equal(result_y, expected_y, check_dtype=False)
1021
+ if expected_h is not None:
1022
+ tm.assert_numpy_array_equal(result_height, expected_h, check_dtype=False)
1023
+ if expected_x is not None:
1024
+ tm.assert_numpy_array_equal(result_x, expected_x, check_dtype=False)
1025
+ if expected_w is not None:
1026
+ tm.assert_numpy_array_equal(result_width, expected_w, check_dtype=False)
1027
+
1028
+ def test_hist_df_coord(self):
1029
+ normal_df = DataFrame(
1030
+ {
1031
+ "A": np.repeat(np.array([1, 2, 3, 4, 5]), np.array([10, 9, 8, 7, 6])),
1032
+ "B": np.repeat(np.array([1, 2, 3, 4, 5]), np.array([8, 8, 8, 8, 8])),
1033
+ "C": np.repeat(np.array([1, 2, 3, 4, 5]), np.array([6, 7, 8, 9, 10])),
1034
+ },
1035
+ columns=["A", "B", "C"],
1036
+ )
1037
+
1038
+ nan_df = DataFrame(
1039
+ {
1040
+ "A": np.repeat(
1041
+ np.array([np.nan, 1, 2, 3, 4, 5]), np.array([3, 10, 9, 8, 7, 6])
1042
+ ),
1043
+ "B": np.repeat(
1044
+ np.array([1, np.nan, 2, 3, 4, 5]), np.array([8, 3, 8, 8, 8, 8])
1045
+ ),
1046
+ "C": np.repeat(
1047
+ np.array([1, 2, 3, np.nan, 4, 5]), np.array([6, 7, 8, 3, 9, 10])
1048
+ ),
1049
+ },
1050
+ columns=["A", "B", "C"],
1051
+ )
1052
+
1053
+ for df in [normal_df, nan_df]:
1054
+ ax = df.plot.hist(bins=5)
1055
+ self._check_box_coord(
1056
+ ax.patches[:5],
1057
+ expected_y=np.array([0, 0, 0, 0, 0]),
1058
+ expected_h=np.array([10, 9, 8, 7, 6]),
1059
+ )
1060
+ self._check_box_coord(
1061
+ ax.patches[5:10],
1062
+ expected_y=np.array([0, 0, 0, 0, 0]),
1063
+ expected_h=np.array([8, 8, 8, 8, 8]),
1064
+ )
1065
+ self._check_box_coord(
1066
+ ax.patches[10:],
1067
+ expected_y=np.array([0, 0, 0, 0, 0]),
1068
+ expected_h=np.array([6, 7, 8, 9, 10]),
1069
+ )
1070
+
1071
+ ax = df.plot.hist(bins=5, stacked=True)
1072
+ self._check_box_coord(
1073
+ ax.patches[:5],
1074
+ expected_y=np.array([0, 0, 0, 0, 0]),
1075
+ expected_h=np.array([10, 9, 8, 7, 6]),
1076
+ )
1077
+ self._check_box_coord(
1078
+ ax.patches[5:10],
1079
+ expected_y=np.array([10, 9, 8, 7, 6]),
1080
+ expected_h=np.array([8, 8, 8, 8, 8]),
1081
+ )
1082
+ self._check_box_coord(
1083
+ ax.patches[10:],
1084
+ expected_y=np.array([18, 17, 16, 15, 14]),
1085
+ expected_h=np.array([6, 7, 8, 9, 10]),
1086
+ )
1087
+
1088
+ axes = df.plot.hist(bins=5, stacked=True, subplots=True)
1089
+ self._check_box_coord(
1090
+ axes[0].patches,
1091
+ expected_y=np.array([0, 0, 0, 0, 0]),
1092
+ expected_h=np.array([10, 9, 8, 7, 6]),
1093
+ )
1094
+ self._check_box_coord(
1095
+ axes[1].patches,
1096
+ expected_y=np.array([0, 0, 0, 0, 0]),
1097
+ expected_h=np.array([8, 8, 8, 8, 8]),
1098
+ )
1099
+ self._check_box_coord(
1100
+ axes[2].patches,
1101
+ expected_y=np.array([0, 0, 0, 0, 0]),
1102
+ expected_h=np.array([6, 7, 8, 9, 10]),
1103
+ )
1104
+
1105
+ # horizontal
1106
+ ax = df.plot.hist(bins=5, orientation="horizontal")
1107
+ self._check_box_coord(
1108
+ ax.patches[:5],
1109
+ expected_x=np.array([0, 0, 0, 0, 0]),
1110
+ expected_w=np.array([10, 9, 8, 7, 6]),
1111
+ )
1112
+ self._check_box_coord(
1113
+ ax.patches[5:10],
1114
+ expected_x=np.array([0, 0, 0, 0, 0]),
1115
+ expected_w=np.array([8, 8, 8, 8, 8]),
1116
+ )
1117
+ self._check_box_coord(
1118
+ ax.patches[10:],
1119
+ expected_x=np.array([0, 0, 0, 0, 0]),
1120
+ expected_w=np.array([6, 7, 8, 9, 10]),
1121
+ )
1122
+
1123
+ ax = df.plot.hist(bins=5, stacked=True, orientation="horizontal")
1124
+ self._check_box_coord(
1125
+ ax.patches[:5],
1126
+ expected_x=np.array([0, 0, 0, 0, 0]),
1127
+ expected_w=np.array([10, 9, 8, 7, 6]),
1128
+ )
1129
+ self._check_box_coord(
1130
+ ax.patches[5:10],
1131
+ expected_x=np.array([10, 9, 8, 7, 6]),
1132
+ expected_w=np.array([8, 8, 8, 8, 8]),
1133
+ )
1134
+ self._check_box_coord(
1135
+ ax.patches[10:],
1136
+ expected_x=np.array([18, 17, 16, 15, 14]),
1137
+ expected_w=np.array([6, 7, 8, 9, 10]),
1138
+ )
1139
+
1140
+ axes = df.plot.hist(
1141
+ bins=5, stacked=True, subplots=True, orientation="horizontal"
1142
+ )
1143
+ self._check_box_coord(
1144
+ axes[0].patches,
1145
+ expected_x=np.array([0, 0, 0, 0, 0]),
1146
+ expected_w=np.array([10, 9, 8, 7, 6]),
1147
+ )
1148
+ self._check_box_coord(
1149
+ axes[1].patches,
1150
+ expected_x=np.array([0, 0, 0, 0, 0]),
1151
+ expected_w=np.array([8, 8, 8, 8, 8]),
1152
+ )
1153
+ self._check_box_coord(
1154
+ axes[2].patches,
1155
+ expected_x=np.array([0, 0, 0, 0, 0]),
1156
+ expected_w=np.array([6, 7, 8, 9, 10]),
1157
+ )
1158
+
1159
+ def test_plot_int_columns(self):
1160
+ df = DataFrame(np.random.randn(100, 4)).cumsum()
1161
+ _check_plot_works(df.plot, legend=True)
1162
+
1163
+ def test_style_by_column(self):
1164
+ import matplotlib.pyplot as plt
1165
+
1166
+ fig = plt.gcf()
1167
+
1168
+ df = DataFrame(np.random.randn(100, 3))
1169
+ for markers in [
1170
+ {0: "^", 1: "+", 2: "o"},
1171
+ {0: "^", 1: "+"},
1172
+ ["^", "+", "o"],
1173
+ ["^", "+"],
1174
+ ]:
1175
+ fig.clf()
1176
+ fig.add_subplot(111)
1177
+ ax = df.plot(style=markers)
1178
+ for idx, line in enumerate(ax.get_lines()[: len(markers)]):
1179
+ assert line.get_marker() == markers[idx]
1180
+
1181
+ def test_line_label_none(self):
1182
+ s = Series([1, 2])
1183
+ ax = s.plot()
1184
+ assert ax.get_legend() is None
1185
+
1186
+ ax = s.plot(legend=True)
1187
+ assert ax.get_legend().get_texts()[0].get_text() == ""
1188
+
1189
+ @pytest.mark.parametrize(
1190
+ "props, expected",
1191
+ [
1192
+ ("boxprops", "boxes"),
1193
+ ("whiskerprops", "whiskers"),
1194
+ ("capprops", "caps"),
1195
+ ("medianprops", "medians"),
1196
+ ],
1197
+ )
1198
+ def test_specified_props_kwd_plot_box(self, props, expected):
1199
+ # GH 30346
1200
+ df = DataFrame({k: np.random.random(100) for k in "ABC"})
1201
+ kwd = {props: {"color": "C1"}}
1202
+ result = df.plot.box(return_type="dict", **kwd)
1203
+
1204
+ assert result[expected][0].get_color() == "C1"
1205
+
1206
+ def test_unordered_ts(self):
1207
+ df = DataFrame(
1208
+ np.array([3.0, 2.0, 1.0]),
1209
+ index=[date(2012, 10, 1), date(2012, 9, 1), date(2012, 8, 1)],
1210
+ columns=["test"],
1211
+ )
1212
+ ax = df.plot()
1213
+ xticks = ax.lines[0].get_xdata()
1214
+ assert xticks[0] < xticks[1]
1215
+ ydata = ax.lines[0].get_ydata()
1216
+ tm.assert_numpy_array_equal(ydata, np.array([1.0, 2.0, 3.0]))
1217
+
1218
+ @td.skip_if_no_scipy
1219
+ def test_kind_both_ways(self):
1220
+ df = DataFrame({"x": [1, 2, 3]})
1221
+ for kind in plotting.PlotAccessor._common_kinds:
1222
+ df.plot(kind=kind)
1223
+ getattr(df.plot, kind)()
1224
+ for kind in ["scatter", "hexbin"]:
1225
+ df.plot("x", "x", kind=kind)
1226
+ getattr(df.plot, kind)("x", "x")
1227
+
1228
+ def test_all_invalid_plot_data(self):
1229
+ df = DataFrame(list("abcd"))
1230
+ for kind in plotting.PlotAccessor._common_kinds:
1231
+ msg = "no numeric data to plot"
1232
+ with pytest.raises(TypeError, match=msg):
1233
+ df.plot(kind=kind)
1234
+
1235
+ def test_partially_invalid_plot_data(self):
1236
+ df = DataFrame(np.random.RandomState(42).randn(10, 2), dtype=object)
1237
+ df[np.random.rand(df.shape[0]) > 0.5] = "a"
1238
+ for kind in plotting.PlotAccessor._common_kinds:
1239
+ msg = "no numeric data to plot"
1240
+ with pytest.raises(TypeError, match=msg):
1241
+ df.plot(kind=kind)
1242
+
1243
+ # area plot doesn't support positive/negative mixed data
1244
+ df = DataFrame(np.random.RandomState(42).rand(10, 2), dtype=object)
1245
+ df[np.random.rand(df.shape[0]) > 0.5] = "a"
1246
+ with pytest.raises(TypeError, match="no numeric data to plot"):
1247
+ df.plot(kind="area")
1248
+
1249
+ def test_invalid_kind(self):
1250
+ df = DataFrame(np.random.randn(10, 2))
1251
+ msg = "invalid_plot_kind is not a valid plot kind"
1252
+ with pytest.raises(ValueError, match=msg):
1253
+ df.plot(kind="invalid_plot_kind")
1254
+
1255
+ @pytest.mark.parametrize(
1256
+ "x,y,lbl",
1257
+ [
1258
+ (["B", "C"], "A", "a"),
1259
+ (["A"], ["B", "C"], ["b", "c"]),
1260
+ ],
1261
+ )
1262
+ def test_invalid_xy_args(self, x, y, lbl):
1263
+ # GH 18671, 19699 allows y to be list-like but not x
1264
+ df = DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]})
1265
+ with pytest.raises(ValueError, match="x must be a label or position"):
1266
+ df.plot(x=x, y=y, label=lbl)
1267
+
1268
+ def test_bad_label(self):
1269
+ df = DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]})
1270
+ msg = "label should be list-like and same length as y"
1271
+ with pytest.raises(ValueError, match=msg):
1272
+ df.plot(x="A", y=["B", "C"], label="bad_label")
1273
+
1274
+ @pytest.mark.parametrize("x,y", [("A", "B"), (["A"], "B")])
1275
+ def test_invalid_xy_args_dup_cols(self, x, y):
1276
+ # GH 18671, 19699 allows y to be list-like but not x
1277
+ df = DataFrame([[1, 3, 5], [2, 4, 6]], columns=list("AAB"))
1278
+ with pytest.raises(ValueError, match="x must be a label or position"):
1279
+ df.plot(x=x, y=y)
1280
+
1281
+ @pytest.mark.parametrize(
1282
+ "x,y,lbl,colors",
1283
+ [
1284
+ ("A", ["B"], ["b"], ["red"]),
1285
+ ("A", ["B", "C"], ["b", "c"], ["red", "blue"]),
1286
+ (0, [1, 2], ["bokeh", "cython"], ["green", "yellow"]),
1287
+ ],
1288
+ )
1289
+ def test_y_listlike(self, x, y, lbl, colors):
1290
+ # GH 19699: tests list-like y and verifies lbls & colors
1291
+ df = DataFrame({"A": [1, 2], "B": [3, 4], "C": [5, 6]})
1292
+ _check_plot_works(df.plot, x="A", y=y, label=lbl)
1293
+
1294
+ ax = df.plot(x=x, y=y, label=lbl, color=colors)
1295
+ assert len(ax.lines) == len(y)
1296
+ self._check_colors(ax.get_lines(), linecolors=colors)
1297
+
1298
+ @pytest.mark.parametrize("x,y,colnames", [(0, 1, ["A", "B"]), (1, 0, [0, 1])])
1299
+ def test_xy_args_integer(self, x, y, colnames):
1300
+ # GH 20056: tests integer args for xy and checks col names
1301
+ df = DataFrame({"A": [1, 2], "B": [3, 4]})
1302
+ df.columns = colnames
1303
+ _check_plot_works(df.plot, x=x, y=y)
1304
+
1305
+ def test_hexbin_basic(self):
1306
+ df = DataFrame(
1307
+ {
1308
+ "A": np.random.uniform(size=20),
1309
+ "B": np.random.uniform(size=20),
1310
+ "C": np.arange(20) + np.random.uniform(size=20),
1311
+ }
1312
+ )
1313
+
1314
+ ax = df.plot.hexbin(x="A", y="B", gridsize=10)
1315
+ # TODO: need better way to test. This just does existence.
1316
+ assert len(ax.collections) == 1
1317
+
1318
+ # GH 6951
1319
+ axes = df.plot.hexbin(x="A", y="B", subplots=True)
1320
+ # hexbin should have 2 axes in the figure, 1 for plotting and another
1321
+ # is colorbar
1322
+ assert len(axes[0].figure.axes) == 2
1323
+ # return value is single axes
1324
+ self._check_axes_shape(axes, axes_num=1, layout=(1, 1))
1325
+
1326
+ def test_hexbin_with_c(self):
1327
+ df = DataFrame(
1328
+ {
1329
+ "A": np.random.uniform(size=20),
1330
+ "B": np.random.uniform(size=20),
1331
+ "C": np.arange(20) + np.random.uniform(size=20),
1332
+ }
1333
+ )
1334
+
1335
+ ax = df.plot.hexbin(x="A", y="B", C="C")
1336
+ assert len(ax.collections) == 1
1337
+
1338
+ ax = df.plot.hexbin(x="A", y="B", C="C", reduce_C_function=np.std)
1339
+ assert len(ax.collections) == 1
1340
+
1341
+ @pytest.mark.parametrize(
1342
+ "kwargs, expected",
1343
+ [
1344
+ ({}, "BuGn"), # default cmap
1345
+ ({"colormap": "cubehelix"}, "cubehelix"),
1346
+ ({"cmap": "YlGn"}, "YlGn"),
1347
+ ],
1348
+ )
1349
+ def test_hexbin_cmap(self, kwargs, expected):
1350
+ df = DataFrame(
1351
+ {
1352
+ "A": np.random.uniform(size=20),
1353
+ "B": np.random.uniform(size=20),
1354
+ "C": np.arange(20) + np.random.uniform(size=20),
1355
+ }
1356
+ )
1357
+ ax = df.plot.hexbin(x="A", y="B", **kwargs)
1358
+ assert ax.collections[0].cmap.name == expected
1359
+
1360
+ def test_pie_df(self):
1361
+ df = DataFrame(
1362
+ np.random.rand(5, 3),
1363
+ columns=["X", "Y", "Z"],
1364
+ index=["a", "b", "c", "d", "e"],
1365
+ )
1366
+ msg = "pie requires either y column or 'subplots=True'"
1367
+ with pytest.raises(ValueError, match=msg):
1368
+ df.plot.pie()
1369
+
1370
+ ax = _check_plot_works(df.plot.pie, y="Y")
1371
+ self._check_text_labels(ax.texts, df.index)
1372
+
1373
+ ax = _check_plot_works(df.plot.pie, y=2)
1374
+ self._check_text_labels(ax.texts, df.index)
1375
+
1376
+ axes = _check_plot_works(
1377
+ df.plot.pie,
1378
+ default_axes=True,
1379
+ subplots=True,
1380
+ )
1381
+ assert len(axes) == len(df.columns)
1382
+ for ax in axes:
1383
+ self._check_text_labels(ax.texts, df.index)
1384
+ for ax, ylabel in zip(axes, df.columns):
1385
+ assert ax.get_ylabel() == ylabel
1386
+
1387
+ labels = ["A", "B", "C", "D", "E"]
1388
+ color_args = ["r", "g", "b", "c", "m"]
1389
+ axes = _check_plot_works(
1390
+ df.plot.pie,
1391
+ default_axes=True,
1392
+ subplots=True,
1393
+ labels=labels,
1394
+ colors=color_args,
1395
+ )
1396
+ assert len(axes) == len(df.columns)
1397
+
1398
+ for ax in axes:
1399
+ self._check_text_labels(ax.texts, labels)
1400
+ self._check_colors(ax.patches, facecolors=color_args)
1401
+
1402
+ def test_pie_df_nan(self):
1403
+ import matplotlib as mpl
1404
+
1405
+ df = DataFrame(np.random.rand(4, 4))
1406
+ for i in range(4):
1407
+ df.iloc[i, i] = np.nan
1408
+ fig, axes = self.plt.subplots(ncols=4)
1409
+
1410
+ # GH 37668
1411
+ kwargs = {}
1412
+ if mpl.__version__ >= "3.3":
1413
+ kwargs = {"normalize": True}
1414
+
1415
+ with tm.assert_produces_warning(None):
1416
+ df.plot.pie(subplots=True, ax=axes, legend=True, **kwargs)
1417
+
1418
+ base_expected = ["0", "1", "2", "3"]
1419
+ for i, ax in enumerate(axes):
1420
+ expected = list(base_expected) # force copy
1421
+ expected[i] = ""
1422
+ result = [x.get_text() for x in ax.texts]
1423
+ assert result == expected
1424
+
1425
+ # legend labels
1426
+ # NaN's not included in legend with subplots
1427
+ # see https://github.com/pandas-dev/pandas/issues/8390
1428
+ result_labels = [x.get_text() for x in ax.get_legend().get_texts()]
1429
+ expected_labels = base_expected[:i] + base_expected[i + 1 :]
1430
+ assert result_labels == expected_labels
1431
+
1432
+ @pytest.mark.slow
1433
+ def test_errorbar_plot(self):
1434
+ d = {"x": np.arange(12), "y": np.arange(12, 0, -1)}
1435
+ df = DataFrame(d)
1436
+ d_err = {"x": np.ones(12) * 0.2, "y": np.ones(12) * 0.4}
1437
+ df_err = DataFrame(d_err)
1438
+
1439
+ # check line plots
1440
+ ax = _check_plot_works(df.plot, yerr=df_err, logy=True)
1441
+ self._check_has_errorbars(ax, xerr=0, yerr=2)
1442
+
1443
+ ax = _check_plot_works(df.plot, yerr=df_err, logx=True, logy=True)
1444
+ self._check_has_errorbars(ax, xerr=0, yerr=2)
1445
+
1446
+ ax = _check_plot_works(df.plot, yerr=df_err, loglog=True)
1447
+ self._check_has_errorbars(ax, xerr=0, yerr=2)
1448
+
1449
+ ax = _check_plot_works(
1450
+ (df + 1).plot, yerr=df_err, xerr=df_err, kind="bar", log=True
1451
+ )
1452
+ self._check_has_errorbars(ax, xerr=2, yerr=2)
1453
+
1454
+ # yerr is raw error values
1455
+ ax = _check_plot_works(df["y"].plot, yerr=np.ones(12) * 0.4)
1456
+ self._check_has_errorbars(ax, xerr=0, yerr=1)
1457
+
1458
+ ax = _check_plot_works(df.plot, yerr=np.ones((2, 12)) * 0.4)
1459
+ self._check_has_errorbars(ax, xerr=0, yerr=2)
1460
+
1461
+ # yerr is column name
1462
+ for yerr in ["yerr", "誤差"]:
1463
+ s_df = df.copy()
1464
+ s_df[yerr] = np.ones(12) * 0.2
1465
+
1466
+ ax = _check_plot_works(s_df.plot, yerr=yerr)
1467
+ self._check_has_errorbars(ax, xerr=0, yerr=2)
1468
+
1469
+ ax = _check_plot_works(s_df.plot, y="y", x="x", yerr=yerr)
1470
+ self._check_has_errorbars(ax, xerr=0, yerr=1)
1471
+
1472
+ with tm.external_error_raised(ValueError):
1473
+ df.plot(yerr=np.random.randn(11))
1474
+
1475
+ df_err = DataFrame({"x": ["zzz"] * 12, "y": ["zzz"] * 12})
1476
+ with tm.external_error_raised(TypeError):
1477
+ df.plot(yerr=df_err)
1478
+
1479
+ @pytest.mark.slow
1480
+ @pytest.mark.parametrize("kind", ["line", "bar", "barh"])
1481
+ def test_errorbar_plot_different_kinds(self, kind):
1482
+ d = {"x": np.arange(12), "y": np.arange(12, 0, -1)}
1483
+ df = DataFrame(d)
1484
+ d_err = {"x": np.ones(12) * 0.2, "y": np.ones(12) * 0.4}
1485
+ df_err = DataFrame(d_err)
1486
+
1487
+ ax = _check_plot_works(df.plot, yerr=df_err["x"], kind=kind)
1488
+ self._check_has_errorbars(ax, xerr=0, yerr=2)
1489
+
1490
+ ax = _check_plot_works(df.plot, yerr=d_err, kind=kind)
1491
+ self._check_has_errorbars(ax, xerr=0, yerr=2)
1492
+
1493
+ ax = _check_plot_works(df.plot, yerr=df_err, xerr=df_err, kind=kind)
1494
+ self._check_has_errorbars(ax, xerr=2, yerr=2)
1495
+
1496
+ ax = _check_plot_works(df.plot, yerr=df_err["x"], xerr=df_err["x"], kind=kind)
1497
+ self._check_has_errorbars(ax, xerr=2, yerr=2)
1498
+
1499
+ ax = _check_plot_works(df.plot, xerr=0.2, yerr=0.2, kind=kind)
1500
+ self._check_has_errorbars(ax, xerr=2, yerr=2)
1501
+
1502
+ axes = _check_plot_works(
1503
+ df.plot,
1504
+ default_axes=True,
1505
+ yerr=df_err,
1506
+ xerr=df_err,
1507
+ subplots=True,
1508
+ kind=kind,
1509
+ )
1510
+ self._check_has_errorbars(axes, xerr=1, yerr=1)
1511
+
1512
+ @pytest.mark.xfail(reason="Iterator is consumed", raises=ValueError)
1513
+ def test_errorbar_plot_iterator(self):
1514
+ with warnings.catch_warnings():
1515
+ d = {"x": np.arange(12), "y": np.arange(12, 0, -1)}
1516
+ df = DataFrame(d)
1517
+
1518
+ # yerr is iterator
1519
+ ax = _check_plot_works(df.plot, yerr=itertools.repeat(0.1, len(df)))
1520
+ self._check_has_errorbars(ax, xerr=0, yerr=2)
1521
+
1522
+ def test_errorbar_with_integer_column_names(self):
1523
+ # test with integer column names
1524
+ df = DataFrame(np.abs(np.random.randn(10, 2)))
1525
+ df_err = DataFrame(np.abs(np.random.randn(10, 2)))
1526
+ ax = _check_plot_works(df.plot, yerr=df_err)
1527
+ self._check_has_errorbars(ax, xerr=0, yerr=2)
1528
+ ax = _check_plot_works(df.plot, y=0, yerr=1)
1529
+ self._check_has_errorbars(ax, xerr=0, yerr=1)
1530
+
1531
+ @pytest.mark.slow
1532
+ def test_errorbar_with_partial_columns(self):
1533
+ df = DataFrame(np.abs(np.random.randn(10, 3)))
1534
+ df_err = DataFrame(np.abs(np.random.randn(10, 2)), columns=[0, 2])
1535
+ kinds = ["line", "bar"]
1536
+ for kind in kinds:
1537
+ ax = _check_plot_works(df.plot, yerr=df_err, kind=kind)
1538
+ self._check_has_errorbars(ax, xerr=0, yerr=2)
1539
+
1540
+ ix = date_range("1/1/2000", periods=10, freq="M")
1541
+ df.set_index(ix, inplace=True)
1542
+ df_err.set_index(ix, inplace=True)
1543
+ ax = _check_plot_works(df.plot, yerr=df_err, kind="line")
1544
+ self._check_has_errorbars(ax, xerr=0, yerr=2)
1545
+
1546
+ d = {"x": np.arange(12), "y": np.arange(12, 0, -1)}
1547
+ df = DataFrame(d)
1548
+ d_err = {"x": np.ones(12) * 0.2, "z": np.ones(12) * 0.4}
1549
+ df_err = DataFrame(d_err)
1550
+ for err in [d_err, df_err]:
1551
+ ax = _check_plot_works(df.plot, yerr=err)
1552
+ self._check_has_errorbars(ax, xerr=0, yerr=1)
1553
+
1554
+ @pytest.mark.parametrize("kind", ["line", "bar", "barh"])
1555
+ def test_errorbar_timeseries(self, kind):
1556
+ d = {"x": np.arange(12), "y": np.arange(12, 0, -1)}
1557
+ d_err = {"x": np.ones(12) * 0.2, "y": np.ones(12) * 0.4}
1558
+
1559
+ # check time-series plots
1560
+ ix = date_range("1/1/2000", "1/1/2001", freq="M")
1561
+ tdf = DataFrame(d, index=ix)
1562
+ tdf_err = DataFrame(d_err, index=ix)
1563
+
1564
+ ax = _check_plot_works(tdf.plot, yerr=tdf_err, kind=kind)
1565
+ self._check_has_errorbars(ax, xerr=0, yerr=2)
1566
+
1567
+ ax = _check_plot_works(tdf.plot, yerr=d_err, kind=kind)
1568
+ self._check_has_errorbars(ax, xerr=0, yerr=2)
1569
+
1570
+ ax = _check_plot_works(tdf.plot, y="y", yerr=tdf_err["x"], kind=kind)
1571
+ self._check_has_errorbars(ax, xerr=0, yerr=1)
1572
+
1573
+ ax = _check_plot_works(tdf.plot, y="y", yerr="x", kind=kind)
1574
+ self._check_has_errorbars(ax, xerr=0, yerr=1)
1575
+
1576
+ ax = _check_plot_works(tdf.plot, yerr=tdf_err, kind=kind)
1577
+ self._check_has_errorbars(ax, xerr=0, yerr=2)
1578
+
1579
+ axes = _check_plot_works(
1580
+ tdf.plot,
1581
+ default_axes=True,
1582
+ kind=kind,
1583
+ yerr=tdf_err,
1584
+ subplots=True,
1585
+ )
1586
+ self._check_has_errorbars(axes, xerr=0, yerr=1)
1587
+
1588
+ def test_errorbar_asymmetrical(self):
1589
+ np.random.seed(0)
1590
+ err = np.random.rand(3, 2, 5)
1591
+
1592
+ # each column is [0, 1, 2, 3, 4], [3, 4, 5, 6, 7]...
1593
+ df = DataFrame(np.arange(15).reshape(3, 5)).T
1594
+
1595
+ ax = df.plot(yerr=err, xerr=err / 2)
1596
+
1597
+ yerr_0_0 = ax.collections[1].get_paths()[0].vertices[:, 1]
1598
+ expected_0_0 = err[0, :, 0] * np.array([-1, 1])
1599
+ tm.assert_almost_equal(yerr_0_0, expected_0_0)
1600
+
1601
+ msg = re.escape(
1602
+ "Asymmetrical error bars should be provided with the shape (3, 2, 5)"
1603
+ )
1604
+ with pytest.raises(ValueError, match=msg):
1605
+ df.plot(yerr=err.T)
1606
+
1607
+ tm.close()
1608
+
1609
+ def test_table(self):
1610
+ df = DataFrame(np.random.rand(10, 3), index=list(string.ascii_letters[:10]))
1611
+ _check_plot_works(df.plot, table=True)
1612
+ _check_plot_works(df.plot, table=df)
1613
+
1614
+ # GH 35945 UserWarning
1615
+ with tm.assert_produces_warning(None):
1616
+ ax = df.plot()
1617
+ assert len(ax.tables) == 0
1618
+ plotting.table(ax, df.T)
1619
+ assert len(ax.tables) == 1
1620
+
1621
+ def test_errorbar_scatter(self):
1622
+ df = DataFrame(
1623
+ np.abs(np.random.randn(5, 2)), index=range(5), columns=["x", "y"]
1624
+ )
1625
+ df_err = DataFrame(
1626
+ np.abs(np.random.randn(5, 2)) / 5, index=range(5), columns=["x", "y"]
1627
+ )
1628
+
1629
+ ax = _check_plot_works(df.plot.scatter, x="x", y="y")
1630
+ self._check_has_errorbars(ax, xerr=0, yerr=0)
1631
+ ax = _check_plot_works(df.plot.scatter, x="x", y="y", xerr=df_err)
1632
+ self._check_has_errorbars(ax, xerr=1, yerr=0)
1633
+
1634
+ ax = _check_plot_works(df.plot.scatter, x="x", y="y", yerr=df_err)
1635
+ self._check_has_errorbars(ax, xerr=0, yerr=1)
1636
+ ax = _check_plot_works(df.plot.scatter, x="x", y="y", xerr=df_err, yerr=df_err)
1637
+ self._check_has_errorbars(ax, xerr=1, yerr=1)
1638
+
1639
+ def _check_errorbar_color(containers, expected, has_err="has_xerr"):
1640
+ lines = []
1641
+ errs = [c.lines for c in ax.containers if getattr(c, has_err, False)][0]
1642
+ for el in errs:
1643
+ if is_list_like(el):
1644
+ lines.extend(el)
1645
+ else:
1646
+ lines.append(el)
1647
+ err_lines = [x for x in lines if x in ax.collections]
1648
+ self._check_colors(
1649
+ err_lines, linecolors=np.array([expected] * len(err_lines))
1650
+ )
1651
+
1652
+ # GH 8081
1653
+ df = DataFrame(
1654
+ np.abs(np.random.randn(10, 5)), columns=["a", "b", "c", "d", "e"]
1655
+ )
1656
+ ax = df.plot.scatter(x="a", y="b", xerr="d", yerr="e", c="red")
1657
+ self._check_has_errorbars(ax, xerr=1, yerr=1)
1658
+ _check_errorbar_color(ax.containers, "red", has_err="has_xerr")
1659
+ _check_errorbar_color(ax.containers, "red", has_err="has_yerr")
1660
+
1661
+ ax = df.plot.scatter(x="a", y="b", yerr="e", color="green")
1662
+ self._check_has_errorbars(ax, xerr=0, yerr=1)
1663
+ _check_errorbar_color(ax.containers, "green", has_err="has_yerr")
1664
+
1665
+ def test_scatter_unknown_colormap(self):
1666
+ # GH#48726
1667
+ df = DataFrame({"a": [1, 2, 3], "b": 4})
1668
+ with pytest.raises((ValueError, KeyError), match="'unknown' is not a"):
1669
+ df.plot(x="a", y="b", colormap="unknown", kind="scatter")
1670
+
1671
+ def test_sharex_and_ax(self):
1672
+ # https://github.com/pandas-dev/pandas/issues/9737 using gridspec,
1673
+ # the axis in fig.get_axis() are sorted differently than pandas
1674
+ # expected them, so make sure that only the right ones are removed
1675
+ import matplotlib.pyplot as plt
1676
+
1677
+ plt.close("all")
1678
+ gs, axes = _generate_4_axes_via_gridspec()
1679
+
1680
+ df = DataFrame(
1681
+ {
1682
+ "a": [1, 2, 3, 4, 5, 6],
1683
+ "b": [1, 2, 3, 4, 5, 6],
1684
+ "c": [1, 2, 3, 4, 5, 6],
1685
+ "d": [1, 2, 3, 4, 5, 6],
1686
+ }
1687
+ )
1688
+
1689
+ def _check(axes):
1690
+ for ax in axes:
1691
+ assert len(ax.lines) == 1
1692
+ self._check_visible(ax.get_yticklabels(), visible=True)
1693
+ for ax in [axes[0], axes[2]]:
1694
+ self._check_visible(ax.get_xticklabels(), visible=False)
1695
+ self._check_visible(ax.get_xticklabels(minor=True), visible=False)
1696
+ for ax in [axes[1], axes[3]]:
1697
+ self._check_visible(ax.get_xticklabels(), visible=True)
1698
+ self._check_visible(ax.get_xticklabels(minor=True), visible=True)
1699
+
1700
+ for ax in axes:
1701
+ df.plot(x="a", y="b", title="title", ax=ax, sharex=True)
1702
+ gs.tight_layout(plt.gcf())
1703
+ _check(axes)
1704
+ tm.close()
1705
+
1706
+ gs, axes = _generate_4_axes_via_gridspec()
1707
+ with tm.assert_produces_warning(UserWarning):
1708
+ axes = df.plot(subplots=True, ax=axes, sharex=True)
1709
+ _check(axes)
1710
+ tm.close()
1711
+
1712
+ gs, axes = _generate_4_axes_via_gridspec()
1713
+ # without sharex, no labels should be touched!
1714
+ for ax in axes:
1715
+ df.plot(x="a", y="b", title="title", ax=ax)
1716
+
1717
+ gs.tight_layout(plt.gcf())
1718
+ for ax in axes:
1719
+ assert len(ax.lines) == 1
1720
+ self._check_visible(ax.get_yticklabels(), visible=True)
1721
+ self._check_visible(ax.get_xticklabels(), visible=True)
1722
+ self._check_visible(ax.get_xticklabels(minor=True), visible=True)
1723
+ tm.close()
1724
+
1725
+ def test_sharey_and_ax(self):
1726
+ # https://github.com/pandas-dev/pandas/issues/9737 using gridspec,
1727
+ # the axis in fig.get_axis() are sorted differently than pandas
1728
+ # expected them, so make sure that only the right ones are removed
1729
+ import matplotlib.pyplot as plt
1730
+
1731
+ gs, axes = _generate_4_axes_via_gridspec()
1732
+
1733
+ df = DataFrame(
1734
+ {
1735
+ "a": [1, 2, 3, 4, 5, 6],
1736
+ "b": [1, 2, 3, 4, 5, 6],
1737
+ "c": [1, 2, 3, 4, 5, 6],
1738
+ "d": [1, 2, 3, 4, 5, 6],
1739
+ }
1740
+ )
1741
+
1742
+ def _check(axes):
1743
+ for ax in axes:
1744
+ assert len(ax.lines) == 1
1745
+ self._check_visible(ax.get_xticklabels(), visible=True)
1746
+ self._check_visible(ax.get_xticklabels(minor=True), visible=True)
1747
+ for ax in [axes[0], axes[1]]:
1748
+ self._check_visible(ax.get_yticklabels(), visible=True)
1749
+ for ax in [axes[2], axes[3]]:
1750
+ self._check_visible(ax.get_yticklabels(), visible=False)
1751
+
1752
+ for ax in axes:
1753
+ df.plot(x="a", y="b", title="title", ax=ax, sharey=True)
1754
+ gs.tight_layout(plt.gcf())
1755
+ _check(axes)
1756
+ tm.close()
1757
+
1758
+ gs, axes = _generate_4_axes_via_gridspec()
1759
+ with tm.assert_produces_warning(UserWarning):
1760
+ axes = df.plot(subplots=True, ax=axes, sharey=True)
1761
+
1762
+ gs.tight_layout(plt.gcf())
1763
+ _check(axes)
1764
+ tm.close()
1765
+
1766
+ gs, axes = _generate_4_axes_via_gridspec()
1767
+ # without sharex, no labels should be touched!
1768
+ for ax in axes:
1769
+ df.plot(x="a", y="b", title="title", ax=ax)
1770
+
1771
+ gs.tight_layout(plt.gcf())
1772
+ for ax in axes:
1773
+ assert len(ax.lines) == 1
1774
+ self._check_visible(ax.get_yticklabels(), visible=True)
1775
+ self._check_visible(ax.get_xticklabels(), visible=True)
1776
+ self._check_visible(ax.get_xticklabels(minor=True), visible=True)
1777
+
1778
+ @td.skip_if_no_scipy
1779
+ def test_memory_leak(self):
1780
+ """Check that every plot type gets properly collected."""
1781
+ results = {}
1782
+ for kind in plotting.PlotAccessor._all_kinds:
1783
+ args = {}
1784
+ if kind in ["hexbin", "scatter", "pie"]:
1785
+ df = DataFrame(
1786
+ {
1787
+ "A": np.random.uniform(size=20),
1788
+ "B": np.random.uniform(size=20),
1789
+ "C": np.arange(20) + np.random.uniform(size=20),
1790
+ }
1791
+ )
1792
+ args = {"x": "A", "y": "B"}
1793
+ elif kind == "area":
1794
+ df = tm.makeTimeDataFrame().abs()
1795
+ else:
1796
+ df = tm.makeTimeDataFrame()
1797
+
1798
+ # Use a weakref so we can see if the object gets collected without
1799
+ # also preventing it from being collected
1800
+ results[kind] = weakref.proxy(df.plot(kind=kind, **args))
1801
+
1802
+ # have matplotlib delete all the figures
1803
+ tm.close()
1804
+ # force a garbage collection
1805
+ gc.collect()
1806
+ msg = "weakly-referenced object no longer exists"
1807
+ for result_value in results.values():
1808
+ # check that every plot was collected
1809
+ with pytest.raises(ReferenceError, match=msg):
1810
+ # need to actually access something to get an error
1811
+ result_value.lines
1812
+
1813
+ def test_df_gridspec_patterns(self):
1814
+ # GH 10819
1815
+ from matplotlib import gridspec
1816
+ import matplotlib.pyplot as plt
1817
+
1818
+ ts = Series(np.random.randn(10), index=date_range("1/1/2000", periods=10))
1819
+
1820
+ df = DataFrame(np.random.randn(10, 2), index=ts.index, columns=list("AB"))
1821
+
1822
+ def _get_vertical_grid():
1823
+ gs = gridspec.GridSpec(3, 1)
1824
+ fig = plt.figure()
1825
+ ax1 = fig.add_subplot(gs[:2, :])
1826
+ ax2 = fig.add_subplot(gs[2, :])
1827
+ return ax1, ax2
1828
+
1829
+ def _get_horizontal_grid():
1830
+ gs = gridspec.GridSpec(1, 3)
1831
+ fig = plt.figure()
1832
+ ax1 = fig.add_subplot(gs[:, :2])
1833
+ ax2 = fig.add_subplot(gs[:, 2])
1834
+ return ax1, ax2
1835
+
1836
+ for ax1, ax2 in [_get_vertical_grid(), _get_horizontal_grid()]:
1837
+ ax1 = ts.plot(ax=ax1)
1838
+ assert len(ax1.lines) == 1
1839
+ ax2 = df.plot(ax=ax2)
1840
+ assert len(ax2.lines) == 2
1841
+ for ax in [ax1, ax2]:
1842
+ self._check_visible(ax.get_yticklabels(), visible=True)
1843
+ self._check_visible(ax.get_xticklabels(), visible=True)
1844
+ self._check_visible(ax.get_xticklabels(minor=True), visible=True)
1845
+ tm.close()
1846
+
1847
+ # subplots=True
1848
+ for ax1, ax2 in [_get_vertical_grid(), _get_horizontal_grid()]:
1849
+ axes = df.plot(subplots=True, ax=[ax1, ax2])
1850
+ assert len(ax1.lines) == 1
1851
+ assert len(ax2.lines) == 1
1852
+ for ax in axes:
1853
+ self._check_visible(ax.get_yticklabels(), visible=True)
1854
+ self._check_visible(ax.get_xticklabels(), visible=True)
1855
+ self._check_visible(ax.get_xticklabels(minor=True), visible=True)
1856
+ tm.close()
1857
+
1858
+ # vertical / subplots / sharex=True / sharey=True
1859
+ ax1, ax2 = _get_vertical_grid()
1860
+ with tm.assert_produces_warning(UserWarning):
1861
+ axes = df.plot(subplots=True, ax=[ax1, ax2], sharex=True, sharey=True)
1862
+ assert len(axes[0].lines) == 1
1863
+ assert len(axes[1].lines) == 1
1864
+ for ax in [ax1, ax2]:
1865
+ # yaxis are visible because there is only one column
1866
+ self._check_visible(ax.get_yticklabels(), visible=True)
1867
+ # xaxis of axes0 (top) are hidden
1868
+ self._check_visible(axes[0].get_xticklabels(), visible=False)
1869
+ self._check_visible(axes[0].get_xticklabels(minor=True), visible=False)
1870
+ self._check_visible(axes[1].get_xticklabels(), visible=True)
1871
+ self._check_visible(axes[1].get_xticklabels(minor=True), visible=True)
1872
+ tm.close()
1873
+
1874
+ # horizontal / subplots / sharex=True / sharey=True
1875
+ ax1, ax2 = _get_horizontal_grid()
1876
+ with tm.assert_produces_warning(UserWarning):
1877
+ axes = df.plot(subplots=True, ax=[ax1, ax2], sharex=True, sharey=True)
1878
+ assert len(axes[0].lines) == 1
1879
+ assert len(axes[1].lines) == 1
1880
+ self._check_visible(axes[0].get_yticklabels(), visible=True)
1881
+ # yaxis of axes1 (right) are hidden
1882
+ self._check_visible(axes[1].get_yticklabels(), visible=False)
1883
+ for ax in [ax1, ax2]:
1884
+ # xaxis are visible because there is only one column
1885
+ self._check_visible(ax.get_xticklabels(), visible=True)
1886
+ self._check_visible(ax.get_xticklabels(minor=True), visible=True)
1887
+ tm.close()
1888
+
1889
+ # boxed
1890
+ def _get_boxed_grid():
1891
+ gs = gridspec.GridSpec(3, 3)
1892
+ fig = plt.figure()
1893
+ ax1 = fig.add_subplot(gs[:2, :2])
1894
+ ax2 = fig.add_subplot(gs[:2, 2])
1895
+ ax3 = fig.add_subplot(gs[2, :2])
1896
+ ax4 = fig.add_subplot(gs[2, 2])
1897
+ return ax1, ax2, ax3, ax4
1898
+
1899
+ axes = _get_boxed_grid()
1900
+ df = DataFrame(np.random.randn(10, 4), index=ts.index, columns=list("ABCD"))
1901
+ axes = df.plot(subplots=True, ax=axes)
1902
+ for ax in axes:
1903
+ assert len(ax.lines) == 1
1904
+ # axis are visible because these are not shared
1905
+ self._check_visible(ax.get_yticklabels(), visible=True)
1906
+ self._check_visible(ax.get_xticklabels(), visible=True)
1907
+ self._check_visible(ax.get_xticklabels(minor=True), visible=True)
1908
+ tm.close()
1909
+
1910
+ # subplots / sharex=True / sharey=True
1911
+ axes = _get_boxed_grid()
1912
+ with tm.assert_produces_warning(UserWarning):
1913
+ axes = df.plot(subplots=True, ax=axes, sharex=True, sharey=True)
1914
+ for ax in axes:
1915
+ assert len(ax.lines) == 1
1916
+ for ax in [axes[0], axes[2]]: # left column
1917
+ self._check_visible(ax.get_yticklabels(), visible=True)
1918
+ for ax in [axes[1], axes[3]]: # right column
1919
+ self._check_visible(ax.get_yticklabels(), visible=False)
1920
+ for ax in [axes[0], axes[1]]: # top row
1921
+ self._check_visible(ax.get_xticklabels(), visible=False)
1922
+ self._check_visible(ax.get_xticklabels(minor=True), visible=False)
1923
+ for ax in [axes[2], axes[3]]: # bottom row
1924
+ self._check_visible(ax.get_xticklabels(), visible=True)
1925
+ self._check_visible(ax.get_xticklabels(minor=True), visible=True)
1926
+ tm.close()
1927
+
1928
+ def test_df_grid_settings(self):
1929
+ # Make sure plot defaults to rcParams['axes.grid'] setting, GH 9792
1930
+ self._check_grid_settings(
1931
+ DataFrame({"a": [1, 2, 3], "b": [2, 3, 4]}),
1932
+ plotting.PlotAccessor._dataframe_kinds,
1933
+ kws={"x": "a", "y": "b"},
1934
+ )
1935
+
1936
+ def test_plain_axes(self):
1937
+ # supplied ax itself is a SubplotAxes, but figure contains also
1938
+ # a plain Axes object (GH11556)
1939
+ fig, ax = self.plt.subplots()
1940
+ fig.add_axes([0.2, 0.2, 0.2, 0.2])
1941
+ Series(np.random.rand(10)).plot(ax=ax)
1942
+
1943
+ # supplied ax itself is a plain Axes, but because the cmap keyword
1944
+ # a new ax is created for the colorbar -> also multiples axes (GH11520)
1945
+ df = DataFrame({"a": np.random.randn(8), "b": np.random.randn(8)})
1946
+ fig = self.plt.figure()
1947
+ ax = fig.add_axes((0, 0, 1, 1))
1948
+ df.plot(kind="scatter", ax=ax, x="a", y="b", c="a", cmap="hsv")
1949
+
1950
+ # other examples
1951
+ fig, ax = self.plt.subplots()
1952
+ from mpl_toolkits.axes_grid1 import make_axes_locatable
1953
+
1954
+ divider = make_axes_locatable(ax)
1955
+ cax = divider.append_axes("right", size="5%", pad=0.05)
1956
+ Series(np.random.rand(10)).plot(ax=ax)
1957
+ Series(np.random.rand(10)).plot(ax=cax)
1958
+
1959
+ fig, ax = self.plt.subplots()
1960
+ from mpl_toolkits.axes_grid1.inset_locator import inset_axes
1961
+
1962
+ iax = inset_axes(ax, width="30%", height=1.0, loc=3)
1963
+ Series(np.random.rand(10)).plot(ax=ax)
1964
+ Series(np.random.rand(10)).plot(ax=iax)
1965
+
1966
+ @pytest.mark.parametrize("method", ["line", "barh", "bar"])
1967
+ def test_secondary_axis_font_size(self, method):
1968
+ # GH: 12565
1969
+ df = (
1970
+ DataFrame(np.random.randn(15, 2), columns=list("AB"))
1971
+ .assign(C=lambda df: df.B.cumsum())
1972
+ .assign(D=lambda df: df.C * 1.1)
1973
+ )
1974
+
1975
+ fontsize = 20
1976
+ sy = ["C", "D"]
1977
+
1978
+ kwargs = {"secondary_y": sy, "fontsize": fontsize, "mark_right": True}
1979
+ ax = getattr(df.plot, method)(**kwargs)
1980
+ self._check_ticks_props(axes=ax.right_ax, ylabelsize=fontsize)
1981
+
1982
+ def test_x_string_values_ticks(self):
1983
+ # Test if string plot index have a fixed xtick position
1984
+ # GH: 7612, GH: 22334
1985
+ df = DataFrame(
1986
+ {
1987
+ "sales": [3, 2, 3],
1988
+ "visits": [20, 42, 28],
1989
+ "day": ["Monday", "Tuesday", "Wednesday"],
1990
+ }
1991
+ )
1992
+ ax = df.plot.area(x="day")
1993
+ ax.set_xlim(-1, 3)
1994
+ xticklabels = [t.get_text() for t in ax.get_xticklabels()]
1995
+ labels_position = dict(zip(xticklabels, ax.get_xticks()))
1996
+ # Testing if the label stayed at the right position
1997
+ assert labels_position["Monday"] == 0.0
1998
+ assert labels_position["Tuesday"] == 1.0
1999
+ assert labels_position["Wednesday"] == 2.0
2000
+
2001
+ def test_x_multiindex_values_ticks(self):
2002
+ # Test if multiindex plot index have a fixed xtick position
2003
+ # GH: 15912
2004
+ index = MultiIndex.from_product([[2012, 2013], [1, 2]])
2005
+ df = DataFrame(np.random.randn(4, 2), columns=["A", "B"], index=index)
2006
+ ax = df.plot()
2007
+ ax.set_xlim(-1, 4)
2008
+ xticklabels = [t.get_text() for t in ax.get_xticklabels()]
2009
+ labels_position = dict(zip(xticklabels, ax.get_xticks()))
2010
+ # Testing if the label stayed at the right position
2011
+ assert labels_position["(2012, 1)"] == 0.0
2012
+ assert labels_position["(2012, 2)"] == 1.0
2013
+ assert labels_position["(2013, 1)"] == 2.0
2014
+ assert labels_position["(2013, 2)"] == 3.0
2015
+
2016
+ @pytest.mark.parametrize("kind", ["line", "area"])
2017
+ def test_xlim_plot_line(self, kind):
2018
+ # test if xlim is set correctly in plot.line and plot.area
2019
+ # GH 27686
2020
+ df = DataFrame([2, 4], index=[1, 2])
2021
+ ax = df.plot(kind=kind)
2022
+ xlims = ax.get_xlim()
2023
+ assert xlims[0] < 1
2024
+ assert xlims[1] > 2
2025
+
2026
+ def test_xlim_plot_line_correctly_in_mixed_plot_type(self):
2027
+ # test if xlim is set correctly when ax contains multiple different kinds
2028
+ # of plots, GH 27686
2029
+ fig, ax = self.plt.subplots()
2030
+
2031
+ indexes = ["k1", "k2", "k3", "k4"]
2032
+ df = DataFrame(
2033
+ {
2034
+ "s1": [1000, 2000, 1500, 2000],
2035
+ "s2": [900, 1400, 2000, 3000],
2036
+ "s3": [1500, 1500, 1600, 1200],
2037
+ "secondary_y": [1, 3, 4, 3],
2038
+ },
2039
+ index=indexes,
2040
+ )
2041
+ df[["s1", "s2", "s3"]].plot.bar(ax=ax, stacked=False)
2042
+ df[["secondary_y"]].plot(ax=ax, secondary_y=True)
2043
+
2044
+ xlims = ax.get_xlim()
2045
+ assert xlims[0] < 0
2046
+ assert xlims[1] > 3
2047
+
2048
+ # make sure axis labels are plotted correctly as well
2049
+ xticklabels = [t.get_text() for t in ax.get_xticklabels()]
2050
+ assert xticklabels == indexes
2051
+
2052
+ def test_plot_no_rows(self):
2053
+ # GH 27758
2054
+ df = DataFrame(columns=["foo"], dtype=int)
2055
+ assert df.empty
2056
+ ax = df.plot()
2057
+ assert len(ax.get_lines()) == 1
2058
+ line = ax.get_lines()[0]
2059
+ assert len(line.get_xdata()) == 0
2060
+ assert len(line.get_ydata()) == 0
2061
+
2062
+ def test_plot_no_numeric_data(self):
2063
+ df = DataFrame(["a", "b", "c"])
2064
+ with pytest.raises(TypeError, match="no numeric data to plot"):
2065
+ df.plot()
2066
+
2067
+ @td.skip_if_no_scipy
2068
+ @pytest.mark.parametrize(
2069
+ "kind", ("line", "bar", "barh", "hist", "kde", "density", "area", "pie")
2070
+ )
2071
+ def test_group_subplot(self, kind):
2072
+ d = {
2073
+ "a": np.arange(10),
2074
+ "b": np.arange(10) + 1,
2075
+ "c": np.arange(10) + 1,
2076
+ "d": np.arange(10),
2077
+ "e": np.arange(10),
2078
+ }
2079
+ df = DataFrame(d)
2080
+
2081
+ axes = df.plot(subplots=[("b", "e"), ("c", "d")], kind=kind)
2082
+ assert len(axes) == 3 # 2 groups + single column a
2083
+
2084
+ expected_labels = (["b", "e"], ["c", "d"], ["a"])
2085
+ for ax, labels in zip(axes, expected_labels):
2086
+ if kind != "pie":
2087
+ self._check_legend_labels(ax, labels=labels)
2088
+ if kind == "line":
2089
+ assert len(ax.lines) == len(labels)
2090
+
2091
+ def test_group_subplot_series_notimplemented(self):
2092
+ ser = Series(range(1))
2093
+ msg = "An iterable subplots for a Series"
2094
+ with pytest.raises(NotImplementedError, match=msg):
2095
+ ser.plot(subplots=[("a",)])
2096
+
2097
+ def test_group_subplot_multiindex_notimplemented(self):
2098
+ df = DataFrame(np.eye(2), columns=MultiIndex.from_tuples([(0, 1), (1, 2)]))
2099
+ msg = "An iterable subplots for a DataFrame with a MultiIndex"
2100
+ with pytest.raises(NotImplementedError, match=msg):
2101
+ df.plot(subplots=[(0, 1)])
2102
+
2103
+ def test_group_subplot_nonunique_cols_notimplemented(self):
2104
+ df = DataFrame(np.eye(2), columns=["a", "a"])
2105
+ msg = "An iterable subplots for a DataFrame with non-unique"
2106
+ with pytest.raises(NotImplementedError, match=msg):
2107
+ df.plot(subplots=[("a",)])
2108
+
2109
+ @pytest.mark.parametrize(
2110
+ "subplots, expected_msg",
2111
+ [
2112
+ (123, "subplots should be a bool or an iterable"),
2113
+ ("a", "each entry should be a list/tuple"), # iterable of non-iterable
2114
+ ((1,), "each entry should be a list/tuple"), # iterable of non-iterable
2115
+ (("a",), "each entry should be a list/tuple"), # iterable of strings
2116
+ ],
2117
+ )
2118
+ def test_group_subplot_bad_input(self, subplots, expected_msg):
2119
+ # Make sure error is raised when subplots is not a properly
2120
+ # formatted iterable. Only iterables of iterables are permitted, and
2121
+ # entries should not be strings.
2122
+ d = {"a": np.arange(10), "b": np.arange(10)}
2123
+ df = DataFrame(d)
2124
+
2125
+ with pytest.raises(ValueError, match=expected_msg):
2126
+ df.plot(subplots=subplots)
2127
+
2128
+ def test_group_subplot_invalid_column_name(self):
2129
+ d = {"a": np.arange(10), "b": np.arange(10)}
2130
+ df = DataFrame(d)
2131
+
2132
+ with pytest.raises(ValueError, match=r"Column label\(s\) \['bad_name'\]"):
2133
+ df.plot(subplots=[("a", "bad_name")])
2134
+
2135
+ def test_group_subplot_duplicated_column(self):
2136
+ d = {"a": np.arange(10), "b": np.arange(10), "c": np.arange(10)}
2137
+ df = DataFrame(d)
2138
+
2139
+ with pytest.raises(ValueError, match="should be in only one subplot"):
2140
+ df.plot(subplots=[("a", "b"), ("a", "c")])
2141
+
2142
+ @pytest.mark.parametrize("kind", ("box", "scatter", "hexbin"))
2143
+ def test_group_subplot_invalid_kind(self, kind):
2144
+ d = {"a": np.arange(10), "b": np.arange(10)}
2145
+ df = DataFrame(d)
2146
+ with pytest.raises(
2147
+ ValueError, match="When subplots is an iterable, kind must be one of"
2148
+ ):
2149
+ df.plot(subplots=[("a", "b")], kind=kind)
2150
+
2151
+ @pytest.mark.parametrize(
2152
+ "index_name, old_label, new_label",
2153
+ [
2154
+ (None, "", "new"),
2155
+ ("old", "old", "new"),
2156
+ (None, "", ""),
2157
+ (None, "", 1),
2158
+ (None, "", [1, 2]),
2159
+ ],
2160
+ )
2161
+ @pytest.mark.parametrize("kind", ["line", "area", "bar"])
2162
+ def test_xlabel_ylabel_dataframe_single_plot(
2163
+ self, kind, index_name, old_label, new_label
2164
+ ):
2165
+ # GH 9093
2166
+ df = DataFrame([[1, 2], [2, 5]], columns=["Type A", "Type B"])
2167
+ df.index.name = index_name
2168
+
2169
+ # default is the ylabel is not shown and xlabel is index name
2170
+ ax = df.plot(kind=kind)
2171
+ assert ax.get_xlabel() == old_label
2172
+ assert ax.get_ylabel() == ""
2173
+
2174
+ # old xlabel will be overridden and assigned ylabel will be used as ylabel
2175
+ ax = df.plot(kind=kind, ylabel=new_label, xlabel=new_label)
2176
+ assert ax.get_ylabel() == str(new_label)
2177
+ assert ax.get_xlabel() == str(new_label)
2178
+
2179
+ @pytest.mark.parametrize(
2180
+ "xlabel, ylabel",
2181
+ [
2182
+ (None, None),
2183
+ ("X Label", None),
2184
+ (None, "Y Label"),
2185
+ ("X Label", "Y Label"),
2186
+ ],
2187
+ )
2188
+ @pytest.mark.parametrize("kind", ["scatter", "hexbin"])
2189
+ def test_xlabel_ylabel_dataframe_plane_plot(self, kind, xlabel, ylabel):
2190
+ # GH 37001
2191
+ xcol = "Type A"
2192
+ ycol = "Type B"
2193
+ df = DataFrame([[1, 2], [2, 5]], columns=[xcol, ycol])
2194
+
2195
+ # default is the labels are column names
2196
+ ax = df.plot(kind=kind, x=xcol, y=ycol, xlabel=xlabel, ylabel=ylabel)
2197
+ assert ax.get_xlabel() == (xcol if xlabel is None else xlabel)
2198
+ assert ax.get_ylabel() == (ycol if ylabel is None else ylabel)
2199
+
2200
+ @pytest.mark.parametrize("secondary_y", (False, True))
2201
+ def test_secondary_y(self, secondary_y):
2202
+ ax_df = DataFrame([0]).plot(
2203
+ secondary_y=secondary_y, ylabel="Y", ylim=(0, 100), yticks=[99]
2204
+ )
2205
+ for ax in ax_df.figure.axes:
2206
+ if ax.yaxis.get_visible():
2207
+ assert ax.get_ylabel() == "Y"
2208
+ assert ax.get_ylim() == (0, 100)
2209
+ assert ax.get_yticks()[0] == 99
2210
+
2211
+
2212
+ def _generate_4_axes_via_gridspec():
2213
+ import matplotlib as mpl
2214
+ import matplotlib.gridspec
2215
+ import matplotlib.pyplot as plt
2216
+
2217
+ gs = mpl.gridspec.GridSpec(2, 2)
2218
+ ax_tl = plt.subplot(gs[0, 0])
2219
+ ax_ll = plt.subplot(gs[1, 0])
2220
+ ax_tr = plt.subplot(gs[0, 1])
2221
+ ax_lr = plt.subplot(gs[1, 1])
2222
+
2223
+ return gs, [ax_tl, ax_ll, ax_tr, ax_lr]
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/test_frame_color.py ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Test cases for DataFrame.plot """
2
+ import re
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ import pandas.util._test_decorators as td
8
+
9
+ import pandas as pd
10
+ from pandas import DataFrame
11
+ import pandas._testing as tm
12
+ from pandas.tests.plotting.common import (
13
+ TestPlotBase,
14
+ _check_plot_works,
15
+ )
16
+ from pandas.util.version import Version
17
+
18
+
19
+ @td.skip_if_no_mpl
20
+ class TestDataFrameColor(TestPlotBase):
21
+ @pytest.mark.parametrize(
22
+ "color", ["C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"]
23
+ )
24
+ def test_mpl2_color_cycle_str(self, color):
25
+ # GH 15516
26
+ df = DataFrame(np.random.randn(10, 3), columns=["a", "b", "c"])
27
+ _check_plot_works(df.plot, color=color)
28
+
29
+ def test_color_single_series_list(self):
30
+ # GH 3486
31
+ df = DataFrame({"A": [1, 2, 3]})
32
+ _check_plot_works(df.plot, color=["red"])
33
+
34
+ @pytest.mark.parametrize("color", [(1, 0, 0), (1, 0, 0, 0.5)])
35
+ def test_rgb_tuple_color(self, color):
36
+ # GH 16695
37
+ df = DataFrame({"x": [1, 2], "y": [3, 4]})
38
+ _check_plot_works(df.plot, x="x", y="y", color=color)
39
+
40
+ def test_color_empty_string(self):
41
+ df = DataFrame(np.random.randn(10, 2))
42
+ with pytest.raises(ValueError, match="Invalid color argument:"):
43
+ df.plot(color="")
44
+
45
+ def test_color_and_style_arguments(self):
46
+ df = DataFrame({"x": [1, 2], "y": [3, 4]})
47
+ # passing both 'color' and 'style' arguments should be allowed
48
+ # if there is no color symbol in the style strings:
49
+ ax = df.plot(color=["red", "black"], style=["-", "--"])
50
+ # check that the linestyles are correctly set:
51
+ linestyle = [line.get_linestyle() for line in ax.lines]
52
+ assert linestyle == ["-", "--"]
53
+ # check that the colors are correctly set:
54
+ color = [line.get_color() for line in ax.lines]
55
+ assert color == ["red", "black"]
56
+ # passing both 'color' and 'style' arguments should not be allowed
57
+ # if there is a color symbol in the style strings:
58
+ msg = (
59
+ "Cannot pass 'style' string with a color symbol and 'color' keyword "
60
+ "argument. Please use one or the other or pass 'style' without a color "
61
+ "symbol"
62
+ )
63
+ with pytest.raises(ValueError, match=msg):
64
+ df.plot(color=["red", "black"], style=["k-", "r--"])
65
+
66
+ @pytest.mark.parametrize(
67
+ "color, expected",
68
+ [
69
+ ("green", ["green"] * 4),
70
+ (["yellow", "red", "green", "blue"], ["yellow", "red", "green", "blue"]),
71
+ ],
72
+ )
73
+ def test_color_and_marker(self, color, expected):
74
+ # GH 21003
75
+ df = DataFrame(np.random.random((7, 4)))
76
+ ax = df.plot(color=color, style="d--")
77
+ # check colors
78
+ result = [i.get_color() for i in ax.lines]
79
+ assert result == expected
80
+ # check markers and linestyles
81
+ assert all(i.get_linestyle() == "--" for i in ax.lines)
82
+ assert all(i.get_marker() == "d" for i in ax.lines)
83
+
84
+ def test_bar_colors(self):
85
+ import matplotlib.pyplot as plt
86
+
87
+ default_colors = self._unpack_cycler(plt.rcParams)
88
+
89
+ df = DataFrame(np.random.randn(5, 5))
90
+ ax = df.plot.bar()
91
+ self._check_colors(ax.patches[::5], facecolors=default_colors[:5])
92
+ tm.close()
93
+
94
+ custom_colors = "rgcby"
95
+ ax = df.plot.bar(color=custom_colors)
96
+ self._check_colors(ax.patches[::5], facecolors=custom_colors)
97
+ tm.close()
98
+
99
+ from matplotlib import cm
100
+
101
+ # Test str -> colormap functionality
102
+ ax = df.plot.bar(colormap="jet")
103
+ rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, 5)]
104
+ self._check_colors(ax.patches[::5], facecolors=rgba_colors)
105
+ tm.close()
106
+
107
+ # Test colormap functionality
108
+ ax = df.plot.bar(colormap=cm.jet)
109
+ rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, 5)]
110
+ self._check_colors(ax.patches[::5], facecolors=rgba_colors)
111
+ tm.close()
112
+
113
+ ax = df.loc[:, [0]].plot.bar(color="DodgerBlue")
114
+ self._check_colors([ax.patches[0]], facecolors=["DodgerBlue"])
115
+ tm.close()
116
+
117
+ ax = df.plot(kind="bar", color="green")
118
+ self._check_colors(ax.patches[::5], facecolors=["green"] * 5)
119
+ tm.close()
120
+
121
+ def test_bar_user_colors(self):
122
+ df = DataFrame(
123
+ {"A": range(4), "B": range(1, 5), "color": ["red", "blue", "blue", "red"]}
124
+ )
125
+ # This should *only* work when `y` is specified, else
126
+ # we use one color per column
127
+ ax = df.plot.bar(y="A", color=df["color"])
128
+ result = [p.get_facecolor() for p in ax.patches]
129
+ expected = [
130
+ (1.0, 0.0, 0.0, 1.0),
131
+ (0.0, 0.0, 1.0, 1.0),
132
+ (0.0, 0.0, 1.0, 1.0),
133
+ (1.0, 0.0, 0.0, 1.0),
134
+ ]
135
+ assert result == expected
136
+
137
+ def test_if_scatterplot_colorbar_affects_xaxis_visibility(self):
138
+ # addressing issue #10611, to ensure colobar does not
139
+ # interfere with x-axis label and ticklabels with
140
+ # ipython inline backend.
141
+ random_array = np.random.random((1000, 3))
142
+ df = DataFrame(random_array, columns=["A label", "B label", "C label"])
143
+
144
+ ax1 = df.plot.scatter(x="A label", y="B label")
145
+ ax2 = df.plot.scatter(x="A label", y="B label", c="C label")
146
+
147
+ vis1 = [vis.get_visible() for vis in ax1.xaxis.get_minorticklabels()]
148
+ vis2 = [vis.get_visible() for vis in ax2.xaxis.get_minorticklabels()]
149
+ assert vis1 == vis2
150
+
151
+ vis1 = [vis.get_visible() for vis in ax1.xaxis.get_majorticklabels()]
152
+ vis2 = [vis.get_visible() for vis in ax2.xaxis.get_majorticklabels()]
153
+ assert vis1 == vis2
154
+
155
+ assert (
156
+ ax1.xaxis.get_label().get_visible() == ax2.xaxis.get_label().get_visible()
157
+ )
158
+
159
+ def test_if_hexbin_xaxis_label_is_visible(self):
160
+ # addressing issue #10678, to ensure colobar does not
161
+ # interfere with x-axis label and ticklabels with
162
+ # ipython inline backend.
163
+ random_array = np.random.random((1000, 3))
164
+ df = DataFrame(random_array, columns=["A label", "B label", "C label"])
165
+
166
+ ax = df.plot.hexbin("A label", "B label", gridsize=12)
167
+ assert all(vis.get_visible() for vis in ax.xaxis.get_minorticklabels())
168
+ assert all(vis.get_visible() for vis in ax.xaxis.get_majorticklabels())
169
+ assert ax.xaxis.get_label().get_visible()
170
+
171
+ def test_if_scatterplot_colorbars_are_next_to_parent_axes(self):
172
+ import matplotlib.pyplot as plt
173
+
174
+ random_array = np.random.random((1000, 3))
175
+ df = DataFrame(random_array, columns=["A label", "B label", "C label"])
176
+
177
+ fig, axes = plt.subplots(1, 2)
178
+ df.plot.scatter("A label", "B label", c="C label", ax=axes[0])
179
+ df.plot.scatter("A label", "B label", c="C label", ax=axes[1])
180
+ plt.tight_layout()
181
+
182
+ points = np.array([ax.get_position().get_points() for ax in fig.axes])
183
+ axes_x_coords = points[:, :, 0]
184
+ parent_distance = axes_x_coords[1, :] - axes_x_coords[0, :]
185
+ colorbar_distance = axes_x_coords[3, :] - axes_x_coords[2, :]
186
+ assert np.isclose(parent_distance, colorbar_distance, atol=1e-7).all()
187
+
188
+ @pytest.mark.parametrize("cmap", [None, "Greys"])
189
+ def test_scatter_with_c_column_name_with_colors(self, cmap):
190
+ # https://github.com/pandas-dev/pandas/issues/34316
191
+
192
+ df = DataFrame(
193
+ [[5.1, 3.5], [4.9, 3.0], [7.0, 3.2], [6.4, 3.2], [5.9, 3.0]],
194
+ columns=["length", "width"],
195
+ )
196
+ df["species"] = ["r", "r", "g", "g", "b"]
197
+ if cmap is not None:
198
+ with tm.assert_produces_warning(UserWarning, check_stacklevel=False):
199
+ ax = df.plot.scatter(x=0, y=1, cmap=cmap, c="species")
200
+ else:
201
+ ax = df.plot.scatter(x=0, y=1, c="species", cmap=cmap)
202
+ assert ax.collections[0].colorbar is None
203
+
204
+ def test_scatter_colors(self):
205
+ df = DataFrame({"a": [1, 2, 3], "b": [1, 2, 3], "c": [1, 2, 3]})
206
+ with pytest.raises(TypeError, match="Specify exactly one of `c` and `color`"):
207
+ df.plot.scatter(x="a", y="b", c="c", color="green")
208
+
209
+ default_colors = self._unpack_cycler(self.plt.rcParams)
210
+
211
+ ax = df.plot.scatter(x="a", y="b", c="c")
212
+ tm.assert_numpy_array_equal(
213
+ ax.collections[0].get_facecolor()[0],
214
+ np.array(self.colorconverter.to_rgba(default_colors[0])),
215
+ )
216
+
217
+ ax = df.plot.scatter(x="a", y="b", color="white")
218
+ tm.assert_numpy_array_equal(
219
+ ax.collections[0].get_facecolor()[0],
220
+ np.array([1, 1, 1, 1], dtype=np.float64),
221
+ )
222
+
223
+ def test_scatter_colorbar_different_cmap(self):
224
+ # GH 33389
225
+ import matplotlib.pyplot as plt
226
+
227
+ df = DataFrame({"x": [1, 2, 3], "y": [1, 3, 2], "c": [1, 2, 3]})
228
+ df["x2"] = df["x"] + 1
229
+
230
+ fig, ax = plt.subplots()
231
+ df.plot("x", "y", c="c", kind="scatter", cmap="cividis", ax=ax)
232
+ df.plot("x2", "y", c="c", kind="scatter", cmap="magma", ax=ax)
233
+
234
+ assert ax.collections[0].cmap.name == "cividis"
235
+ assert ax.collections[1].cmap.name == "magma"
236
+
237
+ def test_line_colors(self):
238
+ from matplotlib import cm
239
+
240
+ custom_colors = "rgcby"
241
+ df = DataFrame(np.random.randn(5, 5))
242
+
243
+ ax = df.plot(color=custom_colors)
244
+ self._check_colors(ax.get_lines(), linecolors=custom_colors)
245
+
246
+ tm.close()
247
+
248
+ ax2 = df.plot(color=custom_colors)
249
+ lines2 = ax2.get_lines()
250
+
251
+ for l1, l2 in zip(ax.get_lines(), lines2):
252
+ assert l1.get_color() == l2.get_color()
253
+
254
+ tm.close()
255
+
256
+ ax = df.plot(colormap="jet")
257
+ rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, len(df))]
258
+ self._check_colors(ax.get_lines(), linecolors=rgba_colors)
259
+ tm.close()
260
+
261
+ ax = df.plot(colormap=cm.jet)
262
+ rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, len(df))]
263
+ self._check_colors(ax.get_lines(), linecolors=rgba_colors)
264
+ tm.close()
265
+
266
+ # make color a list if plotting one column frame
267
+ # handles cases like df.plot(color='DodgerBlue')
268
+ ax = df.loc[:, [0]].plot(color="DodgerBlue")
269
+ self._check_colors(ax.lines, linecolors=["DodgerBlue"])
270
+
271
+ ax = df.plot(color="red")
272
+ self._check_colors(ax.get_lines(), linecolors=["red"] * 5)
273
+ tm.close()
274
+
275
+ # GH 10299
276
+ custom_colors = ["#FF0000", "#0000FF", "#FFFF00", "#000000", "#FFFFFF"]
277
+ ax = df.plot(color=custom_colors)
278
+ self._check_colors(ax.get_lines(), linecolors=custom_colors)
279
+ tm.close()
280
+
281
+ def test_dont_modify_colors(self):
282
+ colors = ["r", "g", "b"]
283
+ DataFrame(np.random.rand(10, 2)).plot(color=colors)
284
+ assert len(colors) == 3
285
+
286
+ def test_line_colors_and_styles_subplots(self):
287
+ # GH 9894
288
+ from matplotlib import cm
289
+
290
+ default_colors = self._unpack_cycler(self.plt.rcParams)
291
+
292
+ df = DataFrame(np.random.randn(5, 5))
293
+
294
+ axes = df.plot(subplots=True)
295
+ for ax, c in zip(axes, list(default_colors)):
296
+ self._check_colors(ax.get_lines(), linecolors=[c])
297
+ tm.close()
298
+
299
+ # single color char
300
+ axes = df.plot(subplots=True, color="k")
301
+ for ax in axes:
302
+ self._check_colors(ax.get_lines(), linecolors=["k"])
303
+ tm.close()
304
+
305
+ # single color str
306
+ axes = df.plot(subplots=True, color="green")
307
+ for ax in axes:
308
+ self._check_colors(ax.get_lines(), linecolors=["green"])
309
+ tm.close()
310
+
311
+ custom_colors = "rgcby"
312
+ axes = df.plot(color=custom_colors, subplots=True)
313
+ for ax, c in zip(axes, list(custom_colors)):
314
+ self._check_colors(ax.get_lines(), linecolors=[c])
315
+ tm.close()
316
+
317
+ axes = df.plot(color=list(custom_colors), subplots=True)
318
+ for ax, c in zip(axes, list(custom_colors)):
319
+ self._check_colors(ax.get_lines(), linecolors=[c])
320
+ tm.close()
321
+
322
+ # GH 10299
323
+ custom_colors = ["#FF0000", "#0000FF", "#FFFF00", "#000000", "#FFFFFF"]
324
+ axes = df.plot(color=custom_colors, subplots=True)
325
+ for ax, c in zip(axes, list(custom_colors)):
326
+ self._check_colors(ax.get_lines(), linecolors=[c])
327
+ tm.close()
328
+
329
+ rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, len(df))]
330
+ for cmap in ["jet", cm.jet]:
331
+ axes = df.plot(colormap=cmap, subplots=True)
332
+ for ax, c in zip(axes, rgba_colors):
333
+ self._check_colors(ax.get_lines(), linecolors=[c])
334
+ tm.close()
335
+
336
+ # make color a list if plotting one column frame
337
+ # handles cases like df.plot(color='DodgerBlue')
338
+ axes = df.loc[:, [0]].plot(color="DodgerBlue", subplots=True)
339
+ self._check_colors(axes[0].lines, linecolors=["DodgerBlue"])
340
+
341
+ # single character style
342
+ axes = df.plot(style="r", subplots=True)
343
+ for ax in axes:
344
+ self._check_colors(ax.get_lines(), linecolors=["r"])
345
+ tm.close()
346
+
347
+ # list of styles
348
+ styles = list("rgcby")
349
+ axes = df.plot(style=styles, subplots=True)
350
+ for ax, c in zip(axes, styles):
351
+ self._check_colors(ax.get_lines(), linecolors=[c])
352
+ tm.close()
353
+
354
+ def test_area_colors(self):
355
+ from matplotlib import cm
356
+ from matplotlib.collections import PolyCollection
357
+
358
+ custom_colors = "rgcby"
359
+ df = DataFrame(np.random.rand(5, 5))
360
+
361
+ ax = df.plot.area(color=custom_colors)
362
+ self._check_colors(ax.get_lines(), linecolors=custom_colors)
363
+ poly = [o for o in ax.get_children() if isinstance(o, PolyCollection)]
364
+ self._check_colors(poly, facecolors=custom_colors)
365
+
366
+ handles, labels = ax.get_legend_handles_labels()
367
+ self._check_colors(handles, facecolors=custom_colors)
368
+
369
+ for h in handles:
370
+ assert h.get_alpha() is None
371
+ tm.close()
372
+
373
+ ax = df.plot.area(colormap="jet")
374
+ jet_colors = [cm.jet(n) for n in np.linspace(0, 1, len(df))]
375
+ self._check_colors(ax.get_lines(), linecolors=jet_colors)
376
+ poly = [o for o in ax.get_children() if isinstance(o, PolyCollection)]
377
+ self._check_colors(poly, facecolors=jet_colors)
378
+
379
+ handles, labels = ax.get_legend_handles_labels()
380
+ self._check_colors(handles, facecolors=jet_colors)
381
+ for h in handles:
382
+ assert h.get_alpha() is None
383
+ tm.close()
384
+
385
+ # When stacked=False, alpha is set to 0.5
386
+ ax = df.plot.area(colormap=cm.jet, stacked=False)
387
+ self._check_colors(ax.get_lines(), linecolors=jet_colors)
388
+ poly = [o for o in ax.get_children() if isinstance(o, PolyCollection)]
389
+ jet_with_alpha = [(c[0], c[1], c[2], 0.5) for c in jet_colors]
390
+ self._check_colors(poly, facecolors=jet_with_alpha)
391
+
392
+ handles, labels = ax.get_legend_handles_labels()
393
+ linecolors = jet_with_alpha
394
+ self._check_colors(handles[: len(jet_colors)], linecolors=linecolors)
395
+ for h in handles:
396
+ assert h.get_alpha() == 0.5
397
+
398
+ def test_hist_colors(self):
399
+ default_colors = self._unpack_cycler(self.plt.rcParams)
400
+
401
+ df = DataFrame(np.random.randn(5, 5))
402
+ ax = df.plot.hist()
403
+ self._check_colors(ax.patches[::10], facecolors=default_colors[:5])
404
+ tm.close()
405
+
406
+ custom_colors = "rgcby"
407
+ ax = df.plot.hist(color=custom_colors)
408
+ self._check_colors(ax.patches[::10], facecolors=custom_colors)
409
+ tm.close()
410
+
411
+ from matplotlib import cm
412
+
413
+ # Test str -> colormap functionality
414
+ ax = df.plot.hist(colormap="jet")
415
+ rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, 5)]
416
+ self._check_colors(ax.patches[::10], facecolors=rgba_colors)
417
+ tm.close()
418
+
419
+ # Test colormap functionality
420
+ ax = df.plot.hist(colormap=cm.jet)
421
+ rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, 5)]
422
+ self._check_colors(ax.patches[::10], facecolors=rgba_colors)
423
+ tm.close()
424
+
425
+ ax = df.loc[:, [0]].plot.hist(color="DodgerBlue")
426
+ self._check_colors([ax.patches[0]], facecolors=["DodgerBlue"])
427
+
428
+ ax = df.plot(kind="hist", color="green")
429
+ self._check_colors(ax.patches[::10], facecolors=["green"] * 5)
430
+ tm.close()
431
+
432
+ @td.skip_if_no_scipy
433
+ def test_kde_colors(self):
434
+ from matplotlib import cm
435
+
436
+ custom_colors = "rgcby"
437
+ df = DataFrame(np.random.rand(5, 5))
438
+
439
+ ax = df.plot.kde(color=custom_colors)
440
+ self._check_colors(ax.get_lines(), linecolors=custom_colors)
441
+ tm.close()
442
+
443
+ ax = df.plot.kde(colormap="jet")
444
+ rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, len(df))]
445
+ self._check_colors(ax.get_lines(), linecolors=rgba_colors)
446
+ tm.close()
447
+
448
+ ax = df.plot.kde(colormap=cm.jet)
449
+ rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, len(df))]
450
+ self._check_colors(ax.get_lines(), linecolors=rgba_colors)
451
+
452
+ @td.skip_if_no_scipy
453
+ def test_kde_colors_and_styles_subplots(self):
454
+ from matplotlib import cm
455
+
456
+ default_colors = self._unpack_cycler(self.plt.rcParams)
457
+
458
+ df = DataFrame(np.random.randn(5, 5))
459
+
460
+ axes = df.plot(kind="kde", subplots=True)
461
+ for ax, c in zip(axes, list(default_colors)):
462
+ self._check_colors(ax.get_lines(), linecolors=[c])
463
+ tm.close()
464
+
465
+ # single color char
466
+ axes = df.plot(kind="kde", color="k", subplots=True)
467
+ for ax in axes:
468
+ self._check_colors(ax.get_lines(), linecolors=["k"])
469
+ tm.close()
470
+
471
+ # single color str
472
+ axes = df.plot(kind="kde", color="red", subplots=True)
473
+ for ax in axes:
474
+ self._check_colors(ax.get_lines(), linecolors=["red"])
475
+ tm.close()
476
+
477
+ custom_colors = "rgcby"
478
+ axes = df.plot(kind="kde", color=custom_colors, subplots=True)
479
+ for ax, c in zip(axes, list(custom_colors)):
480
+ self._check_colors(ax.get_lines(), linecolors=[c])
481
+ tm.close()
482
+
483
+ rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, len(df))]
484
+ for cmap in ["jet", cm.jet]:
485
+ axes = df.plot(kind="kde", colormap=cmap, subplots=True)
486
+ for ax, c in zip(axes, rgba_colors):
487
+ self._check_colors(ax.get_lines(), linecolors=[c])
488
+ tm.close()
489
+
490
+ # make color a list if plotting one column frame
491
+ # handles cases like df.plot(color='DodgerBlue')
492
+ axes = df.loc[:, [0]].plot(kind="kde", color="DodgerBlue", subplots=True)
493
+ self._check_colors(axes[0].lines, linecolors=["DodgerBlue"])
494
+
495
+ # single character style
496
+ axes = df.plot(kind="kde", style="r", subplots=True)
497
+ for ax in axes:
498
+ self._check_colors(ax.get_lines(), linecolors=["r"])
499
+ tm.close()
500
+
501
+ # list of styles
502
+ styles = list("rgcby")
503
+ axes = df.plot(kind="kde", style=styles, subplots=True)
504
+ for ax, c in zip(axes, styles):
505
+ self._check_colors(ax.get_lines(), linecolors=[c])
506
+ tm.close()
507
+
508
+ def test_boxplot_colors(self):
509
+ def _check_colors(bp, box_c, whiskers_c, medians_c, caps_c="k", fliers_c=None):
510
+ # TODO: outside this func?
511
+ if fliers_c is None:
512
+ fliers_c = "k"
513
+ self._check_colors(bp["boxes"], linecolors=[box_c] * len(bp["boxes"]))
514
+ self._check_colors(
515
+ bp["whiskers"], linecolors=[whiskers_c] * len(bp["whiskers"])
516
+ )
517
+ self._check_colors(
518
+ bp["medians"], linecolors=[medians_c] * len(bp["medians"])
519
+ )
520
+ self._check_colors(bp["fliers"], linecolors=[fliers_c] * len(bp["fliers"]))
521
+ self._check_colors(bp["caps"], linecolors=[caps_c] * len(bp["caps"]))
522
+
523
+ default_colors = self._unpack_cycler(self.plt.rcParams)
524
+
525
+ df = DataFrame(np.random.randn(5, 5))
526
+ bp = df.plot.box(return_type="dict")
527
+ _check_colors(
528
+ bp,
529
+ default_colors[0],
530
+ default_colors[0],
531
+ default_colors[2],
532
+ default_colors[0],
533
+ )
534
+ tm.close()
535
+
536
+ dict_colors = {
537
+ "boxes": "#572923",
538
+ "whiskers": "#982042",
539
+ "medians": "#804823",
540
+ "caps": "#123456",
541
+ }
542
+ bp = df.plot.box(color=dict_colors, sym="r+", return_type="dict")
543
+ _check_colors(
544
+ bp,
545
+ dict_colors["boxes"],
546
+ dict_colors["whiskers"],
547
+ dict_colors["medians"],
548
+ dict_colors["caps"],
549
+ "r",
550
+ )
551
+ tm.close()
552
+
553
+ # partial colors
554
+ dict_colors = {"whiskers": "c", "medians": "m"}
555
+ bp = df.plot.box(color=dict_colors, return_type="dict")
556
+ _check_colors(bp, default_colors[0], "c", "m", default_colors[0])
557
+ tm.close()
558
+
559
+ from matplotlib import cm
560
+
561
+ # Test str -> colormap functionality
562
+ bp = df.plot.box(colormap="jet", return_type="dict")
563
+ jet_colors = [cm.jet(n) for n in np.linspace(0, 1, 3)]
564
+ _check_colors(bp, jet_colors[0], jet_colors[0], jet_colors[2], jet_colors[0])
565
+ tm.close()
566
+
567
+ # Test colormap functionality
568
+ bp = df.plot.box(colormap=cm.jet, return_type="dict")
569
+ _check_colors(bp, jet_colors[0], jet_colors[0], jet_colors[2], jet_colors[0])
570
+ tm.close()
571
+
572
+ # string color is applied to all artists except fliers
573
+ bp = df.plot.box(color="DodgerBlue", return_type="dict")
574
+ _check_colors(bp, "DodgerBlue", "DodgerBlue", "DodgerBlue", "DodgerBlue")
575
+
576
+ # tuple is also applied to all artists except fliers
577
+ bp = df.plot.box(color=(0, 1, 0), sym="#123456", return_type="dict")
578
+ _check_colors(bp, (0, 1, 0), (0, 1, 0), (0, 1, 0), (0, 1, 0), "#123456")
579
+
580
+ msg = re.escape(
581
+ "color dict contains invalid key 'xxxx'. The key must be either "
582
+ "['boxes', 'whiskers', 'medians', 'caps']"
583
+ )
584
+ with pytest.raises(ValueError, match=msg):
585
+ # Color contains invalid key results in ValueError
586
+ df.plot.box(color={"boxes": "red", "xxxx": "blue"})
587
+
588
+ def test_default_color_cycle(self):
589
+ import cycler
590
+ import matplotlib.pyplot as plt
591
+
592
+ colors = list("rgbk")
593
+ plt.rcParams["axes.prop_cycle"] = cycler.cycler("color", colors)
594
+
595
+ df = DataFrame(np.random.randn(5, 3))
596
+ ax = df.plot()
597
+
598
+ expected = self._unpack_cycler(plt.rcParams)[:3]
599
+ self._check_colors(ax.get_lines(), linecolors=expected)
600
+
601
+ def test_no_color_bar(self):
602
+ df = DataFrame(
603
+ {
604
+ "A": np.random.uniform(size=20),
605
+ "B": np.random.uniform(size=20),
606
+ "C": np.arange(20) + np.random.uniform(size=20),
607
+ }
608
+ )
609
+ ax = df.plot.hexbin(x="A", y="B", colorbar=None)
610
+ assert ax.collections[0].colorbar is None
611
+
612
+ def test_mixing_cmap_and_colormap_raises(self):
613
+ df = DataFrame(
614
+ {
615
+ "A": np.random.uniform(size=20),
616
+ "B": np.random.uniform(size=20),
617
+ "C": np.arange(20) + np.random.uniform(size=20),
618
+ }
619
+ )
620
+ msg = "Only specify one of `cmap` and `colormap`"
621
+ with pytest.raises(TypeError, match=msg):
622
+ df.plot.hexbin(x="A", y="B", cmap="YlGn", colormap="BuGn")
623
+
624
+ def test_passed_bar_colors(self):
625
+ import matplotlib as mpl
626
+
627
+ color_tuples = [(0.9, 0, 0, 1), (0, 0.9, 0, 1), (0, 0, 0.9, 1)]
628
+ colormap = mpl.colors.ListedColormap(color_tuples)
629
+ barplot = DataFrame([[1, 2, 3]]).plot(kind="bar", cmap=colormap)
630
+ assert color_tuples == [c.get_facecolor() for c in barplot.patches]
631
+
632
+ def test_rcParams_bar_colors(self):
633
+ import matplotlib as mpl
634
+
635
+ color_tuples = [(0.9, 0, 0, 1), (0, 0.9, 0, 1), (0, 0, 0.9, 1)]
636
+ with mpl.rc_context(rc={"axes.prop_cycle": mpl.cycler("color", color_tuples)}):
637
+ barplot = DataFrame([[1, 2, 3]]).plot(kind="bar")
638
+ assert color_tuples == [c.get_facecolor() for c in barplot.patches]
639
+
640
+ def test_colors_of_columns_with_same_name(self):
641
+ # ISSUE 11136 -> https://github.com/pandas-dev/pandas/issues/11136
642
+ # Creating a DataFrame with duplicate column labels and testing colors of them.
643
+ import matplotlib as mpl
644
+
645
+ df = DataFrame({"b": [0, 1, 0], "a": [1, 2, 3]})
646
+ df1 = DataFrame({"a": [2, 4, 6]})
647
+ df_concat = pd.concat([df, df1], axis=1)
648
+ result = df_concat.plot()
649
+ legend = result.get_legend()
650
+ if Version(mpl.__version__) < Version("3.7"):
651
+ handles = legend.legendHandles
652
+ else:
653
+ handles = legend.legend_handles
654
+ for legend, line in zip(handles, result.lines):
655
+ assert legend.get_color() == line.get_color()
656
+
657
+ def test_invalid_colormap(self):
658
+ df = DataFrame(np.random.randn(3, 2), columns=["A", "B"])
659
+ msg = "(is not a valid value)|(is not a known colormap)"
660
+ with pytest.raises((ValueError, KeyError), match=msg):
661
+ df.plot(colormap="invalid_colormap")
videochat2/lib/python3.10/site-packages/pandas/tests/plotting/frame/test_frame_groupby.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Test cases for DataFrame.plot """
2
+
3
+ import pytest
4
+
5
+ import pandas.util._test_decorators as td
6
+
7
+ from pandas import DataFrame
8
+ from pandas.tests.plotting.common import TestPlotBase
9
+
10
+
11
+ @td.skip_if_no_mpl
12
+ class TestDataFramePlotsGroupby(TestPlotBase):
13
+ def _assert_ytickslabels_visibility(self, axes, expected):
14
+ for ax, exp in zip(axes, expected):
15
+ self._check_visible(ax.get_yticklabels(), visible=exp)
16
+
17
+ def _assert_xtickslabels_visibility(self, axes, expected):
18
+ for ax, exp in zip(axes, expected):
19
+ self._check_visible(ax.get_xticklabels(), visible=exp)
20
+
21
+ @pytest.mark.parametrize(
22
+ "kwargs, expected",
23
+ [
24
+ # behavior without keyword
25
+ ({}, [True, False, True, False]),
26
+ # set sharey=True should be identical
27
+ ({"sharey": True}, [True, False, True, False]),
28
+ # sharey=False, all yticklabels should be visible
29
+ ({"sharey": False}, [True, True, True, True]),
30
+ ],
31
+ )
32
+ def test_groupby_boxplot_sharey(self, kwargs, expected):
33
+ # https://github.com/pandas-dev/pandas/issues/20968
34
+ # sharey can now be switched check whether the right
35
+ # pair of axes is turned on or off
36
+ df = DataFrame(
37
+ {
38
+ "a": [-1.43, -0.15, -3.70, -1.43, -0.14],
39
+ "b": [0.56, 0.84, 0.29, 0.56, 0.85],
40
+ "c": [0, 1, 2, 3, 1],
41
+ },
42
+ index=[0, 1, 2, 3, 4],
43
+ )
44
+ axes = df.groupby("c").boxplot(**kwargs)
45
+ self._assert_ytickslabels_visibility(axes, expected)
46
+
47
+ @pytest.mark.parametrize(
48
+ "kwargs, expected",
49
+ [
50
+ # behavior without keyword
51
+ ({}, [True, True, True, True]),
52
+ # set sharex=False should be identical
53
+ ({"sharex": False}, [True, True, True, True]),
54
+ # sharex=True, xticklabels should be visible
55
+ # only for bottom plots
56
+ ({"sharex": True}, [False, False, True, True]),
57
+ ],
58
+ )
59
+ def test_groupby_boxplot_sharex(self, kwargs, expected):
60
+ # https://github.com/pandas-dev/pandas/issues/20968
61
+ # sharex can now be switched check whether the right
62
+ # pair of axes is turned on or off
63
+
64
+ df = DataFrame(
65
+ {
66
+ "a": [-1.43, -0.15, -3.70, -1.43, -0.14],
67
+ "b": [0.56, 0.84, 0.29, 0.56, 0.85],
68
+ "c": [0, 1, 2, 3, 1],
69
+ },
70
+ index=[0, 1, 2, 3, 4],
71
+ )
72
+ axes = df.groupby("c").boxplot(**kwargs)
73
+ self._assert_xtickslabels_visibility(axes, expected)