From 272b917486ddaf90918b64caa23bb7571a7b8154 Mon Sep 17 00:00:00 2001 From: jhyching Date: Wed, 2 Oct 2024 14:00:17 +0200 Subject: [PATCH 01/10] use the bokeh get_screenshot_as_png instead and add option functionality Changes in either Selenium or the ChromeDriver causes the lower parts of charts to be cropped in the png output. The Bokeh `get_screenshot_as_png` has some smarter calculations to overcome this. Plus it also allows a scale factor to improve output resolution. --- chartify/_core/chart.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/chartify/_core/chart.py b/chartify/_core/chart.py index 4e46eba..20635c0 100644 --- a/chartify/_core/chart.py +++ b/chartify/_core/chart.py @@ -25,7 +25,7 @@ import warnings import bokeh -from bokeh.io.export import _SVG_SCRIPT, wait_until_render_complete +from bokeh.io.export import _SVG_SCRIPT, wait_until_render_complete, get_screenshot_as_png import bokeh.plotting from bokeh.embed import file_html @@ -444,7 +444,7 @@ def _initialize_webdriver(self): driver = webdriver.Chrome(options=options) return driver - def _figure_to_png(self): + def _figure_to_png(self, force_resize=True, scale_factor=1): """Convert figure object to PNG Bokeh can only save figure objects as html. To convert to PNG the HTML file is opened in a headless browser. @@ -458,14 +458,14 @@ def _figure_to_png(self): # Open html file in the browser. driver.get("file:///" + fp.name) driver.execute_script("document.body.style.margin = '0px';") - png = driver.get_screenshot_as_png() + image = get_screenshot_as_png(self.figure, driver=driver, scale_factor=scale_factor) driver.quit() fp.close() # Resize image if necessary. - image = Image.open(BytesIO(png)) - target_dimensions = (self.style.plot_width, self.style.plot_height) - if image.size != target_dimensions: - image = image.resize(target_dimensions, resample=Resampling.LANCZOS) + if force_resize: + target_dimensions = (self.style.plot_width, self.style.plot_height) + if image.size != target_dimensions: + image = image.resize(target_dimensions, resample=Resampling.LANCZOS) return image def _set_svg_backend_decorator(f): From 0780e5c473e41ec5e475ff7eea106c60dedc237b Mon Sep 17 00:00:00 2001 From: jhyching <9971934+jhyching@users.noreply.github.com> Date: Mon, 14 Oct 2024 20:03:52 -0400 Subject: [PATCH 02/10] run notebook to ensure output are the same --- examples/Examples.ipynb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/Examples.ipynb b/examples/Examples.ipynb index 5602105..8fae3d4 100644 --- a/examples/Examples.ipynb +++ b/examples/Examples.ipynb @@ -4908,7 +4908,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.8.13" + "version": "3.9.2" }, "toc": { "nav_menu": {}, From 0ea2b7fad6623f0cd825b6fb53c9e37816fbe4a8 Mon Sep 17 00:00:00 2001 From: jhyching <9971934+jhyching@users.noreply.github.com> Date: Mon, 14 Oct 2024 20:20:36 -0400 Subject: [PATCH 03/10] remove unused dependency --- chartify/_core/chart.py | 1 - 1 file changed, 1 deletion(-) diff --git a/chartify/_core/chart.py b/chartify/_core/chart.py index 20635c0..cd93062 100644 --- a/chartify/_core/chart.py +++ b/chartify/_core/chart.py @@ -20,7 +20,6 @@ from collections import OrderedDict from functools import wraps import io -from io import BytesIO import tempfile import warnings From 96c9689fa8af7d639b00443b6aff467e50f9fae0 Mon Sep 17 00:00:00 2001 From: jhyching <9971934+jhyching@users.noreply.github.com> Date: Tue, 15 Oct 2024 06:55:37 -0400 Subject: [PATCH 04/10] bump bokeh min. version to support scale_factor --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 4196e4d..9997425 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,7 +3,7 @@ Pillow>=9.1.0 # Avoid selenium bug: # https://github.com/SeleniumHQ/selenium/issues/5296 selenium>=4.0.0 -bokeh>=3.0.0 +bokeh>=3.3.4 scipy>=1.6.0 ipykernel>=6.0 ipython>=7.17.0 From 93d36ee3afde4be7689938fabf4ca9250bbb6637 Mon Sep 17 00:00:00 2001 From: jhyching <9971934+jhyching@users.noreply.github.com> Date: Tue, 15 Oct 2024 06:56:07 -0400 Subject: [PATCH 05/10] drop support for py38 --- tox.ini | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tox.ini b/tox.ini index 17f7c8e..09b6e11 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,6 @@ [tox] -envlist = py38, py39, py310 +#envlist = py38, py39, py310 +envlist = py39, py310 skipsdist = True usedevelop = True @@ -7,7 +8,7 @@ usedevelop = True python = 3.10: py310 3.9: py39 - 3.8: py38 +# 3.8: py38 [testenv] setenv = From e562e5993e872657e7787d8eb96ff410102217a8 Mon Sep 17 00:00:00 2001 From: jhyching <9971934+jhyching@users.noreply.github.com> Date: Tue, 15 Oct 2024 06:57:16 -0400 Subject: [PATCH 06/10] fix error in examples --- chartify/examples.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chartify/examples.py b/chartify/examples.py index 430e5e4..e0a7801 100644 --- a/chartify/examples.py +++ b/chartify/examples.py @@ -1268,7 +1268,7 @@ def style_color_palette_sequential(): id_vars=["time"], value_vars=data.columns[1:], value_name="y", - var_name=["grouping"], + var_name="grouping", ) # Plot the data @@ -1306,7 +1306,7 @@ def style_color_palette_diverging(): id_vars=["time"], value_vars=data.columns[1:], value_name="y", - var_name=["grouping"], + var_name="grouping", ) # Plot the data From d6e9e59ca0ef7c906e91592f5d783c6902ac8a25 Mon Sep 17 00:00:00 2001 From: jhyching <9971934+jhyching@users.noreply.github.com> Date: Tue, 15 Oct 2024 06:58:48 -0400 Subject: [PATCH 07/10] update coverage --- docs/_static/coverage.svg | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/_static/coverage.svg b/docs/_static/coverage.svg index 1c7007c..c149003 100644 --- a/docs/_static/coverage.svg +++ b/docs/_static/coverage.svg @@ -9,13 +9,13 @@ - + coverage coverage - 89% - 89% + 90% + 90% From 1664e6605850953751e574cc5d216169203fd21c Mon Sep 17 00:00:00 2001 From: Alexander Sundin Date: Tue, 15 Oct 2024 16:35:44 +0200 Subject: [PATCH 08/10] drop support for python3.8, add support for 3.11 and prep for new release --- .github/workflows/tox.yml | 2 +- CONTRIBUTING.rst | 5 +++-- HISTORY.rst | 7 +++++++ Makefile | 5 ++++- README.rst | 6 ++++-- docs/_static/coverage.svg | 6 +++--- requirements.txt | 2 +- setup.py | 4 ++-- tox.ini | 5 ++--- 9 files changed, 27 insertions(+), 15 deletions(-) diff --git a/.github/workflows/tox.yml b/.github/workflows/tox.yml index e9a1275..bdfee59 100644 --- a/.github/workflows/tox.yml +++ b/.github/workflows/tox.yml @@ -8,7 +8,7 @@ jobs: strategy: max-parallel: 5 matrix: - python-version: ["3.8", "3.9", "3.10"] + python-version: ["3.9", "3.10", "3.11"] steps: - uses: actions/checkout@v3 diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index aeb0c92..7f6b0d4 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -81,8 +81,9 @@ Ready to contribute? Here's how to set up `chartify` for local development. Now you can make your changes locally. -5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:: +5. When you're done making changes, format using make black, check that your changes pass flake8 and the tests, including testing other Python versions with tox:: + $ make black $ flake8 chartify tests $ python setup.py test or py.test $ tox @@ -106,7 +107,7 @@ Before you submit a pull request, check that it meets these guidelines: 2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list in README.rst. -3. The pull request should work for Python 3.8, 3.9 and 3.10. Check +3. The pull request should work for Python 3.9, 3.10 and 3.11. Check https://github.com/spotify/chartify/actions and make sure that the tests pass for all supported Python versions. diff --git a/HISTORY.rst b/HISTORY.rst index 391ce0b..6e764fc 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -1,6 +1,13 @@ ======= History ======= +5.0.0 (2024-10-16) + +* Drop support for Python 3.8 +* Add support for Python 3.11 +* Fixes bad cropping in png introduced by changes to chrome webdriver +* Add support and recommendation to use make black for code formatting + 4.0.5 (2023-10-12) ------------------ diff --git a/Makefile b/Makefile index 1e9ea1f..500dfdd 100644 --- a/Makefile +++ b/Makefile @@ -84,4 +84,7 @@ release-prod: clean ## package and upload a release twine upload dist/* install-from-test-pypi: - pip3 install --index-url https://test.pypi.org/simple/ chartify \ No newline at end of file + pip3 install --index-url https://test.pypi.org/simple/ chartify + +black: + black spotify_confidence tests --line-length 119 \ No newline at end of file diff --git a/README.rst b/README.rst index 1244fcb..f82620c 100644 --- a/README.rst +++ b/README.rst @@ -4,8 +4,10 @@ Chartify |status| |release| |python| |CI| .. |status| image:: https://img.shields.io/badge/Status-Beta-blue.svg -.. |release| image:: https://img.shields.io/badge/Release-4.0.3-blue.svg -.. |python| image:: https://img.shields.io/badge/Python-3.7-blue.svg +.. |release| image:: https://img.shields.io/badge/Release-5.0.0-blue.svg +.. |python| image:: https://img.shields.io/badge/Python-3.9-blue.svg +.. |python| image:: https://img.shields.io/badge/Python-3.10-blue.svg +.. |python| image:: https://img.shields.io/badge/Python-3.11-blue.svg .. |CI| image:: https://github.com/spotify/chartify/workflows/Tox/badge.svg :target: https://github.com/spotify/chartify/actions diff --git a/docs/_static/coverage.svg b/docs/_static/coverage.svg index c149003..f5af1db 100644 --- a/docs/_static/coverage.svg +++ b/docs/_static/coverage.svg @@ -9,13 +9,13 @@ - + coverage coverage - 90% - 90% + 72% + 72% diff --git a/requirements.txt b/requirements.txt index 9997425..f087e41 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,7 +3,7 @@ Pillow>=9.1.0 # Avoid selenium bug: # https://github.com/SeleniumHQ/selenium/issues/5296 selenium>=4.0.0 -bokeh>=3.3.4 +bokeh>=3.4.2 scipy>=1.6.0 ipykernel>=6.0 ipython>=7.17.0 diff --git a/setup.py b/setup.py index 38fe655..12eb854 100644 --- a/setup.py +++ b/setup.py @@ -104,13 +104,13 @@ def find_meta(meta): 'Development Status :: 4 - Beta', 'Intended Audience :: Science/Research', 'Natural Language :: English', - "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", "License :: OSI Approved :: Apache Software License" ], test_suite='tests', tests_require=test_requirements, setup_requires=setup_requirements, - python_requires='>=3.8,<4', + python_requires='>=3.9,<4', license="Apache 2") diff --git a/tox.ini b/tox.ini index 09b6e11..81d2f2b 100644 --- a/tox.ini +++ b/tox.ini @@ -1,14 +1,13 @@ [tox] -#envlist = py38, py39, py310 -envlist = py39, py310 +envlist = py39, py310, py311 skipsdist = True usedevelop = True [gh-actions] python = + 3.11: py311 3.10: py310 3.9: py39 -# 3.8: py38 [testenv] setenv = From a027bac594db75e4050d738204ef0c9c2a21774a Mon Sep 17 00:00:00 2001 From: Alexander Sundin Date: Tue, 15 Oct 2024 16:45:50 +0200 Subject: [PATCH 09/10] update build to python3.9 --- .github/workflows/python-publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/python-publish.yml b/.github/workflows/python-publish.yml index 6fb9e30..4f2e205 100644 --- a/.github/workflows/python-publish.yml +++ b/.github/workflows/python-publish.yml @@ -22,7 +22,7 @@ jobs: - name: Set up Python uses: actions/setup-python@v2 with: - python-version: '3.8' + python-version: '3.9' - name: Install dependencies run: | python -m pip install --upgrade pip From 305984ec2e190cb46c61c7c7eb13f5f3872c4fbf Mon Sep 17 00:00:00 2001 From: Alexander Sundin Date: Tue, 15 Oct 2024 16:53:02 +0200 Subject: [PATCH 10/10] fix formatting using make black --- Makefile | 2 +- chartify/_core/plot.py | 19 +- chartify/_core/radar_chart.py | 16 +- tests/test_axes.py | 123 ++-- tests/test_callout.py | 23 +- tests/test_chart.py | 165 +++-- tests/test_color_palettes_config.py | 13 +- tests/test_colors.py | 26 +- tests/test_colors_config.py | 26 +- tests/test_examples.py | 9 +- tests/test_options_config.py | 22 +- tests/test_plots.py | 926 ++++++++++++---------------- tests/test_style_settings_config.py | 12 +- 13 files changed, 607 insertions(+), 775 deletions(-) diff --git a/Makefile b/Makefile index 500dfdd..9fde468 100644 --- a/Makefile +++ b/Makefile @@ -87,4 +87,4 @@ install-from-test-pypi: pip3 install --index-url https://test.pypi.org/simple/ chartify black: - black spotify_confidence tests --line-length 119 \ No newline at end of file + black chartify tests --line-length 119 \ No newline at end of file diff --git a/chartify/_core/plot.py b/chartify/_core/plot.py index 6af7b55..cdf5c68 100644 --- a/chartify/_core/plot.py +++ b/chartify/_core/plot.py @@ -350,7 +350,9 @@ def line( else: sliced_data = data_frame[data_frame[color_column] == color_value] # Filter to only relevant columns. - sliced_data = sliced_data[[col for col in sliced_data.columns if col in (x_column, y_column, color_column)]] + sliced_data = sliced_data[ + [col for col in sliced_data.columns if col in (x_column, y_column, color_column)] + ] cast_data = self._cast_datetime_axis(sliced_data, x_column) @@ -959,9 +961,7 @@ def _sort_categories_by_value(source, categorical_columns, categorical_order_asc hierarchical_sort_cols = categorical_columns[:] for i, _ in enumerate(hierarchical_sort_cols): - row_totals["level_%s" % i] = row_totals.groupby(hierarchical_sort_cols[: i + 1])["_sum"].transform( - "sum" - ) + row_totals["level_%s" % i] = row_totals.groupby(hierarchical_sort_cols[: i + 1])["_sum"].transform("sum") row_totals = row_totals.sort_values( by=["level_%s" % i for i, _ in enumerate(hierarchical_sort_cols)], ascending=categorical_order_ascending, @@ -969,19 +969,12 @@ def _sort_categories_by_value(source, categorical_columns, categorical_order_asc return source.reindex(row_totals.index) @staticmethod - def _sort_categories( - source, - categorical_columns, - categorical_order_by, - categorical_order_ascending - ): - + def _sort_categories(source, categorical_columns, categorical_order_by, categorical_order_ascending): is_string = isinstance(categorical_order_by, str) order_length = getattr(categorical_order_by, "__len__", None) # Sort the categories if is_string and categorical_order_by == "values": - return PlotMixedTypeXY._sort_categories_by_value( - source, categorical_columns, categorical_order_ascending) + return PlotMixedTypeXY._sort_categories_by_value(source, categorical_columns, categorical_order_ascending) elif is_string and categorical_order_by == "labels": return source.sort_index(axis=0, ascending=categorical_order_ascending) # Manual sort diff --git a/chartify/_core/radar_chart.py b/chartify/_core/radar_chart.py index b8491dc..29f2a86 100644 --- a/chartify/_core/radar_chart.py +++ b/chartify/_core/radar_chart.py @@ -149,7 +149,9 @@ def text( coord_df = sliced_data.copy() coord_df[self._THETA_COLUMN] = self._get_thetas(len(coord_df)) - coord_df[[self._X_COLUMN, self._Y_COLUMN]] = self._to_xy_coords(coord_df, radius_column, self._THETA_COLUMN) + coord_df[[self._X_COLUMN, self._Y_COLUMN]] = self._to_xy_coords( + coord_df, radius_column, self._THETA_COLUMN + ) source = self._named_column_data_source(coord_df, series_name=color_value) @@ -214,7 +216,9 @@ def perimeter( coord_df = sliced_data[[radius_column]].copy() coord_df[self._THETA_COLUMN] = self._get_thetas(len(coord_df)) - coord_df[[self._X_COLUMN, self._Y_COLUMN]] = self._to_xy_coords(coord_df, radius_column, self._THETA_COLUMN) + coord_df[[self._X_COLUMN, self._Y_COLUMN]] = self._to_xy_coords( + coord_df, radius_column, self._THETA_COLUMN + ) # Add endpoint coord_df = pd.concat([coord_df, pd.DataFrame([coord_df.iloc[0]])]) @@ -267,7 +271,9 @@ def area(self, data_frame, radius_column, color_column=None, color_order=None, a coord_df = sliced_data[[radius_column]].copy() coord_df[self._THETA_COLUMN] = self._get_thetas(len(coord_df)) - coord_df[[self._X_COLUMN, self._Y_COLUMN]] = self._to_xy_coords(coord_df, radius_column, self._THETA_COLUMN) + coord_df[[self._X_COLUMN, self._Y_COLUMN]] = self._to_xy_coords( + coord_df, radius_column, self._THETA_COLUMN + ) # Add endpoint coord_df = pd.concat([coord_df, pd.DataFrame([coord_df.iloc[0]])]) @@ -337,7 +343,9 @@ def radius( coord_df = sliced_data[[radius_column]].copy() coord_df[self._THETA_COLUMN] = self._get_thetas(len(coord_df)) - coord_df[[self._X_COLUMN, self._Y_COLUMN]] = self._to_xy_coords(coord_df, radius_column, self._THETA_COLUMN) + coord_df[[self._X_COLUMN, self._Y_COLUMN]] = self._to_xy_coords( + coord_df, radius_column, self._THETA_COLUMN + ) color_value = str(color_value) if color_value is not None else color_value diff --git a/tests/test_axes.py b/tests/test_axes.py index 5f1164b..e8d1b35 100644 --- a/tests/test_axes.py +++ b/tests/test_axes.py @@ -21,95 +21,82 @@ class TestBaseAxes: def test_vertical(self): ch = chartify.Chart() - assert (ch.axes._vertical) - ch = chartify.Chart(x_axis_type='categorical') - assert (ch.axes._vertical) - ch = chartify.Chart(y_axis_type='categorical') - assert (not ch.axes._vertical) - ch = chartify.Chart(y_axis_type='density') - assert (ch.axes._vertical) - ch = chartify.Chart(x_axis_type='density') - assert (not ch.axes._vertical) - ch = chartify.Chart(x_axis_type='datetime') - assert (ch.axes._vertical) + assert ch.axes._vertical + ch = chartify.Chart(x_axis_type="categorical") + assert ch.axes._vertical + ch = chartify.Chart(y_axis_type="categorical") + assert not ch.axes._vertical + ch = chartify.Chart(y_axis_type="density") + assert ch.axes._vertical + ch = chartify.Chart(x_axis_type="density") + assert not ch.axes._vertical + ch = chartify.Chart(x_axis_type="datetime") + assert ch.axes._vertical def test_numeric_set_xaxis_range(self): ch = chartify.Chart() start, end = 0, 10 ch.axes.set_xaxis_range(start, end) - assert (ch.figure.x_range.end == end) - assert (ch.figure.x_range.start == start) + assert ch.figure.x_range.end == end + assert ch.figure.x_range.start == start def test_datetime_set_xaxis_range(self): - ch = chartify.Chart(x_axis_type='datetime') - ch.axes.set_xaxis_range( - pd.to_datetime('2018-01-01'), pd.to_datetime('2018-02-01')) - assert (ch.figure.x_range.end == 1517443200000) - assert (ch.figure.x_range.start == 1514764800000) + ch = chartify.Chart(x_axis_type="datetime") + ch.axes.set_xaxis_range(pd.to_datetime("2018-01-01"), pd.to_datetime("2018-02-01")) + assert ch.figure.x_range.end == 1517443200000 + assert ch.figure.x_range.start == 1514764800000 def test_xaxis_tick_orientation(self): data = chartify.examples.example_data() quantity_by_fruit_and_country = ( - data.groupby(['fruit', 'country', 'date'])['quantity'].sum() - .reset_index().head(10)) - ch = chartify.Chart(blank_labels=True, - x_axis_type='categorical') + data.groupby(["fruit", "country", "date"])["quantity"].sum().reset_index().head(10) + ) + ch = chartify.Chart(blank_labels=True, x_axis_type="categorical") ch.plot.bar( data_frame=quantity_by_fruit_and_country, - categorical_columns=['fruit', 'country', 'date'], - numeric_column='quantity', - color_column='fruit') + categorical_columns=["fruit", "country", "date"], + numeric_column="quantity", + color_column="fruit", + ) - ch.axes.set_xaxis_tick_orientation(['vertical', - 'horizontal', - 'diagonal']) - assert np.allclose(ch.figure.xaxis[0].major_label_orientation, - 1.5707963267948966) - assert ch.figure.xaxis[0].subgroup_label_orientation == 'parallel' - assert np.allclose(ch.figure.xaxis[0].group_label_orientation, - 0.7853981633974483) + ch.axes.set_xaxis_tick_orientation(["vertical", "horizontal", "diagonal"]) + assert np.allclose(ch.figure.xaxis[0].major_label_orientation, 1.5707963267948966) + assert ch.figure.xaxis[0].subgroup_label_orientation == "parallel" + assert np.allclose(ch.figure.xaxis[0].group_label_orientation, 0.7853981633974483) - ch.axes.set_xaxis_tick_orientation('horizontal') - assert ch.figure.xaxis[0].major_label_orientation == 'horizontal' - assert ch.figure.xaxis[0].subgroup_label_orientation == 'parallel' - assert ch.figure.xaxis[0].group_label_orientation == 'parallel' + ch.axes.set_xaxis_tick_orientation("horizontal") + assert ch.figure.xaxis[0].major_label_orientation == "horizontal" + assert ch.figure.xaxis[0].subgroup_label_orientation == "parallel" + assert ch.figure.xaxis[0].group_label_orientation == "parallel" - ch.axes.set_xaxis_tick_orientation('vertical') - assert np.allclose(ch.figure.xaxis[0].major_label_orientation, - 1.5707963267948966) - assert np.allclose(ch.figure.xaxis[0].subgroup_label_orientation, - 1.5707963267948966) - assert np.allclose(ch.figure.xaxis[0].group_label_orientation, - 1.5707963267948966) + ch.axes.set_xaxis_tick_orientation("vertical") + assert np.allclose(ch.figure.xaxis[0].major_label_orientation, 1.5707963267948966) + assert np.allclose(ch.figure.xaxis[0].subgroup_label_orientation, 1.5707963267948966) + assert np.allclose(ch.figure.xaxis[0].group_label_orientation, 1.5707963267948966) - ch = chartify.Chart(blank_labels=True, - y_axis_type='categorical') + ch = chartify.Chart(blank_labels=True, y_axis_type="categorical") ch.plot.bar( data_frame=quantity_by_fruit_and_country, - categorical_columns=['fruit', 'country', 'date'], - numeric_column='quantity', - color_column='fruit') + categorical_columns=["fruit", "country", "date"], + numeric_column="quantity", + color_column="fruit", + ) - ch.axes.set_yaxis_tick_orientation(['vertical', - 'vertical', - 'diagonal']) - assert np.allclose(ch.figure.yaxis[0].major_label_orientation, - 1.5707963267948966) - assert ch.figure.yaxis[0].subgroup_label_orientation == 'parallel' - assert np.allclose(ch.figure.yaxis[0].group_label_orientation, - 0.7853981633974483) + ch.axes.set_yaxis_tick_orientation(["vertical", "vertical", "diagonal"]) + assert np.allclose(ch.figure.yaxis[0].major_label_orientation, 1.5707963267948966) + assert ch.figure.yaxis[0].subgroup_label_orientation == "parallel" + assert np.allclose(ch.figure.yaxis[0].group_label_orientation, 0.7853981633974483) - ch.axes.set_yaxis_tick_orientation('horizontal') - assert ch.figure.yaxis[0].major_label_orientation == 'horizontal' - assert ch.figure.yaxis[0].subgroup_label_orientation == 'normal' - assert ch.figure.yaxis[0].group_label_orientation == 'normal' + ch.axes.set_yaxis_tick_orientation("horizontal") + assert ch.figure.yaxis[0].major_label_orientation == "horizontal" + assert ch.figure.yaxis[0].subgroup_label_orientation == "normal" + assert ch.figure.yaxis[0].group_label_orientation == "normal" - quantity_by_date = data.groupby('date')['quantity'].sum().reset_index() - ch = chartify.Chart(x_axis_type='datetime') - ch.plot.line(quantity_by_date, 'date', 'quantity') - assert ch.figure.xaxis[0].major_label_orientation == 'horizontal' + quantity_by_date = data.groupby("date")["quantity"].sum().reset_index() + ch = chartify.Chart(x_axis_type="datetime") + ch.plot.line(quantity_by_date, "date", "quantity") + assert ch.figure.xaxis[0].major_label_orientation == "horizontal" - ch.axes.set_xaxis_tick_orientation('vertical') - assert np.allclose(ch.figure.xaxis[0].major_label_orientation, - 1.5707963267948966) + ch.axes.set_xaxis_tick_orientation("vertical") + assert np.allclose(ch.figure.xaxis[0].major_label_orientation, 1.5707963267948966) diff --git a/tests/test_callout.py b/tests/test_callout.py index 5f60053..5ac9ef3 100644 --- a/tests/test_callout.py +++ b/tests/test_callout.py @@ -17,24 +17,21 @@ class TestBaseAxes: - def test_datetime_callouts(self): data = chartify.examples.example_data() # Sum price grouped by date - price_by_date = ( - data.groupby('date')['total_price'].sum() - .reset_index() # Move 'date' from index to column - ) + price_by_date = data.groupby("date")["total_price"].sum().reset_index() # Move 'date' from index to column # Plot the data - ch = chartify.Chart(blank_labels=True, x_axis_type='datetime') + ch = chartify.Chart(blank_labels=True, x_axis_type="datetime") ch.plot.line( # Data must be sorted by x column - data_frame=price_by_date.sort_values('date'), - x_column='date', - y_column='total_price') - ch.callout.line('2017-08-01', orientation='height', line_width=10) - ch.callout.line_segment('2017-08-01', 10, '2017-09-05', 20) - ch.callout.box(10, 0, '2017-05-01', '2017-05-05') - ch.callout.text('text', '2017-05-01', 10) + data_frame=price_by_date.sort_values("date"), + x_column="date", + y_column="total_price", + ) + ch.callout.line("2017-08-01", orientation="height", line_width=10) + ch.callout.line_segment("2017-08-01", 10, "2017-09-05", 20) + ch.callout.box(10, 0, "2017-05-01", "2017-05-05") + ch.callout.text("text", "2017-05-01", 10) diff --git a/tests/test_chart.py b/tests/test_chart.py index 25ab7a6..6d835bd 100644 --- a/tests/test_chart.py +++ b/tests/test_chart.py @@ -23,80 +23,71 @@ class TestLegend: def test_set_legend_location(self): data = chartify.examples.example_data() - ch = chartify.Chart(x_axis_type='datetime') + ch = chartify.Chart(x_axis_type="datetime") ch.plot.scatter( - data_frame=data, - x_column='date', - y_column='unit_price', - size_column='quantity', - color_column='fruit') - ch.set_legend_location('top_right') - assert (ch.figure.legend[0].location == 'top_right') - assert (ch.figure.legend[0].orientation == 'horizontal') - ch.set_legend_location('top_left', 'vertical') - assert (ch.figure.legend[0].location == 'top_left') - assert (ch.figure.legend[0].orientation == 'vertical') - ch.set_legend_location('outside_bottom') - ch = chartify.Chart(x_axis_type='datetime') + data_frame=data, x_column="date", y_column="unit_price", size_column="quantity", color_column="fruit" + ) + ch.set_legend_location("top_right") + assert ch.figure.legend[0].location == "top_right" + assert ch.figure.legend[0].orientation == "horizontal" + ch.set_legend_location("top_left", "vertical") + assert ch.figure.legend[0].location == "top_left" + assert ch.figure.legend[0].orientation == "vertical" + ch.set_legend_location("outside_bottom") + ch = chartify.Chart(x_axis_type="datetime") ch.plot.scatter( - data_frame=data, - x_column='date', - y_column='unit_price', - size_column='quantity', - color_column='fruit') + data_frame=data, x_column="date", y_column="unit_price", size_column="quantity", color_column="fruit" + ) ch.set_legend_location(None) - assert (ch.figure.legend[0].visible is False) + assert ch.figure.legend[0].visible is False def test_reverse_vertical_legend_area(self): data = chartify.examples.example_data() total_quantity_by_month_and_fruit = ( - data.groupby([data['date'] + pd.offsets.MonthBegin(-1), 'fruit']) - ['quantity'].sum() - .reset_index().rename(columns={'date': 'month'}) - .sort_values('month')) + data.groupby([data["date"] + pd.offsets.MonthBegin(-1), "fruit"])["quantity"] + .sum() + .reset_index() + .rename(columns={"date": "month"}) + .sort_values("month") + ) # Plot the data - ch = chartify.Chart(blank_labels=True, x_axis_type='datetime') + ch = chartify.Chart(blank_labels=True, x_axis_type="datetime") ch.plot.area( data_frame=total_quantity_by_month_and_fruit, - x_column='month', - y_column='quantity', - color_column='fruit', - stacked=True) - labels = [item.label['value'] for item in ch.figure.legend[0].items] - assert np.array_equal(labels, - ['Apple', 'Banana', 'Grape', 'Orange']) - ch.set_legend_location('top_right', 'vertical') - labels = [item.label['value'] for item in ch.figure.legend[0].items] - assert np.array_equal(labels, - ['Orange', 'Grape', 'Banana', 'Apple']) + x_column="month", + y_column="quantity", + color_column="fruit", + stacked=True, + ) + labels = [item.label["value"] for item in ch.figure.legend[0].items] + assert np.array_equal(labels, ["Apple", "Banana", "Grape", "Orange"]) + ch.set_legend_location("top_right", "vertical") + labels = [item.label["value"] for item in ch.figure.legend[0].items] + assert np.array_equal(labels, ["Orange", "Grape", "Banana", "Apple"]) def test_reverse_vertical_legend_bar(self): data = chartify.examples.example_data() - quantity_by_fruit_and_country = ( - data.groupby(['fruit', 'country'])['quantity'].sum().reset_index()) + quantity_by_fruit_and_country = data.groupby(["fruit", "country"])["quantity"].sum().reset_index() - ch = chartify.Chart(blank_labels=True, - x_axis_type='categorical') + ch = chartify.Chart(blank_labels=True, x_axis_type="categorical") ch.plot.bar_stacked( data_frame=quantity_by_fruit_and_country, - categorical_columns=['fruit'], - numeric_column='quantity', - stack_column='country', - normalize=False) - labels = [item.label['value'] for item in ch.figure.legend[0].items] - assert np.array_equal(labels, - ['BR', 'CA', 'GB', 'JP', 'US']) - ch.set_legend_location('top_right', 'vertical') - labels = [item.label['value'] for item in ch.figure.legend[0].items] - assert np.array_equal(labels, - ['US', 'JP', 'GB', 'CA', 'BR']) + categorical_columns=["fruit"], + numeric_column="quantity", + stack_column="country", + normalize=False, + ) + labels = [item.label["value"] for item in ch.figure.legend[0].items] + assert np.array_equal(labels, ["BR", "CA", "GB", "JP", "US"]) + ch.set_legend_location("top_right", "vertical") + labels = [item.label["value"] for item in ch.figure.legend[0].items] + assert np.array_equal(labels, ["US", "JP", "GB", "CA", "BR"]) def test_legen_with_grouping_and_color(self): - df = pd.DataFrame.from_dict({"data": [1, 1, 2, 2, 3, 3], - "group": ["a", "a", "a", "b", "b", "b"]}) - ch = chartify.Chart(x_axis_type='categorical') + df = pd.DataFrame.from_dict({"data": [1, 1, 2, 2, 3, 3], "group": ["a", "a", "a", "b", "b", "b"]}) + ch = chartify.Chart(x_axis_type="categorical") ch.plot.scatter( data_frame=df, categorical_columns="group", @@ -106,19 +97,19 @@ def test_legen_with_grouping_and_color(self): class TestChart: - def setup_method(self): data = chartify.examples.example_data() - data = data.sort_values(['date', 'fruit']) - color_order = data['fruit'].unique() - ch = chartify.Chart(x_axis_type='datetime') + data = data.sort_values(["date", "fruit"]) + color_order = data["fruit"].unique() + ch = chartify.Chart(x_axis_type="datetime") ch.plot.scatter( data_frame=data, - x_column='date', - y_column='unit_price', - size_column='quantity', - color_column='fruit', - color_order=color_order) + x_column="date", + y_column="unit_price", + size_column="quantity", + color_column="fruit", + color_order=color_order, + ) self.chart = ch self.data = data self.color_order = color_order @@ -126,16 +117,16 @@ def setup_method(self): def test_data(self): data = self.data color_order = self.color_order - assert (np.array_equal( - list(filter(lambda x: x['fruit'][0] == color_order[0], - self.chart.data))[0]['unit_price'], - data[data['fruit'] == color_order[0]]['unit_price'].values)) + assert np.array_equal( + list(filter(lambda x: x["fruit"][0] == color_order[0], self.chart.data))[0]["unit_price"], + data[data["fruit"] == color_order[0]]["unit_price"].values, + ) def test_save(self, tmpdir): ch = self.chart - base_filename = 'test_save' - for filetype in ('png', 'svg', 'html'): - filename = tmpdir.join(base_filename + '.' + filetype) + base_filename = "test_save" + for filetype in ("png", "svg", "html"): + filename = tmpdir.join(base_filename + "." + filetype) try: ch.save(filename=str(filename), format=filetype) # Occurs if chromedriver is not found @@ -144,23 +135,21 @@ def test_save(self, tmpdir): class TestSecondYChart: - def setup_method(self): - self.data = pd.DataFrame({ - 'category1': ['a', 'b', 'a', 'b', 'a', 'b'], - 'number1': [1, 1, 2, 2, 3, 3], - 'number2': [5, 4, 10, -3, 0, -10], - 'datetimes': [ - '2017-01-01', '2017-01-01', '2017-01-02', '2017-01-02', - '2017-01-03', '2017-01-03' - ], - }) + self.data = pd.DataFrame( + { + "category1": ["a", "b", "a", "b", "a", "b"], + "number1": [1, 1, 2, 2, 3, 3], + "number2": [5, 4, 10, -3, 0, -10], + "datetimes": ["2017-01-01", "2017-01-01", "2017-01-02", "2017-01-02", "2017-01-03", "2017-01-03"], + } + ) def test_init(self): with pytest.raises(ValueError): - chartify.Chart(y_axis_type='categorical', second_y_axis=True) - ch = chartify.Chart(y_axis_type='linear', second_y_axis=True) - assert ch._second_y_axis_type == 'linear' + chartify.Chart(y_axis_type="categorical", second_y_axis=True) + ch = chartify.Chart(y_axis_type="linear", second_y_axis=True) + assert ch._second_y_axis_type == "linear" def test_axes(self): ch = chartify.Chart(second_y_axis=True) @@ -170,10 +159,8 @@ def test_axes(self): def test_single_numeric_line(self): """Single line test""" - single_line = self.data[self.data['category1'] == 'a'] + single_line = self.data[self.data["category1"] == "a"] ch = chartify.Chart(second_y_axis=True) - ch.second_axis.plot.line(single_line, - x_column='number1', - y_column='number2') - assert (np.array_equal(ch.data[0]['number1'], [1., 2., 3.])) - assert (np.array_equal(ch.data[0]['number2'], [5, 10, 0])) + ch.second_axis.plot.line(single_line, x_column="number1", y_column="number2") + assert np.array_equal(ch.data[0]["number1"], [1.0, 2.0, 3.0]) + assert np.array_equal(ch.data[0]["number2"], [5, 10, 0]) diff --git a/tests/test_color_palettes_config.py b/tests/test_color_palettes_config.py index a474ad4..998909b 100644 --- a/tests/test_color_palettes_config.py +++ b/tests/test_color_palettes_config.py @@ -17,7 +17,7 @@ import importlib import os -COLOR_PALETTES_CONFIG = '''\ +COLOR_PALETTES_CONFIG = """\ - - - '#5ff550' - '#fae62d' - '#f037a5' @@ -28,24 +28,25 @@ - '#eb1e32' - categorical - Baz Quux -''' +""" EXPECTED_COLOR_PALETTES = { - 'foo bar': ['#5ff550', '#fae62d', '#f037a5'], - 'baz quux': ['#ffc864', '#ffcdd2', '#eb1e32'], + "foo bar": ["#5ff550", "#fae62d", "#f037a5"], + "baz quux": ["#ffc864", "#ffcdd2", "#eb1e32"], } def test_color_palettes_config(monkeypatch, tmpdir): - f = tmpdir.join('color_palettes_config.yaml') + f = tmpdir.join("color_palettes_config.yaml") f.write(COLOR_PALETTES_CONFIG) # XXX (dano): CHARTIFY_CONFIG_DIR must end with / - monkeypatch.setenv('CHARTIFY_CONFIG_DIR', os.path.join(str(tmpdir), '')) + monkeypatch.setenv("CHARTIFY_CONFIG_DIR", os.path.join(str(tmpdir), "")) # reload modules to reload configuration import chartify._core.options import chartify._core.colors + importlib.reload(chartify._core.options) importlib.reload(chartify._core.colors) diff --git a/tests/test_colors.py b/tests/test_colors.py index ae85d51..171490d 100644 --- a/tests/test_colors.py +++ b/tests/test_colors.py @@ -20,8 +20,8 @@ class TestColor: def test_color(self): - color = chartify._core.colors.Color('red') - assert (color.hex == '#f00') + color = chartify._core.colors.Color("red") + assert color.hex == "#f00" class TestColorPalettes: @@ -29,20 +29,18 @@ def test_getitem(self): # reload configuration importlib.reload(chartify) - palette = chartify.color_palettes['Category20'] - assert (isinstance(palette, chartify._core.colors.ColorPalette)) - assert (palette.name == 'Category20') + palette = chartify.color_palettes["Category20"] + assert isinstance(palette, chartify._core.colors.ColorPalette) + assert palette.name == "Category20" def test_create_palette(self): - chartify.color_palettes.create_palette(['white', 'black', '#fff000'], - 'sequential', - 'New') - new_palette = chartify.color_palettes['New'] - assert new_palette.to_hex_list() == ['#ffffff', '#000000', '#fff000'] + chartify.color_palettes.create_palette(["white", "black", "#fff000"], "sequential", "New") + new_palette = chartify.color_palettes["New"] + assert new_palette.to_hex_list() == ["#ffffff", "#000000", "#fff000"] def test_shift_palette(self): - palette = chartify.color_palettes['Greys'] + palette = chartify.color_palettes["Greys"] assert np.array_equal( - palette.shift_palette('red', 20).to_hex_list(), - ['#e0afaf', '#ca9999', '#aa7979', '#8e5d5d', - '#734242', '#4f1e1e', '#310000']) + palette.shift_palette("red", 20).to_hex_list(), + ["#e0afaf", "#ca9999", "#aa7979", "#8e5d5d", "#734242", "#4f1e1e", "#310000"], + ) diff --git a/tests/test_colors_config.py b/tests/test_colors_config.py index 3b970c6..595f891 100644 --- a/tests/test_colors_config.py +++ b/tests/test_colors_config.py @@ -17,7 +17,7 @@ import importlib import os -COLORS_CONFIG = '''\ +COLORS_CONFIG = """\ ? !!python/tuple - 0 - 100 @@ -33,32 +33,34 @@ - 230 - 140 : Baz -''' +""" EXPECTED_COLORS = { - 'style.color_palette_categorical': 'My Palette', - 'style.color_palette_sequential': 'Midnight Orange Sequential', - 'style.color_palette_diverging': 'Midnight Orange Diverging', - 'style.color_palette_accent': 'My Palette', - 'style.color_palette_accent_default_color': 'light grey', + "style.color_palette_categorical": "My Palette", + "style.color_palette_sequential": "Midnight Orange Sequential", + "style.color_palette_diverging": "Midnight Orange Diverging", + "style.color_palette_accent": "My Palette", + "style.color_palette_accent_default_color": "light grey", } def test_colors_config(monkeypatch, tmpdir): - f = tmpdir.join('colors_config.yaml') + f = tmpdir.join("colors_config.yaml") f.write(COLORS_CONFIG) # XXX (dano): CHARTIFY_CONFIG_DIR must end with / - monkeypatch.setenv('CHARTIFY_CONFIG_DIR', os.path.join(str(tmpdir), '')) + monkeypatch.setenv("CHARTIFY_CONFIG_DIR", os.path.join(str(tmpdir), "")) # reload modules to reload configuration import chartify._core.options import chartify._core.colors import chartify._core.style + importlib.reload(chartify._core.options) importlib.reload(chartify._core.colors) import chartify._core.colour as colour - assert colour.COLOR_NAME_TO_RGB['foo'] == (0, 100, 80) - assert colour.COLOR_NAME_TO_RGB['bar'] == (25, 20, 20) - assert colour.COLOR_NAME_TO_RGB['baz'] == (25, 230, 140) + + assert colour.COLOR_NAME_TO_RGB["foo"] == (0, 100, 80) + assert colour.COLOR_NAME_TO_RGB["bar"] == (25, 20, 20) + assert colour.COLOR_NAME_TO_RGB["baz"] == (25, 230, 140) diff --git a/tests/test_examples.py b/tests/test_examples.py index a8e555a..29d9633 100644 --- a/tests/test_examples.py +++ b/tests/test_examples.py @@ -23,12 +23,11 @@ def test_examples(): # reload configuration importlib.reload(chartify) - excluded_examples = ['chart_show'] + excluded_examples = ["chart_show"] public_examples = [ - attr for attr in dir(chartify.examples) if - callable(getattr(chartify.examples, attr)) - and not attr.startswith("_") - and attr not in excluded_examples + attr + for attr in dir(chartify.examples) + if callable(getattr(chartify.examples, attr)) and not attr.startswith("_") and attr not in excluded_examples ] # Disable chart rendering chartify.examples._OUTPUT_FORMAT = None diff --git a/tests/test_options_config.py b/tests/test_options_config.py index 1cc5368..7db1e1b 100644 --- a/tests/test_options_config.py +++ b/tests/test_options_config.py @@ -17,7 +17,7 @@ import importlib import os -OPTIONS_CONFIG = '''\ +OPTIONS_CONFIG = """\ !!python/object/apply:collections.OrderedDict - - - style.color_palette_categorical - !!python/object:chartify._core.options.OptionValue @@ -34,28 +34,28 @@ - - style.color_palette_accent_default_color - !!python/object:chartify._core.options.OptionValue value: light grey -''' +""" EXPECTED_CONFIG = { - 'style.color_palette_categorical': 'My Palette', - 'style.color_palette_sequential': 'Midnight Orange Sequential', - 'style.color_palette_diverging': 'Midnight Orange Diverging', - 'style.color_palette_accent': 'My Palette', - 'style.color_palette_accent_default_color': 'light grey', + "style.color_palette_categorical": "My Palette", + "style.color_palette_sequential": "Midnight Orange Sequential", + "style.color_palette_diverging": "Midnight Orange Diverging", + "style.color_palette_accent": "My Palette", + "style.color_palette_accent_default_color": "light grey", } def test_options_config(monkeypatch, tmpdir): - f = tmpdir.join('options_config.yaml') + f = tmpdir.join("options_config.yaml") f.write(OPTIONS_CONFIG) # XXX (dano): CHARTIFY_CONFIG_DIR must end with / - monkeypatch.setenv('CHARTIFY_CONFIG_DIR', os.path.join(str(tmpdir), '')) + monkeypatch.setenv("CHARTIFY_CONFIG_DIR", os.path.join(str(tmpdir), "")) # reload modules to reload configuration import chartify._core.options + options = importlib.reload(chartify._core.options) - config = {key: options.options.get_option(key) - for key in EXPECTED_CONFIG} + config = {key: options.options.get_option(key) for key in EXPECTED_CONFIG} assert config == EXPECTED_CONFIG diff --git a/tests/test_plots.py b/tests/test_plots.py index ec38fcc..b3cf4a7 100644 --- a/tests/test_plots.py +++ b/tests/test_plots.py @@ -33,210 +33,173 @@ def chart_data(chart_object, series_name): Returns: Dictionary populated with data from the chart. """ - cannonical_series_name = ( - chart_object.plot._cannonical_series_name(series_name)) + cannonical_series_name = chart_object.plot._cannonical_series_name(series_name) return chart_object.figure.select(cannonical_series_name)[0].data def chart_color_mapper(chart_object): - return chart_object.figure.select( - bokeh.models.mappers.CategoricalColorMapper)[0] + return chart_object.figure.select(bokeh.models.mappers.CategoricalColorMapper)[0] class TestHeatmap: def setup_method(self): - self.data = pd.DataFrame({ - 'category1': ['a', 'a', 'b', 'b'], - 'category2': [1, 2, 1, 2], - 'values': [1., 2., 3., 4.] - }) + self.data = pd.DataFrame( + {"category1": ["a", "a", "b", "b"], "category2": [1, 2, 1, 2], "values": [1.0, 2.0, 3.0, 4.0]} + ) def test_heatmap(self): """Area plot tests""" - ch = chartify.Chart( - x_axis_type='categorical', y_axis_type='categorical') - ch.plot.heatmap( - self.data, - x_column='category1', - y_column='category2', - color_column='values') - assert (np.array_equal( - chart_data(ch, '')['category1'], ['a', 'a', 'b', 'b'])) - assert (np.array_equal( - chart_data(ch, '')['category2'], ['1', '2', '1', '2'])) - assert (np.array_equal(chart_data(ch, '')['values'], [1., 2., 3., 4.])) + ch = chartify.Chart(x_axis_type="categorical", y_axis_type="categorical") + ch.plot.heatmap(self.data, x_column="category1", y_column="category2", color_column="values") + assert np.array_equal(chart_data(ch, "")["category1"], ["a", "a", "b", "b"]) + assert np.array_equal(chart_data(ch, "")["category2"], ["1", "2", "1", "2"]) + assert np.array_equal(chart_data(ch, "")["values"], [1.0, 2.0, 3.0, 4.0]) class TestLine: def setup_method(self): self.data = pd.DataFrame( { - 'category1': ['a', 'b', 'a', 'b', 'a', 'b'], - 'number1': [1, 1, 2, 2, 3, 3], - 'number2': [5, 4, 10, -3, 0, -10], - 'datetimes': [ - '2017-01-01', '2017-01-01', '2017-01-02', '2017-01-02', - '2017-01-03', '2017-01-03' - ], + "category1": ["a", "b", "a", "b", "a", "b"], + "number1": [1, 1, 2, 2, 3, 3], + "number2": [5, 4, 10, -3, 0, -10], + "datetimes": ["2017-01-01", "2017-01-01", "2017-01-02", "2017-01-02", "2017-01-03", "2017-01-03"], } ) def test_single_numeric_line(self): """Single line test""" - single_line = self.data[self.data['category1'] == 'a'] + single_line = self.data[self.data["category1"] == "a"] ch = chartify.Chart() - ch.plot.line(single_line, x_column='number1', y_column='number2') - assert (np.array_equal(chart_data(ch, '')['number1'], [1., 2., 3.])) - assert (np.array_equal(chart_data(ch, '')['number2'], [5, 10, 0])) + ch.plot.line(single_line, x_column="number1", y_column="number2") + assert np.array_equal(chart_data(ch, "")["number1"], [1.0, 2.0, 3.0]) + assert np.array_equal(chart_data(ch, "")["number2"], [5, 10, 0]) def test_multi_numeric_line(self): """Single line test""" ch = chartify.Chart() - ch.plot.line( - self.data, - x_column='number1', - y_column='number2', - color_column='category1') - assert (np.array_equal(chart_data(ch, 'a')['number1'], [1., 2., 3.])) - assert (np.array_equal(chart_data(ch, 'a')['number2'], [5, 10, 0])) - assert (np.array_equal(chart_data(ch, 'b')['number1'], [1., 2., 3.])) - assert (np.array_equal(chart_data(ch, 'b')['number2'], [4, -3, -10])) + ch.plot.line(self.data, x_column="number1", y_column="number2", color_column="category1") + assert np.array_equal(chart_data(ch, "a")["number1"], [1.0, 2.0, 3.0]) + assert np.array_equal(chart_data(ch, "a")["number2"], [5, 10, 0]) + assert np.array_equal(chart_data(ch, "b")["number1"], [1.0, 2.0, 3.0]) + assert np.array_equal(chart_data(ch, "b")["number2"], [4, -3, -10]) def test_single_datetime_line(self): """Single line test""" - data = pd.DataFrame({ - 'number': [1, 10, -10, 0], - 'datetimes': - ['2017-01-01', '2017-01-02', '2017-01-03', '2017-01-04'], - }) - ch = chartify.Chart(x_axis_type='datetime') - ch.plot.line(data, x_column='datetimes', y_column='number') - assert (np.array_equal( - chart_data(ch, '')['datetimes'], - pd.date_range('2017-01-01', '2017-01-04'))) - assert (np.array_equal(chart_data(ch, '')['number'], [1, 10, -10, 0])) + data = pd.DataFrame( + { + "number": [1, 10, -10, 0], + "datetimes": ["2017-01-01", "2017-01-02", "2017-01-03", "2017-01-04"], + } + ) + ch = chartify.Chart(x_axis_type="datetime") + ch.plot.line(data, x_column="datetimes", y_column="number") + assert np.array_equal(chart_data(ch, "")["datetimes"], pd.date_range("2017-01-01", "2017-01-04")) + assert np.array_equal(chart_data(ch, "")["number"], [1, 10, -10, 0]) class TestScatter: def setup_method(self): - self.data = pd.DataFrame({ - 'category1': ['a', 'b', 'a', 'b', 'a', 'b'], - 'number1': [1, 1, 2, 2, 3, 3], - 'number2': [5, 4, 10, -3, 0, -10], - 'datetimes': [ - '2017-01-01', '2017-01-01', '2017-01-02', '2017-01-02', - '2017-01-03', '2017-01-03' - ], - }) + self.data = pd.DataFrame( + { + "category1": ["a", "b", "a", "b", "a", "b"], + "number1": [1, 1, 2, 2, 3, 3], + "number2": [5, 4, 10, -3, 0, -10], + "datetimes": ["2017-01-01", "2017-01-01", "2017-01-02", "2017-01-02", "2017-01-03", "2017-01-03"], + } + ) def test_single_numeric_scatter(self): """Single scatter test""" - single_scatter = self.data[self.data['category1'] == 'a'] + single_scatter = self.data[self.data["category1"] == "a"] ch = chartify.Chart() - ch.plot.scatter(single_scatter, x_column='number1', y_column='number2') - assert (np.array_equal(chart_data(ch, '')['number1'], [1., 2., 3.])) - assert (np.array_equal(chart_data(ch, '')['number2'], [5, 10, 0])) + ch.plot.scatter(single_scatter, x_column="number1", y_column="number2") + assert np.array_equal(chart_data(ch, "")["number1"], [1.0, 2.0, 3.0]) + assert np.array_equal(chart_data(ch, "")["number2"], [5, 10, 0]) def test_multi_numeric_scatter(self): """Multi scatter test""" ch = chartify.Chart() - ch.plot.scatter( - self.data, - x_column='number1', - y_column='number2', - color_column='category1') - assert (np.array_equal(chart_data(ch, 'a')['number1'], [1., 2., 3.])) - assert (np.array_equal(chart_data(ch, 'a')['number2'], [5, 10, 0])) - assert (np.array_equal(chart_data(ch, 'b')['number1'], [1., 2., 3.])) - assert (np.array_equal(chart_data(ch, 'b')['number2'], [4, -3, -10])) + ch.plot.scatter(self.data, x_column="number1", y_column="number2", color_column="category1") + assert np.array_equal(chart_data(ch, "a")["number1"], [1.0, 2.0, 3.0]) + assert np.array_equal(chart_data(ch, "a")["number2"], [5, 10, 0]) + assert np.array_equal(chart_data(ch, "b")["number1"], [1.0, 2.0, 3.0]) + assert np.array_equal(chart_data(ch, "b")["number2"], [4, -3, -10]) def test_single_datetime_scatter(self): """Single datetime scatter test""" - data = pd.DataFrame({ - 'number': [1, 10, -10, 0], - 'datetimes': - ['2017-01-01', '2017-01-02', '2017-01-03', '2017-01-04'], - }) - ch = chartify.Chart(x_axis_type='datetime') - ch.plot.scatter(data, x_column='datetimes', y_column='number') - assert (np.array_equal( - chart_data(ch, '')['datetimes'], - pd.date_range('2017-01-01', '2017-01-04'))) - assert (np.array_equal(chart_data(ch, '')['number'], [1, 10, -10, 0])) + data = pd.DataFrame( + { + "number": [1, 10, -10, 0], + "datetimes": ["2017-01-01", "2017-01-02", "2017-01-03", "2017-01-04"], + } + ) + ch = chartify.Chart(x_axis_type="datetime") + ch.plot.scatter(data, x_column="datetimes", y_column="number") + assert np.array_equal(chart_data(ch, "")["datetimes"], pd.date_range("2017-01-01", "2017-01-04")) + assert np.array_equal(chart_data(ch, "")["number"], [1, 10, -10, 0]) class TestText: def setup_method(self): - self.data = pd.DataFrame({ - 'text': ['a', 'b', 'a', 'b', 'a', 'b'], - 'number1': [1, 1, 2, 2, 3, 3], - 'number2': [5, 4, 10, -3, 0, -10], - 'datetimes': [ - '2017-01-01', '2017-01-01', '2017-01-02', '2017-01-02', - '2017-01-03', '2017-01-03' - ], - }) + self.data = pd.DataFrame( + { + "text": ["a", "b", "a", "b", "a", "b"], + "number1": [1, 1, 2, 2, 3, 3], + "number2": [5, 4, 10, -3, 0, -10], + "datetimes": ["2017-01-01", "2017-01-01", "2017-01-02", "2017-01-02", "2017-01-03", "2017-01-03"], + } + ) def test_single_numeric_text(self): """Single line test""" - single_text = self.data[self.data['text'] == 'a'] + single_text = self.data[self.data["text"] == "a"] ch = chartify.Chart() - ch.plot.text( - single_text, - x_column='number1', - y_column='number2', - text_column='text') - assert (np.array_equal(chart_data(ch, '')['number1'], [1., 2., 3.])) - assert (np.array_equal(chart_data(ch, '')['number2'], [5, 10, 0])) - assert (np.array_equal(chart_data(ch, '')['text'], ['a', 'a', 'a'])) + ch.plot.text(single_text, x_column="number1", y_column="number2", text_column="text") + assert np.array_equal(chart_data(ch, "")["number1"], [1.0, 2.0, 3.0]) + assert np.array_equal(chart_data(ch, "")["number2"], [5, 10, 0]) + assert np.array_equal(chart_data(ch, "")["text"], ["a", "a", "a"]) def test_multi_numeric_text(self): """Single line test""" ch = chartify.Chart() - ch.plot.text( - self.data, - x_column='number1', - y_column='number2', - text_column='text', - color_column='text') - assert (np.array_equal(chart_data(ch, 'a')['number1'], [1., 2., 3.])) - assert (np.array_equal(chart_data(ch, 'a')['number2'], [5, 10, 0])) - assert (np.array_equal(chart_data(ch, 'a')['text'], ['a', 'a', 'a'])) - assert (np.array_equal(chart_data(ch, 'b')['number1'], [1., 2., 3.])) - assert (np.array_equal(chart_data(ch, 'b')['number2'], [4, -3, -10])) - assert (np.array_equal(chart_data(ch, 'b')['text'], ['b', 'b', 'b'])) + ch.plot.text(self.data, x_column="number1", y_column="number2", text_column="text", color_column="text") + assert np.array_equal(chart_data(ch, "a")["number1"], [1.0, 2.0, 3.0]) + assert np.array_equal(chart_data(ch, "a")["number2"], [5, 10, 0]) + assert np.array_equal(chart_data(ch, "a")["text"], ["a", "a", "a"]) + assert np.array_equal(chart_data(ch, "b")["number1"], [1.0, 2.0, 3.0]) + assert np.array_equal(chart_data(ch, "b")["number2"], [4, -3, -10]) + assert np.array_equal(chart_data(ch, "b")["text"], ["b", "b", "b"]) def test_single_datetime_text(self): """Single line test""" - data = pd.DataFrame({ - 'number': [1, 10, -10, 0], - 'datetimes': - ['2017-01-01', '2017-01-02', '2017-01-03', '2017-01-04'], - 'text': ['a', 'b', 'a', 'b'], - }) - ch = chartify.Chart(x_axis_type='datetime') - ch.plot.text( - data, x_column='datetimes', y_column='number', text_column='text') - assert (np.array_equal( - chart_data(ch, '')['datetimes'], - pd.date_range('2017-01-01', '2017-01-04'))) - assert (np.array_equal(chart_data(ch, '')['number'], [1, 10, -10, 0])) - assert (np.array_equal( - chart_data(ch, '')['text'], ['a', 'b', 'a', 'b'])) + data = pd.DataFrame( + { + "number": [1, 10, -10, 0], + "datetimes": ["2017-01-01", "2017-01-02", "2017-01-03", "2017-01-04"], + "text": ["a", "b", "a", "b"], + } + ) + ch = chartify.Chart(x_axis_type="datetime") + ch.plot.text(data, x_column="datetimes", y_column="number", text_column="text") + assert np.array_equal(chart_data(ch, "")["datetimes"], pd.date_range("2017-01-01", "2017-01-04")) + assert np.array_equal(chart_data(ch, "")["number"], [1, 10, -10, 0]) + assert np.array_equal(chart_data(ch, "")["text"], ["a", "b", "a", "b"]) class CategoricalTextTest: def test_float_labels(self): label_test = pd.DataFrame( - {'value': [.20, .40, .05, .6, .2, .8], - 'bucket': [1, 2, 3, 1, 2, 3], - 'platform': ['android', 'android', 'android', 'ios', 'ios', 'ios'], - 'value2': [1.0, 2.0, 3, 6., 8., 10.]}) - ch = chartify.Chart(x_axis_type='categorical') - ch.plot.text(label_test, ['bucket', 'platform'], 'value', 'value') - assert (np.array_equal( - ch.data[0]['text_column'].values, - ['0.8', '0.05', '0.6', '0.2', '0.4', '0.2'])) + { + "value": [0.20, 0.40, 0.05, 0.6, 0.2, 0.8], + "bucket": [1, 2, 3, 1, 2, 3], + "platform": ["android", "android", "android", "ios", "ios", "ios"], + "value2": [1.0, 2.0, 3, 6.0, 8.0, 10.0], + } + ) + ch = chartify.Chart(x_axis_type="categorical") + ch.plot.text(label_test, ["bucket", "platform"], "value", "value") + assert np.array_equal(ch.data[0]["text_column"].values, ["0.8", "0.05", "0.6", "0.2", "0.4", "0.2"]) class TestAreaPlot: @@ -250,289 +213,232 @@ class TestAreaPlot: """ def setup_method(self): - self.data = pd.DataFrame({ - 'category': ['a', 'a', 'b', 'b'], - 'upper': [20, 30, 2, 3], - 'lower': [10, 20, 1, 2], - 'x': [1, 2, 1, 2] - }) - self.data_missing = pd.DataFrame({ - 'category': ['a', 'a', 'b', 'b', 'a', 'c'], - 'upper': [20, 30, 2, 3, 40, 4], - 'lower': [10, 20, 1, 2, 25, 6], - 'x': [1, 2, 1, 2, 3, 3] - }) + self.data = pd.DataFrame( + {"category": ["a", "a", "b", "b"], "upper": [20, 30, 2, 3], "lower": [10, 20, 1, 2], "x": [1, 2, 1, 2]} + ) + self.data_missing = pd.DataFrame( + { + "category": ["a", "a", "b", "b", "a", "c"], + "upper": [20, 30, 2, 3, 40, 4], + "lower": [10, 20, 1, 2, 25, 6], + "x": [1, 2, 1, 2, 3, 3], + } + ) def test_single_series_zero_baseline(self): """Area plot tests""" - test_data = self.data.loc[lambda x: x['category'] == 'a'] + test_data = self.data.loc[lambda x: x["category"] == "a"] ch = chartify.Chart() - ch.plot.area(test_data, 'x', 'upper') - assert (np.array_equal(chart_data(ch, None)['x'], [1, 2, 2, 1])) - assert (np.array_equal( - chart_data(ch, None)['upper'], [20., 30., 0., 0.])) + ch.plot.area(test_data, "x", "upper") + assert np.array_equal(chart_data(ch, None)["x"], [1, 2, 2, 1]) + assert np.array_equal(chart_data(ch, None)["upper"], [20.0, 30.0, 0.0, 0.0]) def test_multi_series_zero_baseline_unstacked(self): """Area plot tests""" test_data = self.data ch = chartify.Chart() - ch.plot.area(test_data, 'x', 'upper', color_column='category') - assert (np.array_equal(chart_data(ch, 'a')['x'], [1, 2, 2, 1])) - assert (np.array_equal( - chart_data(ch, 'a')['upper'], [20., 30., 0., 0.])) + ch.plot.area(test_data, "x", "upper", color_column="category") + assert np.array_equal(chart_data(ch, "a")["x"], [1, 2, 2, 1]) + assert np.array_equal(chart_data(ch, "a")["upper"], [20.0, 30.0, 0.0, 0.0]) - assert (np.array_equal(chart_data(ch, 'b')['x'], [1, 2, 2, 1])) - assert (np.array_equal(chart_data(ch, 'b')['upper'], [2., 3., 0., 0.])) + assert np.array_equal(chart_data(ch, "b")["x"], [1, 2, 2, 1]) + assert np.array_equal(chart_data(ch, "b")["upper"], [2.0, 3.0, 0.0, 0.0]) def test_multi_series_zero_baseline_stacked(self): """Area plot tests""" test_data = self.data ch = chartify.Chart() - ch.plot.area( - test_data, 'x', 'upper', color_column='category', stacked=True) - assert (np.array_equal(chart_data(ch, 'a')['x'], [1, 2, 2, 1])) - assert (np.array_equal( - chart_data(ch, 'a')['upper'], [20., 30., 0., 0.])) + ch.plot.area(test_data, "x", "upper", color_column="category", stacked=True) + assert np.array_equal(chart_data(ch, "a")["x"], [1, 2, 2, 1]) + assert np.array_equal(chart_data(ch, "a")["upper"], [20.0, 30.0, 0.0, 0.0]) - assert (np.array_equal(chart_data(ch, 'b')['x'], [1, 2, 2, 1])) - assert (np.array_equal( - chart_data(ch, 'b')['upper'], [22., 33., 30., 20.])) + assert np.array_equal(chart_data(ch, "b")["x"], [1, 2, 2, 1]) + assert np.array_equal(chart_data(ch, "b")["upper"], [22.0, 33.0, 30.0, 20.0]) def test_single_series_interval(self): """Area plot tests""" - test_data = self.data.loc[lambda x: x['category'] == 'a'] + test_data = self.data.loc[lambda x: x["category"] == "a"] ch = chartify.Chart() - ch.plot.area(test_data, 'x', y_column='upper', second_y_column='lower') - assert (np.array_equal(chart_data(ch, None)['x'], [1, 2, 2, 1])) - assert (np.array_equal( - chart_data(ch, None)['upper'], [20., 30., 20., 10.])) + ch.plot.area(test_data, "x", y_column="upper", second_y_column="lower") + assert np.array_equal(chart_data(ch, None)["x"], [1, 2, 2, 1]) + assert np.array_equal(chart_data(ch, None)["upper"], [20.0, 30.0, 20.0, 10.0]) def test_multi_series_interval(self): """Area plot tests""" test_data = self.data ch = chartify.Chart() - ch.plot.area( - test_data, - 'x', - y_column='upper', - second_y_column='lower', - color_column='category') - assert (np.array_equal(chart_data(ch, 'a')['x'], [1, 2, 2, 1])) - assert (np.array_equal( - chart_data(ch, 'a')['upper'], [20., 30., 20., 10.])) - - assert (np.array_equal(chart_data(ch, 'b')['x'], [1, 2, 2, 1])) - assert (np.array_equal(chart_data(ch, 'b')['upper'], [2, 3, 2, 1])) + ch.plot.area(test_data, "x", y_column="upper", second_y_column="lower", color_column="category") + assert np.array_equal(chart_data(ch, "a")["x"], [1, 2, 2, 1]) + assert np.array_equal(chart_data(ch, "a")["upper"], [20.0, 30.0, 20.0, 10.0]) + + assert np.array_equal(chart_data(ch, "b")["x"], [1, 2, 2, 1]) + assert np.array_equal(chart_data(ch, "b")["upper"], [2, 3, 2, 1]) def test_multi_series_zero_baseline_unstacked_missing(self): """Area plot tests""" test_data = self.data_missing ch = chartify.Chart() - ch.plot.area(test_data, 'x', 'upper', color_column='category') - assert (np.array_equal(chart_data(ch, 'a')['x'], [1, 2, 3, 3, 2, 1])) - assert (np.array_equal( - chart_data(ch, 'a')['upper'], [20., 30., 40., 0., 0., 0.])) + ch.plot.area(test_data, "x", "upper", color_column="category") + assert np.array_equal(chart_data(ch, "a")["x"], [1, 2, 3, 3, 2, 1]) + assert np.array_equal(chart_data(ch, "a")["upper"], [20.0, 30.0, 40.0, 0.0, 0.0, 0.0]) - assert (np.array_equal(chart_data(ch, 'c')['x'], [1, 2, 3, 3, 2, 1])) - assert (np.array_equal( - chart_data(ch, 'c')['upper'], [0., 0., 4., 0., 0., 0.])) + assert np.array_equal(chart_data(ch, "c")["x"], [1, 2, 3, 3, 2, 1]) + assert np.array_equal(chart_data(ch, "c")["upper"], [0.0, 0.0, 4.0, 0.0, 0.0, 0.0]) def test_multi_series_zero_baseline_stacked_missing(self): """Area plot tests""" test_data = self.data_missing ch = chartify.Chart() - ch.plot.area( - test_data, 'x', 'upper', color_column='category', stacked=True) - assert (np.array_equal(chart_data(ch, 'a')['x'], [1, 2, 3, 3, 2, 1])) - assert (np.array_equal( - chart_data(ch, 'a')['upper'], [20., 30., 40., 0., 0., 0.])) + ch.plot.area(test_data, "x", "upper", color_column="category", stacked=True) + assert np.array_equal(chart_data(ch, "a")["x"], [1, 2, 3, 3, 2, 1]) + assert np.array_equal(chart_data(ch, "a")["upper"], [20.0, 30.0, 40.0, 0.0, 0.0, 0.0]) - assert (np.array_equal(chart_data(ch, 'c')['x'], [1, 2, 3, 3, 2, 1])) - assert (np.array_equal( - chart_data(ch, 'c')['upper'], [22., 33., 44., 40., 33., 22.])) + assert np.array_equal(chart_data(ch, "c")["x"], [1, 2, 3, 3, 2, 1]) + assert np.array_equal(chart_data(ch, "c")["upper"], [22.0, 33.0, 44.0, 40.0, 33.0, 22.0]) class TestBarLollipopParallel: """Tests for bar, lollipop, and parallel plots""" def setup_method(self): - self.data = pd.DataFrame({ - 'category1': ['a', 'b', 'a', 'b', 'a'], - 'category2': [1, 1, 2, 2, 3], - 'color': ['c', 'd', 'e', 'f', 'g'], - 'number': [5, 4, 10, -3, 0], - }) - self.plot_methods = ['bar', 'lollipop', 'parallel'] + self.data = pd.DataFrame( + { + "category1": ["a", "b", "a", "b", "a"], + "category2": [1, 1, 2, 2, 3], + "color": ["c", "d", "e", "f", "g"], + "number": [5, 4, 10, -3, 0], + } + ) + self.plot_methods = ["bar", "lollipop", "parallel"] def test_vertical(self): """Vertical test""" - sliced_data = self.data[self.data['category1'] == 'a'] + sliced_data = self.data[self.data["category1"] == "a"] for method_name in self.plot_methods: - ch = chartify.Chart(x_axis_type='categorical') + ch = chartify.Chart(x_axis_type="categorical") plot_method = getattr(ch.plot, method_name) - plot_method( - sliced_data, - categorical_columns='category2', - numeric_column='number') - assert (np.array_equal( - chart_data(ch, '')['factors'], ['2', '1', '3'])) - assert (np.array_equal(chart_data(ch, '')['number'], [10, 5, 0])) + plot_method(sliced_data, categorical_columns="category2", numeric_column="number") + assert np.array_equal(chart_data(ch, "")["factors"], ["2", "1", "3"]) + assert np.array_equal(chart_data(ch, "")["number"], [10, 5, 0]) def test_horizontal(self): """Horizontal test""" - sliced_data = self.data[self.data['category1'] == 'a'] + sliced_data = self.data[self.data["category1"] == "a"] for method_name in self.plot_methods: - ch = chartify.Chart(y_axis_type='categorical') + ch = chartify.Chart(y_axis_type="categorical") plot_method = getattr(ch.plot, method_name) - plot_method( - sliced_data, - categorical_columns='category2', - numeric_column='number') - assert (np.array_equal( - chart_data(ch, '')['factors'], ['2', '1', '3'])) - assert (np.array_equal(chart_data(ch, '')['number'], [10, 5, 0])) + plot_method(sliced_data, categorical_columns="category2", numeric_column="number") + assert np.array_equal(chart_data(ch, "")["factors"], ["2", "1", "3"]) + assert np.array_equal(chart_data(ch, "")["number"], [10, 5, 0]) def test_grouping_error(self): for method_name in self.plot_methods: - ch = chartify.Chart(x_axis_type='categorical') + ch = chartify.Chart(x_axis_type="categorical") plot_method = getattr(ch.plot, method_name) with pytest.raises(ValueError): - plot_method( - self.data, - categorical_columns='category2', - numeric_column='number') + plot_method(self.data, categorical_columns="category2", numeric_column="number") def test_grouped_categorical(self): """Grouped test""" for method_name in self.plot_methods: - ch = chartify.Chart(x_axis_type='categorical') + ch = chartify.Chart(x_axis_type="categorical") plot_method = getattr(ch.plot, method_name) - plot_method( - self.data, - categorical_columns=['category1', 'category2'], - numeric_column='number') - assert (np.array_equal( - chart_data(ch, '')['number'], [10, 5, 0, 4, -3])) + plot_method(self.data, categorical_columns=["category1", "category2"], numeric_column="number") + assert np.array_equal(chart_data(ch, "")["number"], [10, 5, 0, 4, -3]) multi_index = pd.MultiIndex( - levels=[['a', 'b'], ['1', '2', '3']], + levels=[["a", "b"], ["1", "2", "3"]], codes=[[0, 0, 0, 1, 1], [1, 0, 2, 0, 1]], - names=['category1', 'category2']) - assert (np.array_equal(chart_data(ch, '')['factors'], multi_index)) + names=["category1", "category2"], + ) + assert np.array_equal(chart_data(ch, "")["factors"], multi_index) - ch = chartify.Chart(x_axis_type='categorical') + ch = chartify.Chart(x_axis_type="categorical") plot_method = getattr(ch.plot, method_name) - plot_method( - self.data, - categorical_columns=['category2', 'category1'], - numeric_column='number') - assert (np.array_equal( - chart_data(ch, '')['number'], [5, 4, 10, -3, 0])) + plot_method(self.data, categorical_columns=["category2", "category1"], numeric_column="number") + assert np.array_equal(chart_data(ch, "")["number"], [5, 4, 10, -3, 0]) multi_index = pd.MultiIndex( - levels=[['1', '2', '3'], ['a', 'b']], + levels=[["1", "2", "3"], ["a", "b"]], codes=[[0, 0, 1, 1, 2], [0, 1, 0, 1, 0]], - names=['category2', 'category1']) - assert (np.array_equal(chart_data(ch, '')['factors'], multi_index)) + names=["category2", "category1"], + ) + assert np.array_equal(chart_data(ch, "")["factors"], multi_index) def test_bar_color_column(self): - sliced_data = self.data[self.data['category1'] == 'a'] - ch = chartify.Chart(x_axis_type='categorical') - ch.plot.bar( - sliced_data, - categorical_columns='category2', - numeric_column='number', - color_column='category2') + sliced_data = self.data[self.data["category1"] == "a"] + ch = chartify.Chart(x_axis_type="categorical") + ch.plot.bar(sliced_data, categorical_columns="category2", numeric_column="number", color_column="category2") if version.parse(bokeh.__version__) < version.parse("3.0"): - assert (np.array_equal( - chart_color_mapper(ch).factors, ['1', '2', '3'])) - assert (np.array_equal(chart_color_mapper(ch).palette, - ['#1f77b4', '#ff7f0e', '#2ca02c'])) + assert np.array_equal(chart_color_mapper(ch).factors, ["1", "2", "3"]) + assert np.array_equal(chart_color_mapper(ch).palette, ["#1f77b4", "#ff7f0e", "#2ca02c"]) return vbar_glyph = ch.figure.renderers[0].glyph - assert (np.array_equal( - vbar_glyph.fill_color.transform.factors, ['1', '2', '3'])) - assert (np.array_equal(vbar_glyph.fill_color.transform.palette, - ['#1f77b4', '#ff7f0e', '#2ca02c'])) - assert vbar_glyph.line_color == 'white' + assert np.array_equal(vbar_glyph.fill_color.transform.factors, ["1", "2", "3"]) + assert np.array_equal(vbar_glyph.fill_color.transform.palette, ["#1f77b4", "#ff7f0e", "#2ca02c"]) + assert vbar_glyph.line_color == "white" def test_lollipop_color_column(self): - sliced_data = self.data[self.data['category1'] == 'a'] - ch = chartify.Chart(x_axis_type='categorical') + sliced_data = self.data[self.data["category1"] == "a"] + ch = chartify.Chart(x_axis_type="categorical") ch.plot.lollipop( - sliced_data, - categorical_columns='category2', - numeric_column='number', - color_column='category2') + sliced_data, categorical_columns="category2", numeric_column="number", color_column="category2" + ) if version.parse(bokeh.__version__) < version.parse("3.0"): - assert (np.array_equal( - chart_color_mapper(ch).factors, ['1', '2', '3'])) - assert (np.array_equal(chart_color_mapper(ch).palette, - ['#1f77b4', '#ff7f0e', '#2ca02c'])) + assert np.array_equal(chart_color_mapper(ch).factors, ["1", "2", "3"]) + assert np.array_equal(chart_color_mapper(ch).palette, ["#1f77b4", "#ff7f0e", "#2ca02c"]) return segment_glyph = ch.figure.renderers[0].glyph circle_glyph = ch.figure.renderers[1].glyph # check segment colors - assert (np.array_equal( - segment_glyph.line_color.transform.factors, ['1', '2', '3'])) - assert (np.array_equal(segment_glyph.line_color.transform.palette, - ['#1f77b4', '#ff7f0e', '#2ca02c'])) + assert np.array_equal(segment_glyph.line_color.transform.factors, ["1", "2", "3"]) + assert np.array_equal(segment_glyph.line_color.transform.palette, ["#1f77b4", "#ff7f0e", "#2ca02c"]) # check circle colors - assert (np.array_equal( - circle_glyph.line_color.transform.factors, ['1', '2', '3'])) - assert (np.array_equal(circle_glyph.line_color.transform.palette, - ['#1f77b4', '#ff7f0e', '#2ca02c'])) - assert (np.array_equal( - circle_glyph.fill_color.transform.factors, ['1', '2', '3'])) - assert (np.array_equal(circle_glyph.fill_color.transform.palette, - ['#1f77b4', '#ff7f0e', '#2ca02c'])) + assert np.array_equal(circle_glyph.line_color.transform.factors, ["1", "2", "3"]) + assert np.array_equal(circle_glyph.line_color.transform.palette, ["#1f77b4", "#ff7f0e", "#2ca02c"]) + assert np.array_equal(circle_glyph.fill_color.transform.factors, ["1", "2", "3"]) + assert np.array_equal(circle_glyph.fill_color.transform.palette, ["#1f77b4", "#ff7f0e", "#2ca02c"]) def test_bar_parallel_color_column(self): - ch = chartify.Chart(x_axis_type='categorical') - ch.plot.parallel( - self.data, - categorical_columns='category1', - numeric_column='number', - color_column='category2') - assert (np.array_equal(chart_data(ch, '')['factors'], ['a', 'b'])) - assert (np.array_equal(chart_data(ch, '')['1'], [5, 4])) - assert (np.array_equal(chart_data(ch, '')['2'], [10, -3])) - assert (np.array_equal(chart_data(ch, '')['3'], [0, 0])) + ch = chartify.Chart(x_axis_type="categorical") + ch.plot.parallel(self.data, categorical_columns="category1", numeric_column="number", color_column="category2") + assert np.array_equal(chart_data(ch, "")["factors"], ["a", "b"]) + assert np.array_equal(chart_data(ch, "")["1"], [5, 4]) + assert np.array_equal(chart_data(ch, "")["2"], [10, -3]) + assert np.array_equal(chart_data(ch, "")["3"], [0, 0]) def test_bar_color(self): - ch = chartify.Chart(blank_labels=True, x_axis_type='categorical') + ch = chartify.Chart(blank_labels=True, x_axis_type="categorical") ch.plot.bar( data_frame=self.data, - categorical_columns=['category1', 'category2'], - numeric_column='number', - color_column='color') - assert np.array_equal( - ch.data[0]['color_column'], ['e', 'c', 'g', 'd', 'f']) + categorical_columns=["category1", "category2"], + numeric_column="number", + color_column="color", + ) + assert np.array_equal(ch.data[0]["color_column"], ["e", "c", "g", "d", "f"]) class TestBarNumericSort: def setup_method(self): - self.data = pd.DataFrame({ - 'category': ['a', 'a', 'b', 'b', 'a', 'c'], - 'upper': [20, 30, 2, 3, 40, 4], - 'lower': [10, 20, 1, 2, 25, 6], - 'x': [1, 2, 1, 2, 11, 10] - }) + self.data = pd.DataFrame( + { + "category": ["a", "a", "b", "b", "a", "c"], + "upper": [20, 30, 2, 3, 40, 4], + "lower": [10, 20, 1, 2, 25, 6], + "x": [1, 2, 1, 2, 11, 10], + } + ) def test_bar_sort(self): - ch = chartify.Chart(x_axis_type='categorical') - ch.plot.bar(self.data, - ['x', 'category'], - 'upper', - categorical_order_by='labels', - categorical_order_ascending=True) - assert (np.array_equal( - chart_data(ch, '')['upper'], [20, 2, 30, 3, 4, 40])) - assert (np.array_equal( - chart_data(ch, '')['index'], [0, 1, 2, 3, 4, 5])) + ch = chartify.Chart(x_axis_type="categorical") + ch.plot.bar( + self.data, ["x", "category"], "upper", categorical_order_by="labels", categorical_order_ascending=True + ) + assert np.array_equal(chart_data(ch, "")["upper"], [20, 2, 30, 3, 4, 40]) + assert np.array_equal(chart_data(ch, "")["index"], [0, 1, 2, 3, 4, 5]) class TestBoxplot: @@ -545,151 +451,125 @@ def _assert_grouped_chart_data(self, chart_data): # loop because the order of elements varies for i in range(3): # q2-q3 boxes - if 'q2' in clean_data[i] and 'q3' in clean_data[i]: + if "q2" in clean_data[i] and "q3" in clean_data[i]: multi_index = pd.MultiIndex.from_tuples( - [('a', 'd'), ('a', 'e'), ('b', 'd'), ('c', 'e')], - names=('category', 'sub-category')) - - assert clean_data[i]['factors'].equals(multi_index) - assert clean_data[i]['factors'].equal_levels(multi_index) - assert np.array_equal(clean_data[i]['q3'], - [46, 205.25, 79, 98.5]) - assert np.array_equal(clean_data[i]['q2'], - [35, 184, 68, 79.5]) + [("a", "d"), ("a", "e"), ("b", "d"), ("c", "e")], names=("category", "sub-category") + ) + + assert clean_data[i]["factors"].equals(multi_index) + assert clean_data[i]["factors"].equal_levels(multi_index) + assert np.array_equal(clean_data[i]["q3"], [46, 205.25, 79, 98.5]) + assert np.array_equal(clean_data[i]["q2"], [35, 184, 68, 79.5]) # q1-q2 boxes - elif 'q1' in clean_data[i] and 'q2' in clean_data[i]: + elif "q1" in clean_data[i] and "q2" in clean_data[i]: multi_index = pd.MultiIndex.from_tuples( - [('a', 'd'), ('a', 'e'), ('b', 'd'), ('c', 'e')], - names=('category', 'sub-category')) - assert clean_data[i]['factors'].equals(multi_index) - assert clean_data[i]['factors'].equal_levels(multi_index) - assert np.array_equal(clean_data[i]['q2'], - [35, 184, 68, 79.5]) - assert np.array_equal(clean_data[i]['q1'], - [23, 123.5, 58, 55.75]) + [("a", "d"), ("a", "e"), ("b", "d"), ("c", "e")], names=("category", "sub-category") + ) + assert clean_data[i]["factors"].equals(multi_index) + assert clean_data[i]["factors"].equal_levels(multi_index) + assert np.array_equal(clean_data[i]["q2"], [35, 184, 68, 79.5]) + assert np.array_equal(clean_data[i]["q1"], [23, 123.5, 58, 55.75]) # outliers - elif 'numeric' in clean_data[i]: + elif "numeric" in clean_data[i]: multi_index = pd.MultiIndex.from_tuples( - [('a', 'd'), ('b', 'd'), ('b', 'd'), - ('b', 'd'), ('c', 'e'), ('c', 'e')], - names=('category', 'sub-category')) - assert clean_data[i]['factors'].equals(multi_index) - assert clean_data[i]['factors'].equal_levels(multi_index) - assert np.array_equal(clean_data[i]['numeric'], [120, 15, 20, 130, -20, 170]) + [("a", "d"), ("b", "d"), ("b", "d"), ("b", "d"), ("c", "e"), ("c", "e")], + names=("category", "sub-category"), + ) + assert clean_data[i]["factors"].equals(multi_index) + assert clean_data[i]["factors"].equal_levels(multi_index) + assert np.array_equal(clean_data[i]["numeric"], [120, 15, 20, 130, -20, 170]) def setup_method(self): np.random.seed(10) random_series_1 = pd.Series(list(np.random.randint(10, 60, 50)) + [120]) - random_series_2 = pd.Series( - list(np.random.randint(40, 200, 50)) + list(np.random.randint(180, 225, 50)) - ) - df1 = pd.DataFrame({'category': 'a', - 'sub-category': 'd', - 'numeric': random_series_1.values}) - df2 = pd.DataFrame({'category': 'a', - 'sub-category': 'e', - 'numeric': random_series_2.values}) - - random_series_3 = pd.Series( - list(np.random.randint(50, 90, 50)) + [15, 20, 130]) - df3 = pd.DataFrame({'category': 'b', - 'sub-category': 'd', - 'numeric': random_series_3.values}) - - random_series_4 = pd.Series( - list(np.random.randint(40, 120, 50)) + [-20, 170]) - df4 = pd.DataFrame({'category': 'c', - 'sub-category': 'e', - 'numeric': random_series_4.values}) + random_series_2 = pd.Series(list(np.random.randint(40, 200, 50)) + list(np.random.randint(180, 225, 50))) + df1 = pd.DataFrame({"category": "a", "sub-category": "d", "numeric": random_series_1.values}) + df2 = pd.DataFrame({"category": "a", "sub-category": "e", "numeric": random_series_2.values}) + + random_series_3 = pd.Series(list(np.random.randint(50, 90, 50)) + [15, 20, 130]) + df3 = pd.DataFrame({"category": "b", "sub-category": "d", "numeric": random_series_3.values}) + + random_series_4 = pd.Series(list(np.random.randint(40, 120, 50)) + [-20, 170]) + df4 = pd.DataFrame({"category": "c", "sub-category": "e", "numeric": random_series_4.values}) self.data = pd.concat([df1, df2, df3, df4]) def test_default(self): - ch = chartify.Chart(x_axis_type='categorical') - ch.plot.boxplot(self.data, ['category'], 'numeric') + ch = chartify.Chart(x_axis_type="categorical") + ch.plot.boxplot(self.data, ["category"], "numeric") clean_data = self._clean_data(ch.data) # loop because the order of elements varies for i in range(3): # q2-q3 boxes - if 'q2' in clean_data[i] and 'q3' in clean_data[i]: - assert clean_data[i]['factors'].equals( - pd.Index(['a', 'b', 'c'], name='category')) - assert np.array_equal(clean_data[i]['q3'], [196, 79, 98.5]) - assert np.array_equal(clean_data[i]['q2'], [122, 68, 79.5]) + if "q2" in clean_data[i] and "q3" in clean_data[i]: + assert clean_data[i]["factors"].equals(pd.Index(["a", "b", "c"], name="category")) + assert np.array_equal(clean_data[i]["q3"], [196, 79, 98.5]) + assert np.array_equal(clean_data[i]["q2"], [122, 68, 79.5]) # q1-q2 boxes - elif 'q1' in clean_data[i] and 'q2' in clean_data[i]: - assert clean_data[i]['factors'].equals( - pd.Index(['a', 'b', 'c'], name='category')) - assert np.array_equal(clean_data[i]['q2'], - [122, 68, 79.5]) - assert np.array_equal(clean_data[i]['q1'], - [43.5, 58, 55.75]) + elif "q1" in clean_data[i] and "q2" in clean_data[i]: + assert clean_data[i]["factors"].equals(pd.Index(["a", "b", "c"], name="category")) + assert np.array_equal(clean_data[i]["q2"], [122, 68, 79.5]) + assert np.array_equal(clean_data[i]["q1"], [43.5, 58, 55.75]) # outliers - elif 'numeric' in clean_data[i]: - assert clean_data[i]['factors'].equals( - pd.Index(['b', 'b', 'b', 'c', 'c'], name='category')) - assert np.array_equal(clean_data[i]['numeric'], - [15, 20, 130, -20, 170]) + elif "numeric" in clean_data[i]: + assert clean_data[i]["factors"].equals(pd.Index(["b", "b", "b", "c", "c"], name="category")) + assert np.array_equal(clean_data[i]["numeric"], [15, 20, 130, -20, 170]) def test_grouped_vertical(self): - ch = chartify.Chart(x_axis_type='categorical', y_axis_type='linear') - ch.plot.boxplot(self.data, - ['category', 'sub-category'], - 'numeric', - color_column='category', - categorical_order_by='labels') + ch = chartify.Chart(x_axis_type="categorical", y_axis_type="linear") + ch.plot.boxplot( + self.data, ["category", "sub-category"], "numeric", color_column="category", categorical_order_by="labels" + ) self._assert_grouped_chart_data(ch.data) def test_grouped_horizontal(self): - ch = chartify.Chart(x_axis_type='linear', y_axis_type='categorical') - ch.plot.boxplot(self.data, - ['category', 'sub-category'], - 'numeric', - color_column='category', - categorical_order_by='labels') + ch = chartify.Chart(x_axis_type="linear", y_axis_type="categorical") + ch.plot.boxplot( + self.data, ["category", "sub-category"], "numeric", color_column="category", categorical_order_by="labels" + ) self._assert_grouped_chart_data(ch.data) def test_color(self): - ch = chartify.Chart(x_axis_type='categorical') - ch.plot.boxplot(self.data, - ['category', 'sub-category'], - 'numeric', - color_column='sub-category', - categorical_order_by='labels') + ch = chartify.Chart(x_axis_type="categorical") + ch.plot.boxplot( + self.data, + ["category", "sub-category"], + "numeric", + color_column="sub-category", + categorical_order_by="labels", + ) self._assert_grouped_chart_data(ch.data) clean_data = self._clean_data(ch.data) for i in range(3): - if 'q2' in clean_data[i] and 'q3' in clean_data[i]: - assert np.array_equal(clean_data[i]['color_column'], - ['d', 'e', 'd', 'e']) - elif 'q1' in clean_data[i] and 'q2' in clean_data[i]: - assert np.array_equal(clean_data[i]['color_column'], - ['d', 'e', 'd', 'e']) + if "q2" in clean_data[i] and "q3" in clean_data[i]: + assert np.array_equal(clean_data[i]["color_column"], ["d", "e", "d", "e"]) + elif "q1" in clean_data[i] and "q2" in clean_data[i]: + assert np.array_equal(clean_data[i]["color_column"], ["d", "e", "d", "e"]) def test_error(self): - ch = chartify.Chart(x_axis_type='categorical') + ch = chartify.Chart(x_axis_type="categorical") with pytest.raises(ValueError): - ch.plot.boxplot(self.data, ['category'], 'numeric', - categorical_order_by='count') + ch.plot.boxplot(self.data, ["category"], "numeric", categorical_order_by="count") class TestBarStacked: """Tests for stacked bar plots""" def setup_method(self): - self.data = pd.DataFrame({ - 'category1': ['a', 'b', 'a', 'b', 'a'], - 'category2': [1, 1, 2, 2, 3], - 'number': [5, 4, 10, -3, 0], - }) + self.data = pd.DataFrame( + { + "category1": ["a", "b", "a", "b", "a"], + "category2": [1, 1, 2, 2, 3], + "number": [5, 4, 10, -3, 0], + } + ) class TestAxisFormatPrecision: - def setup_method(self): self.tests = { (0, 0): "0,0.[0]", @@ -714,186 +594,164 @@ def setup_method(self): def test_axis_format_precision(self): ch = chartify.Chart() for parameters, value in self.tests.items(): - assert (ch.plot._axis_format_precision(parameters[0], - parameters[1]) == value) + assert ch.plot._axis_format_precision(parameters[0], parameters[1]) == value class TestHexbin: def setup_method(self): n_samples = 2000 np.random.seed(10) - x_values = 2 + .5 * np.random.standard_normal(n_samples) - y_values = 1 + .5 * np.random.standard_normal(n_samples) - data = pd.DataFrame({'x': x_values, 'y': y_values}) + x_values = 2 + 0.5 * np.random.standard_normal(n_samples) + y_values = 1 + 0.5 * np.random.standard_normal(n_samples) + data = pd.DataFrame({"x": x_values, "y": y_values}) self.data = data def test_hexbin(self): ch = chartify.Chart( - x_axis_type='density', - y_axis_type='density', - layout='slide_100%', + x_axis_type="density", + y_axis_type="density", + layout="slide_100%", ) - ch.plot.hexbin(self.data, 'x', 'y', .5, orientation='flattop') - assert (ch.data[0]['r'].tolist() == [ - -2, -1, -2, -1, -3, -2, -1, -3, -2, -4, -3 - ]) - assert (ch.data[0]['q'].tolist() == [ - 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5 - ]) - assert (ch.data[0]['c'].tolist() == [ - 13, 75, 485, 232, 126, 851, 27, 123, 64, 1, 3 - ]) + ch.plot.hexbin(self.data, "x", "y", 0.5, orientation="flattop") + assert ch.data[0]["r"].tolist() == [-2, -1, -2, -1, -3, -2, -1, -3, -2, -4, -3] + assert ch.data[0]["q"].tolist() == [1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5] + assert ch.data[0]["c"].tolist() == [13, 75, 485, 232, 126, 851, 27, 123, 64, 1, 3] ch = chartify.Chart( - x_axis_type='density', - y_axis_type='density', - layout='slide_50%', + x_axis_type="density", + y_axis_type="density", + layout="slide_50%", ) - ch.plot.hexbin(self.data, 'x', 'y', 1, orientation='flattop') - assert (ch.data[0]['r'].tolist() == [ - -1, 0, -2, -1, 0, -3, -2, -1 - ]) - assert (ch.data[0]['q'].tolist() == [ - 0, 0, 1, 1, 1, 2, 2, 2 - ]) - assert (ch.data[0]['c'].tolist() == [ - 11, 3, 180, 1181, 32, 2, 391, 200 - ]) + ch.plot.hexbin(self.data, "x", "y", 1, orientation="flattop") + assert ch.data[0]["r"].tolist() == [-1, 0, -2, -1, 0, -3, -2, -1] + assert ch.data[0]["q"].tolist() == [0, 0, 1, 1, 1, 2, 2, 2] + assert ch.data[0]["c"].tolist() == [11, 3, 180, 1181, 32, 2, 391, 200] class TestHistogram: def setup_method(self): - self.data = pd.DataFrame({ - 'values': [0, 4, 8, 22, 2, 2, 10], - 'dimension': ['a', 'a', 'a', 'a', 'b', 'b', 'b'] - }) + self.data = pd.DataFrame({"values": [0, 4, 8, 22, 2, 2, 10], "dimension": ["a", "a", "a", "a", "b", "b", "b"]}) def test_histogram(self): """No groupings.""" - ch = chartify.Chart(y_axis_type='density') - ch.plot.histogram(self.data, 'values', bins=2, method='count') - assert (np.array_equal(chart_data(ch, '')['values'], [6, 1])) - assert (np.array_equal(chart_data(ch, '')['max_edge'], [11., 22.])) - assert (np.array_equal(chart_data(ch, '')['min_edge'], [0., 11.])) + ch = chartify.Chart(y_axis_type="density") + ch.plot.histogram(self.data, "values", bins=2, method="count") + assert np.array_equal(chart_data(ch, "")["values"], [6, 1]) + assert np.array_equal(chart_data(ch, "")["max_edge"], [11.0, 22.0]) + assert np.array_equal(chart_data(ch, "")["min_edge"], [0.0, 11.0]) def test_grouped_histogram(self): """Grouped histogram.""" - ch = chartify.Chart(y_axis_type='density') - ch.plot.histogram( - self.data, - values_column='values', - color_column='dimension', - bins=2, - method='count') - assert (np.array_equal(chart_data(ch, 'a')['values'], [3, 1])) - assert (np.array_equal(chart_data(ch, 'a')['max_edge'], [11., 22.])) - assert (np.array_equal(chart_data(ch, 'a')['min_edge'], [0., 11.])) + ch = chartify.Chart(y_axis_type="density") + ch.plot.histogram(self.data, values_column="values", color_column="dimension", bins=2, method="count") + assert np.array_equal(chart_data(ch, "a")["values"], [3, 1]) + assert np.array_equal(chart_data(ch, "a")["max_edge"], [11.0, 22.0]) + assert np.array_equal(chart_data(ch, "a")["min_edge"], [0.0, 11.0]) - assert (np.array_equal(chart_data(ch, 'b')['values'], [2, 1])) - assert (np.array_equal(chart_data(ch, 'b')['max_edge'], [6., 10.])) - assert (np.array_equal(chart_data(ch, 'b')['min_edge'], [2., 6.])) + assert np.array_equal(chart_data(ch, "b")["values"], [2, 1]) + assert np.array_equal(chart_data(ch, "b")["max_edge"], [6.0, 10.0]) + assert np.array_equal(chart_data(ch, "b")["min_edge"], [2.0, 6.0]) class TestCategoricalOrderBy: def _assert_order_by_array_like(self, chart): - assert (np.array_equal(chart.figure.x_range.factors, ['b', 'd', 'a', 'c'])) + assert np.array_equal(chart.figure.x_range.factors, ["b", "d", "a", "c"]) # check bar data - assert (np.array_equal(chart_data(chart, '')['factors'], ['b', 'd', 'a', 'c'])) - assert (np.array_equal(chart_data(chart, '')['number1'], [3, 1, 4, 2])) + assert np.array_equal(chart_data(chart, "")["factors"], ["b", "d", "a", "c"]) + assert np.array_equal(chart_data(chart, "")["number1"], [3, 1, 4, 2]) # check scatter data - assert (np.array_equal(chart_data(chart, 'number1')['factors'], ['a', 'b', 'c', 'd'])) - assert (np.array_equal(chart_data(chart, 'number1')['number1'], [4, 3, 2, 1])) + assert np.array_equal(chart_data(chart, "number1")["factors"], ["a", "b", "c", "d"]) + assert np.array_equal(chart_data(chart, "number1")["number1"], [4, 3, 2, 1]) def setup_method(self): - self.data1 = pd.DataFrame({ - 'category1': ['a', 'b', 'c', 'd'], - 'number1': [4, 3, 2, 1], - }) + self.data1 = pd.DataFrame( + { + "category1": ["a", "b", "c", "d"], + "number1": [4, 3, 2, 1], + } + ) - self.data2 = pd.DataFrame({ - 'category2': ['b', 'a', 'b', 'b', 'a', 'c'], - 'number2': [1, 2, 3, 4, 5, 6] - }) + self.data2 = pd.DataFrame({"category2": ["b", "a", "b", "b", "a", "c"], "number2": [1, 2, 3, 4, 5, 6]}) def test_order_by_labels(self): - ch = chartify.Chart(x_axis_type='categorical') + ch = chartify.Chart(x_axis_type="categorical") - ch.plot.bar(self.data1, ['category1'], 'number1', categorical_order_by='labels') - assert (np.array_equal(ch.figure.x_range.factors, ['d', 'c', 'b', 'a'])) - assert (np.array_equal(chart_data(ch, '')['factors'], ['d', 'c', 'b', 'a'])) - assert (np.array_equal(chart_data(ch, '')['number1'], [1, 2, 3, 4])) + ch.plot.bar(self.data1, ["category1"], "number1", categorical_order_by="labels") + assert np.array_equal(ch.figure.x_range.factors, ["d", "c", "b", "a"]) + assert np.array_equal(chart_data(ch, "")["factors"], ["d", "c", "b", "a"]) + assert np.array_equal(chart_data(ch, "")["number1"], [1, 2, 3, 4]) - ch.plot.scatter(self.data1, ['category1'], 'number1', categorical_order_by='labels') - assert (np.array_equal(ch.figure.x_range.factors, ['d', 'c', 'b', 'a'])) - assert (np.array_equal(chart_data(ch, 'number1')['factors'], ['a', 'b', 'c', 'd'])) - assert (np.array_equal(chart_data(ch, 'number1')['number1'], [4, 3, 2, 1])) + ch.plot.scatter(self.data1, ["category1"], "number1", categorical_order_by="labels") + assert np.array_equal(ch.figure.x_range.factors, ["d", "c", "b", "a"]) + assert np.array_equal(chart_data(ch, "number1")["factors"], ["a", "b", "c", "d"]) + assert np.array_equal(chart_data(ch, "number1")["number1"], [4, 3, 2, 1]) def test_order_by_values(self): - ch = chartify.Chart(x_axis_type='categorical') - ch.plot.bar(self.data1, ['category1'], 'number1', categorical_order_by='values') - assert (np.array_equal(chart_data(ch, '')['factors'], ['a', 'b', 'c', 'd'])) - assert (np.array_equal(chart_data(ch, '')['number1'], [4, 3, 2, 1])) + ch = chartify.Chart(x_axis_type="categorical") + ch.plot.bar(self.data1, ["category1"], "number1", categorical_order_by="values") + assert np.array_equal(chart_data(ch, "")["factors"], ["a", "b", "c", "d"]) + assert np.array_equal(chart_data(ch, "")["number1"], [4, 3, 2, 1]) def test_order_by_count(self): - ch = chartify.Chart(x_axis_type='categorical') - ch.plot.scatter(self.data2, ['category2'], 'number2', categorical_order_by='count') + ch = chartify.Chart(x_axis_type="categorical") + ch.plot.scatter(self.data2, ["category2"], "number2", categorical_order_by="count") - assert (np.array_equal(ch.figure.x_range.factors, ['b', 'a', 'c'])) - assert (np.array_equal(chart_data(ch, 'number2')['factors'], ['b', 'a', 'b', 'b', 'a', 'c'])) - assert (np.array_equal(chart_data(ch, 'number2')['number2'], [1, 2, 3, 4, 5, 6])) + assert np.array_equal(ch.figure.x_range.factors, ["b", "a", "c"]) + assert np.array_equal(chart_data(ch, "number2")["factors"], ["b", "a", "b", "b", "a", "c"]) + assert np.array_equal(chart_data(ch, "number2")["number2"], [1, 2, 3, 4, 5, 6]) @pytest.mark.parametrize( - 'array_like', [['b', 'd', 'a', 'c'], np.array(['b', 'd', 'a', 'c']), pd.Series(['b', 'd', 'a', 'c'])]) + "array_like", [["b", "d", "a", "c"], np.array(["b", "d", "a", "c"]), pd.Series(["b", "d", "a", "c"])] + ) def test_order_by_array_like(self, array_like): - ch = chartify.Chart(x_axis_type='categorical') - ch.plot.scatter(self.data1, ['category1'], 'number1', categorical_order_by=array_like) - ch.plot.bar(self.data1, ['category1'], 'number1', categorical_order_by=array_like) + ch = chartify.Chart(x_axis_type="categorical") + ch.plot.scatter(self.data1, ["category1"], "number1", categorical_order_by=array_like) + ch.plot.bar(self.data1, ["category1"], "number1", categorical_order_by=array_like) self._assert_order_by_array_like(ch) - @pytest.mark.parametrize('plot_method,categorical_order_by', [('bar', 'count'), ('scatter', 'values')]) + @pytest.mark.parametrize("plot_method,categorical_order_by", [("bar", "count"), ("scatter", "values")]) def test_error(self, plot_method, categorical_order_by): - ch = chartify.Chart(x_axis_type='categorical', y_axis_type='linear') + ch = chartify.Chart(x_axis_type="categorical", y_axis_type="linear") with pytest.raises(ValueError): plot_method = getattr(ch.plot, plot_method) - plot_method(self.data1, ['category1'], 'number1', categorical_order_by=categorical_order_by) + plot_method(self.data1, ["category1"], "number1", categorical_order_by=categorical_order_by) def test_categorical_axis_type_casting(): """Categorical axis plotting breaks for non-str types. Test that type casting is performed correctly""" - test_df = pd.DataFrame({ - 'categorical_strings': ['a', 'a', 'c', 'd'], - 'categorical_integers': [1, 2, 3, 3], - 'categorical_floats': [1.1, 2.1, 3.3, 4.4], - 'numeric': [1, 2, 3, 4] - }) + test_df = pd.DataFrame( + { + "categorical_strings": ["a", "a", "c", "d"], + "categorical_integers": [1, 2, 3, 3], + "categorical_floats": [1.1, 2.1, 3.3, 4.4], + "numeric": [1, 2, 3, 4], + } + ) # Multi factor test - ch = chartify.Chart(blank_labels=True, x_axis_type='categorical') - ch.plot.bar( - test_df, - categorical_columns=['categorical_strings', 'categorical_integers'], - numeric_column='numeric') + ch = chartify.Chart(blank_labels=True, x_axis_type="categorical") + ch.plot.bar(test_df, categorical_columns=["categorical_strings", "categorical_integers"], numeric_column="numeric") # Single factor test - ch = chartify.Chart(blank_labels=True, y_axis_type='categorical') - ch.plot.bar(test_df, 'categorical_floats', 'numeric') + ch = chartify.Chart(blank_labels=True, y_axis_type="categorical") + ch.plot.bar(test_df, "categorical_floats", "numeric") # Stacked bar test - ch = chartify.Chart(blank_labels=True, x_axis_type='categorical') - ch.plot.bar_stacked(test_df, 'categorical_strings', 'numeric', - 'categorical_floats') + ch = chartify.Chart(blank_labels=True, x_axis_type="categorical") + ch.plot.bar_stacked(test_df, "categorical_strings", "numeric", "categorical_floats") # Color test - ch = chartify.Chart(blank_labels=True, x_axis_type='categorical') + ch = chartify.Chart(blank_labels=True, x_axis_type="categorical") ch.plot.bar( test_df, - categorical_columns=['categorical_strings', 'categorical_integers'], - numeric_column='numeric', - color_column='categorical_integers') + categorical_columns=["categorical_strings", "categorical_integers"], + numeric_column="numeric", + color_column="categorical_integers", + ) # Test that original data frame dtypes are not overwritten. - assert (test_df.dtypes['categorical_integers'] == 'int64') - assert (test_df.dtypes['categorical_floats'] == 'float64') + assert test_df.dtypes["categorical_integers"] == "int64" + assert test_df.dtypes["categorical_floats"] == "float64" diff --git a/tests/test_style_settings_config.py b/tests/test_style_settings_config.py index f7f2b89..2b92e62 100644 --- a/tests/test_style_settings_config.py +++ b/tests/test_style_settings_config.py @@ -17,32 +17,34 @@ import importlib import os -STYLE_SETTINGS_CONFIG = '''\ +STYLE_SETTINGS_CONFIG = """\ foo: baz.bar: 0.25 quux: deadbeef bar: baz: bar quux -''' +""" def test_style_settings_config(monkeypatch, tmpdir): - f = tmpdir.join('style_settings_config.yaml') + f = tmpdir.join("style_settings_config.yaml") f.write(STYLE_SETTINGS_CONFIG) # XXX (dano): CHARTIFY_CONFIG_DIR must end with / - monkeypatch.setenv('CHARTIFY_CONFIG_DIR', os.path.join(str(tmpdir), '')) + monkeypatch.setenv("CHARTIFY_CONFIG_DIR", os.path.join(str(tmpdir), "")) # reload modules to reload configuration import chartify._core.options import chartify._core.style + importlib.reload(chartify._core.options) importlib.reload(chartify._core.style) # Check that the expected style is loaded - style = chartify._core.style.Style(None, '') + style = chartify._core.style.Style(None, "") import yaml + expected_settings = yaml.safe_load(STYLE_SETTINGS_CONFIG) for key, expected_value in expected_settings.items():